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.17.0: bundled SDK update, dashboard tiles that show, relationship identity, import resend, a whole-run throttle budget, a token guard (#757)
Akshay Maloo8f7e777e00e0
diff --git a/.github/workflows/model-apps-agent-evals.yml b/.github/workflows/model-apps-agent-evals.ymlindex 1a1cb4744..375d9e664 100644--- a/.github/workflows/model-apps-agent-evals.yml+++ b/.github/workflows/model-apps-agent-evals.yml@@ -4,7 +4,7 @@# Why this is NOT part of model-apps-script-tests.yml (the per-PR gate):# * it is non-deterministic (graded as a pass RATE over several trials), so it must not be a# hard merge gate;-# * it costs real model usage (~1 turn per trial; 20 cases x 3 trials per full run), billed to+# * it costs real model usage (~1 turn per trial; 35 cases x 3 trials per full run), billed to# the organization;# * fork PRs cannot be given Copilot request rights, so a required check would block outside# contributions.diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.ymlindex aeb7d3d37..bc869248c 100644--- a/.github/workflows/model-apps-script-tests.yml+++ b/.github/workflows/model-apps-script-tests.yml@@ -33,6 +33,7 @@ on:- "scripts/validate-plugin-copies.js"- "plugins/pcf/scripts/lib/process-runner.js"- "plugins/pcf/scripts/lib/sdk-http-client.js"+ - "plugins/pcf/scripts/lib/output-redaction.js"- "plugins/pcf/scripts/lib/odata.js"- "plugins/pcf/scripts/lib/source-literals.js"- "plugins/pcf/scripts/lib/interaction-mode.js"diff --git a/.github/workflows/pcf-projects.yml b/.github/workflows/pcf-projects.ymlindex 40b53237a..940d5b4b9 100644--- a/.github/workflows/pcf-projects.yml+++ b/.github/workflows/pcf-projects.yml@@ -25,6 +25,7 @@ on:- "plugins/pcf/scripts/lib/cli-failure.js"- "plugins/pcf/scripts/lib/dataverse-auth.js"- "plugins/pcf/scripts/lib/nearest-name.js"+ - "plugins/pcf/scripts/lib/output-redaction.js"- "plugins/pcf/scripts/lib/sdk-http-client.js"- "plugins/pcf/scripts/lib/source-literals.js"- "plugins/pcf/scripts/lib/xml-lite.js"diff --git a/.github/workflows/pcf-script-tests.yml b/.github/workflows/pcf-script-tests.ymlindex e49188410..cbbdb719a 100644--- a/.github/workflows/pcf-script-tests.yml+++ b/.github/workflows/pcf-script-tests.yml@@ -16,6 +16,7 @@ on:- "scripts/validate-plugin-copies.js"- "plugins/model-apps/scripts/lib/process-runner.js"- "plugins/model-apps/scripts/lib/sdk-http-client.js"+ - "plugins/model-apps/scripts/lib/output-redaction.js"- "plugins/model-apps/scripts/lib/odata.js"- "plugins/model-apps/scripts/lib/source-literals.js"- "plugins/model-apps/scripts/lib/interaction-mode.js"diff --git a/evals/model-apps/routing/EVAL_GUIDE.md b/evals/model-apps/routing/EVAL_GUIDE.mdindex 98fcb2cd7..c658015b5 100644--- a/evals/model-apps/routing/EVAL_GUIDE.md+++ b/evals/model-apps/routing/EVAL_GUIDE.md@@ -24,15 +24,20 @@ instead" and back), so a wording change to one can silently start stealing the o| Field | Meaning ||-------|---------|-| `expect` | The model-apps skill the agent must invoke **first** — `genpage`, `app-builder`, `report-issue`, `telemetry` — or `null` for "none of them" (a negative / bleed case) |+| `expect` | The model-apps skill the agent must invoke **first**, at any turn (see [What counts as the decision](#what-counts-as-the-decision)) — `genpage`, `app-builder`, `report-issue`, `telemetry` — or `null` for "none of them" (a negative / bleed case) || `accept` | Optional other outcomes that are also correct, for a genuinely ambiguous prompt. `null` is never implied: "ambiguous" does not mean "anything goes" || `trap` | Optional. The mis-route the case exists to catch; printed when the case fails || `tier` | `smoke` / `full` / `stress`, as in the other suites |-The 20 committed cases cover: positives for every skill; the `/genpage` ↔ `/app-builder` boundary+The 35 committed cases cover: positives for every skill; the `/genpage` ↔ `/app-builder` boundaryfrom both sides ("add a page to my existing app" vs "an app … plus a dashboard page", "add a**table** to my existing app"); and negatives that share vocabulary with the plugin — Power Pages,-canvas/Power Fx, Power Automate, a generic React dashboard, and a pure knowledge question.+canvas/Power Fx, Power Automate, a generic React dashboard, a plain web app in the stack `/genpage` is+written in (React, TypeScript, Fluent UI), a Power Apps code app, and a pure knowledge question. Several+negatives say outright that the request is not for Power Platform, Dataverse or a model-driven app+(#21–#28). The stress tier also holds positives that carry a "not" about the other skill or about the+schema ("do not create another app", "do not change its Dataverse schema") (#29–#35): the descriptions+rule things out, and these are how a rule-out that is read too widely would show.## How a trial runs@@ -47,7 +52,9 @@ canvas/Power Fx, Power Automate, a generic React dashboard, and a pure knowledge- **Read-only.** The tool set is cut to "invoke a skill + read files". The trade-off is that a realsession offers more tools, so the model sees a slightly smaller menu.- **Stopped at the decision.** The JSONL transcript is parsed as it streams, and the agent is killed- the moment it invokes a model-apps skill, so a positive trial costs about one model turn.+ the moment it invokes a model-apps skill, so a positive trial costs about one model turn. A run that+ has not chosen a skill goes on to its own end, so a skill it reaches for later is seen, and graded, too+ (see [What counts as the decision](#what-counts-as-the-decision)).- **Guarded.** Every trial proves the plugin's skills were loaded before its outcome counts; if theywere not, the trial is a harness **error**, not a passing "none". Claude reports its loadedskills in the transcript's init event. Copilot's transcript does not, so each Copilot trial first@@ -61,6 +68,49 @@ canvas/Power Fx, Power Automate, a generic React dashboard, and a pure knowledgeEvery flag is in `lib/agents.js`; every transcript shape the parser understands is documented in`lib/transcript.js`.+## What counts as the decision++A case is graded on the **first plugin skill the agent asks for, at any turn**. That is the decision a real+session would act on, and a negative case exists to fail when the agent reaches for the plugin on a request+that is not for it. The report also shows what the agent did in its **first turn**, beside the grade and+never in place of it.++The agent runs with a read-only menu (a skill, `view`, `glob`, `grep`: no file writes, no shell). A request+that is plainly not for the plugin can therefore go like this: turn 0 looks at the empty workspace and+decides that no skill applies, which is the right answer, and turn 1, with nothing to build with, asks for+a skill as a stand-in. The grade counts that request, so the case fails, and the first turn's decision is+what tells a stand-in from a description that pulls the request in.++| | Meaning | Part of the grade |+|---|---------|-------------------|+| decision | the first plugin skill the agent asked for, at any turn, or none | yes: `expect` is compared with it |+| initial decision | the plugin skill asked for in the first turn, or none | no: reported beside the grade |+| later fallback | a plugin skill asked for only after a first turn that chose none | it is the decision; `later:` names it |++The first turn is the model's first response: a skill asked for in the same response as a `view` is still a+first-turn decision. The case line shows the first turn once a later request makes it differ from the grade:++```+not ok 21 - #21 [smoke] expect none — 1/3 (genpage×2, none×1) · first turn: 3/3 (none×3) · later: genpage×2+# later fallbacks: 2 trial(s) in 1 case(s) chose a plugin skill only after a first turn that chose none (counted in the grade; the first-turn decision is shown beside each case)+```++Two of the three trials asked for `/genpage` after a first turn that chose none, so the case fails; its first+turn chose none every time. A case that expects a skill and gets it only in turn 1 passes, as it always did, and+reads `ok 1 - #1 [smoke] expect genpage — 3/3 (genpage×3) · first turn: 0/3 (none×3) · later: genpage×3`. Where+nothing is asked for late the two decisions are the same, and the line is the plain+`ok 1 - #1 [smoke] expect genpage — 3/3 (genpage×3)`.++In the `--out` JSON each case has the grade (`status`, `rate`, `passes`, `valid`, `outcomes`), `initial` (the+first turn's `passes`, `valid`, `rate` and `outcomes`, for every case) and `delayed` (the later fallbacks).+Each trial has `routedTo` (the first plugin skill of the run), `initial` (the first-turn skill or `null`),+`delayed` (the later one or `null`) and `turn` (which turn asked for the first plugin skill).++Read a `later:` count as a question. In a real session the agent has file and shell tools and would do the+work itself, so a stand-in is partly a property of this menu. A count that grows after a description edit,+though, means the agent reached for the plugin on a request that is not for it. No option grades only the+first turn: it would pass every negative case on any run that reads the workspace before it asks for a skill.+## GradingRouting is not deterministic, so each case runs `--runs` trials (default 3) and passes when its@@ -74,15 +124,15 @@ Exit codes: `0` every case met the threshold · `1` a case failed · `2` harness```TAP version 13# agent claude · model sonnet · runs 2 · threshold 2/3-1..20+1..35ok 1 - #1 [smoke] expect genpage — 2/2 (genpage×2)not ok 4 - #4 [smoke] expect app-builder — 1/2 (app-builder×1, genpage×1)---prompt: "I need a Dataverse app for inventory ..."trap: "the word \"page\" pulling a whole-app request into /genpage"...-# cases 20 (pass 19, fail 1, error 0)-# trials 40 (errors 0)+# cases 35 (pass 34, fail 1, error 0)+# trials 70 (errors 0)# cost >= $0.48 (killed trials do not report cost)```@@ -111,7 +161,9 @@ keep those local; they can contain local paths and model output.Measured when the suite was added: all 20 cases passed 2/2 on both Claude Code (`--model sonnet`)and Copilot CLI (`--model claude-sonnet-5.5`), ~5–15 s per trial. The suite is therefore a**regression guard** for the descriptions, not a known-failing backlog — and since every case is-currently easy for these models, harder boundary prompts are the most useful additions.+currently easy for these models, harder boundary prompts are the most useful additions. Cases 21–35 were+added later: run a new one on its own (`--eval <id> --runs 3`) on the agent and model you care about+before reading a failure as a description problem.## Cadencediff --git a/evals/model-apps/routing/evals.json b/evals/model-apps/routing/evals.jsonindex 67cedaf9f..938496289 100644--- a/evals/model-apps/routing/evals.json+++ b/evals/model-apps/routing/evals.json@@ -1,6 +1,6 @@{"skill_name": "model-apps-routing",- "eval_instructions": "Each case is one user prompt sent to a headless agent with only the model-apps plugin loaded. `expect` is the model-apps skill the agent must invoke FIRST (genpage | app-builder | report-issue | telemetry), or null when it must invoke none of them. `accept` lists other outcomes that are also correct for a genuinely ambiguous prompt. `trap` names the mis-route the case exists to catch. Graded by run-routing.js over N trials against a pass-rate threshold.",+ "eval_instructions": "Each case is one user prompt sent to a headless agent with only the model-apps plugin loaded. `expect` is the model-apps skill the agent must invoke FIRST (genpage | app-builder | report-issue | telemetry), or null when it must invoke none of them. A skill asked for only after a first turn that chose none still counts; the decision of the agent's first turn is reported beside the grade and never replaces it. `accept` lists other outcomes that are also correct for a genuinely ambiguous prompt. `trap` names the mis-route the case exists to catch. Graded by run-routing.js over N trials against a pass-rate threshold.","evals": [{"id": 1,@@ -134,6 +134,111 @@"expect": "genpage","accept": ["app-builder"],"trap": "genuinely ambiguous: /genpage can create the table it needs, and /app-builder can edit the app; either is acceptable, NEITHER is not"+ },+ {+ "id": 21,+ "tier": "smoke",+ "prompt": "Build a generic React dashboard website using mock property data. No Power Platform, Dataverse or model-driven app.",+ "expect": null,+ "trap": "a \"no Power Platform\" disclaimer that still uses the plugin's own words (React, dashboard, model-driven app) pulling the request into /genpage or /app-builder. An agent that looks at the empty workspace first and then asks for a skill, because it has no tool to build with, fails the case all the same; the report shows that its first turn chose none"+ },+ {+ "id": 22,+ "tier": "full",+ "prompt": "Create a public tenant self-service website with Power Pages where tenants submit maintenance requests. Do not build a model-driven app.",+ "expect": null,+ "trap": "a Power Pages request that names a model-driven app only to rule it out"+ },+ {+ "id": 23,+ "tier": "full",+ "prompt": "Build a Power Apps canvas app for field inspections, using Power Fx and responsive screens. Not a model-driven app.",+ "expect": null,+ "trap": "Power Apps wording pulling a canvas request into /app-builder although it says \"not a model-driven app\""+ },+ {+ "id": 24,+ "tier": "full",+ "prompt": "Create a Power Automate scheduled flow that emails tomorrow's lease expirations. Do not create an app or page.",+ "expect": null,+ "trap": "\"app or page\" in a flow request, which names what both skills build"+ },+ {+ "id": 25,+ "tier": "full",+ "prompt": "Explain the difference between a model-driven app and a generative page. Do not create or edit anything.",+ "expect": null,+ "trap": "a knowledge question that names what both skills build triggering one of them"+ },+ {+ "id": 26,+ "tier": "full",+ "prompt": "I need a standalone web app to manage equipment loans, built with Node.js, Express and SQLite and a React front end. It has nothing to do with Power Apps or Dataverse.",+ "expect": null,+ "trap": "\"an app to manage Y\" read as /app-builder although the user rules out Power Apps and Dataverse"+ },+ {+ "id": 27,+ "tier": "full",+ "prompt": "Build a React 18 and TypeScript dashboard with Fluent UI v9 components and mock data, running locally on Vite. This is not for Power Apps.",+ "expect": null,+ "trap": "the stack /genpage is described with (React, TypeScript, Fluent UI) pulling a plain web app into it"+ },+ {+ "id": 28,+ "tier": "full",+ "prompt": "Create a Power Apps code app with React and Vite that lists Dataverse accounts.",+ "expect": null,+ "trap": "a standalone React app on Dataverse, which a different plugin builds, read as a generative page"+ },+ {+ "id": 29,+ "tier": "stress",+ "prompt": "We already have a model-driven property management app. Add a generative lease-expiry dashboard page using the existing lease tables. Do not create another app.",+ "expect": "genpage",+ "trap": "\"do not create another app\" and \"dashboard\" pulling a page request into /app-builder"+ },+ {+ "id": 30,+ "tier": "stress",+ "prompt": "Create a property management model-driven app from scratch: properties, units, tenants and leases, with forms and a generative dashboard page.",+ "expect": "app-builder",+ "trap": "\"a generative dashboard page\" inside a whole-app request pulling it into /genpage"+ },+ {+ "id": 31,+ "tier": "stress",+ "prompt": "Add a maintenance-request Dataverse table, its main form, view and sitemap entry to our existing model-driven app. This is an app schema edit, not a standalone page.",+ "expect": "app-builder",+ "trap": "an edit to an existing app's data model routed to /genpage because the app already exists"+ },+ {+ "id": 32,+ "tier": "stress",+ "prompt": "Edit the TSX of the generative maintenance page already deployed in our model-driven app, preserving maker edits and existing connector bindings.",+ "expect": "genpage",+ "trap": "an edit of a deployed page read as an edit of the app"+ },+ {+ "id": 33,+ "tier": "stress",+ "prompt": "Update our model-driven app to include a hidden Dataverse reference table and restrict which Main forms it offers. Keep all existing data.",+ "expect": "app-builder",+ "trap": "an existing app's table membership and form list are app-level changes, not a page"+ },+ {+ "id": 34,+ "tier": "stress",+ "prompt": "Add a generative SharePoint-document search page to an existing model-driven app using a connector. Do not change its Dataverse schema.",+ "expect": "genpage",+ "trap": "\"do not change its Dataverse schema\" read as ruling out Dataverse, which the descriptions' rule-out sentence is not about"+ },+ {+ "id": 35,+ "tier": "stress",+ "prompt": "Create an end-to-end property management model-driven app with a dashboard page and a maintenance process. I need the whole app, not just a page.",+ "expect": "app-builder",+ "trap": "\"not just a page\" read as a request for a page"}]}diff --git a/evals/model-apps/routing/lib/grade.js b/evals/model-apps/routing/lib/grade.jsindex 000b02757..61a28246d 100644--- a/evals/model-apps/routing/lib/grade.js+++ b/evals/model-apps/routing/lib/grade.js@@ -8,7 +8,22 @@// "trap": "…" } ← optional: the mis-route this case guards against// `expect: null` means "no skill of the plugin under test" (a negative / bleed-detection case).//-// A trial (one headless agent run) reports `routedTo` — the first plugin skill invoked, or null.+// A trial (one headless agent run) reports `routedTo` — the first plugin skill invoked, at ANY turn, or+// null — and `skillCalls`, every skill it asked for, each with the `turn` that asked (lib/transcript.js).+//+// THE GRADE IS THE WHOLE TRIAL: `routedTo` against what the case accepts. That is what the runner has always+// graded, and it has to stay that way. A negative case exists to fail when the agent reaches for the plugin+// on a request that is not for it; if only the first turn counted, any trial that looks at the workspace+// first and asks for the skill after would pass every one of them.+//+// THE INITIAL DECISION IS REPORTED BESIDE THE GRADE, never in place of it. The agent runs with a cut-down+// tool menu (skill + read-only file tools: no writes, no shell), so a request that is plainly not for the+// plugin can go like this: turn 0 looks at the empty workspace — the agent has decided no skill applies,+// which is the right answer — and turn 1, with nothing to build with, asks for a skill as a stand-in. The+// grade counts that request, so the case fails. The initial decision (the plugin skill asked for in turn 0,+// or none) says the first turn was right, and `delayed` names the skill that came later, so a reader can tell+// such a stand-in from a description that pulls the request in. Neither is a second verdict: `status` is+// computed from the grade alone.//// Model routing is not deterministic, so a case runs N trials and passes when its pass RATE// reaches the threshold. A trial that errored (spawn failure, plugin not loaded, crash before any@@ -31,21 +46,53 @@ function acceptable(evalCase) {return [...new Set(list.map(outcomeLabel))];}+/**+ * What a trial decided, split by WHEN the plugin skill was asked for (see the header).+ * initial the plugin skill asked for in the agent's first turn — chosen from the prompt and the+ * descriptions alone, before any tool result existed — or null+ * delayed the plugin skill asked for only AFTER a first turn that chose none, or null+ * eventual the first plugin skill at any turn (`initial`, else `delayed`): the trial's `routedTo`, which+ * is what a case is graded on+ * turn the 0-based turn that asked for it, or null when none did+ * A trial that carries no per-call turns (a canned trial, a results file from before the split) has+ * only `routedTo`; it is read as a first-turn decision rather than guessed at.+ */+function decisionOf(trial) {+ const eventual = trial.routedTo == null ? null : trial.routedTo;+ if (eventual === null) return { initial: null, delayed: null, eventual: null, turn: null };+ const call = (trial.skillCalls || []).find((c) => c.ofPlugin && c.name === eventual);+ const turn = call && Number.isInteger(call.turn) ? call.turn : 0;+ return turn === 0+ ? { initial: eventual, delayed: null, eventual, turn }+ : { initial: null, delayed: eventual, eventual, turn };+}+/*** @param {object} evalCase- * @param {{routedTo: string|null, error?: string, timedOut?: boolean}} trial- * @returns {{status: 'pass'|'fail'|'error', outcome?: string, reason: string}}+ * @param {{routedTo: string|null, skillCalls?: Array, error?: string, timedOut?: boolean}} trial+ * @returns {{status: 'pass'|'fail'|'error', outcome?: string, delayed?: string|null,+ * initial?: {outcome: string, status: 'pass'|'fail'}, reason: string}}+ * `status` and `outcome` are the grade: the first plugin skill at any turn. `initial` is what the first+ * turn alone would have graded as, and `delayed` the plugin skill asked for only after it; they are+ * reported beside the grade and are not part of it.*/function gradeTrial(evalCase, trial) {// A trial that timed out before routing arrives here with `error` set (run-routing.js): an// unfinished run has not decided "none", so it is excluded rather than graded.if (trial.error) return { status: 'error', reason: trial.error };+ const accepted = acceptable(evalCase);+ // `routedTo`, and not `decisionOf(trial).initial`: the grade must count a skill asked for at any turn.const outcome = outcomeLabel(trial.routedTo);- const ok = acceptable(evalCase).includes(outcome);+ const ok = accepted.includes(outcome);+ const decision = decisionOf(trial);+ const initialOutcome = outcomeLabel(decision.initial);+ const late = decision.delayed ? ' (asked for only after its first turn)' : '';return {status: ok ? 'pass' : 'fail',outcome,- reason: ok ? `routed to ${outcome}` : `routed to ${outcome}, expected ${acceptable(evalCase).join(' | ')}`,+ delayed: decision.delayed,+ initial: { outcome: initialOutcome, status: accepted.includes(initialOutcome) ? 'pass' : 'fail' },+ reason: ok ? `routed to ${outcome}${late}` : `routed to ${outcome}${late}, expected ${accepted.join(' | ')}`,};}@@ -53,16 +100,26 @@ function gradeTrial(evalCase, trial) {* @param {object} evalCase* @param {Array} trials* @param {number} threshold - 0..1, minimum pass rate over the non-error trials.+ * `status`, `passes`, `rate` and `outcomes` grade the whole trial. `initial` counts the first turn's decision+ * the same way, and `delayed` counts the plugin skills asked for only after it; `status` never reads either.*/function summarizeCase(evalCase, trials, threshold) {const graded = trials.map((t) => gradeTrial(evalCase, t));const valid = graded.filter((g) => g.status !== 'error');const passes = valid.filter((g) => g.status === 'pass').length;const outcomes = {};- for (const g of valid) outcomes[g.outcome] = (outcomes[g.outcome] || 0) + 1;+ const delayed = {};+ const initial = { passes: 0, valid: valid.length, rate: null, outcomes: {} };+ for (const g of valid) {+ outcomes[g.outcome] = (outcomes[g.outcome] || 0) + 1;+ if (g.delayed) delayed[g.delayed] = (delayed[g.delayed] || 0) + 1;+ initial.outcomes[g.initial.outcome] = (initial.outcomes[g.initial.outcome] || 0) + 1;+ if (g.initial.status === 'pass') initial.passes += 1;+ }+ if (valid.length) initial.rate = initial.passes / valid.length;const errors = graded.filter((g) => g.status === 'error').map((g) => g.reason);if (!valid.length) {- return { status: 'error', passes: 0, valid: 0, runs: trials.length, rate: null, outcomes, errors, graded };+ return { status: 'error', passes: 0, valid: 0, runs: trials.length, rate: null, outcomes, delayed, initial, errors, graded };}const rate = passes / valid.length;return {@@ -74,6 +131,8 @@ function summarizeCase(evalCase, trials, threshold) {runs: trials.length,rate,outcomes,+ delayed,+ initial,errors,graded,};@@ -100,4 +159,4 @@ function validateEvals(data, pluginSkills) {return errs;}-module.exports = { gradeTrial, summarizeCase, validateEvals, acceptable, outcomeLabel, NONE };+module.exports = { gradeTrial, summarizeCase, validateEvals, acceptable, outcomeLabel, decisionOf, NONE };diff --git a/evals/model-apps/routing/lib/transcript.js b/evals/model-apps/routing/lib/transcript.jsindex 55ef75184..037d760bf 100644--- a/evals/model-apps/routing/lib/transcript.js+++ b/evals/model-apps/routing/lib/transcript.js@@ -21,6 +21,23 @@// Skill names are NOT namespaced. `assistant.message` is the earliest COMPLETE tool request;// `tool.execution_start` repeats it, so calls are de-duplicated by toolCallId.//+// TURNS. Every recorded skill call carries `turn`, the 0-based index of the model response that+// asked for it, because a skill requested in the first response is a different fact from one requested+// after the agent had already read the workspace (see lib/grade.js: `decisionOf`).+// Copilot: the CLI marks its turns itself —+// {"type":"assistant.turn_start","data":{"turnId":"0"}} … one `assistant.message` … {"type":"assistant.turn_end","data":{"turnId":"0"}}+// (measured over real traces: exactly one `assistant.message` per turn, turnIds 0, 1, 2 …). A transcript with+// no turn_start events (an older CLI, a hand-written fixture) is read as one turn per `assistant.message`.+// Claude Code: events are NOT turns. A response can be printed as several `assistant` events, one per content+// block, that share `message.id`, and a tool result comes back between one response and the next:+// {"type":"assistant","message":{"id":"msg_01","content":[{"type":"text","text":"I'll look first."}]}}+// {"type":"assistant","message":{"id":"msg_01","content":[{"type":"tool_use","id":"toolu_01","name":"Glob",…}]}}+// {"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"No files found"}]}}+// {"type":"assistant","message":{"id":"msg_02","content":[{"type":"tool_use","id":"toolu_02","name":"Skill",…}]}} ← turn 1+// so a new turn starts when `message.id` changes. Where an id is missing the tool result is what separates+// two responses instead; the tool result alone is not used when ids exist, because Claude Code can start a+// tool while a later block of the same response is still streaming.+//// Non-JSON lines (CLI banners, warnings on stderr merged into stdout) are ignored rather than// treated as errors: a transcript is evidence, and one noisy line must not void a trial.@@ -38,12 +55,16 @@ class TranscriptParser {this.agent = agent;this.pluginName = pluginName;this.pluginSkills = new Set(pluginSkills);- this.skillCalls = []; // every skill invocation, in order: { raw, name, ofPlugin }+ this.skillCalls = []; // every skill invocation, in order: { raw, name, ofPlugin, turn }this.loadedSkills = null; // Claude only: the init event's skill list (isolation evidence)this.text = ''; // final assistant text (best-effort; for diagnostics only)this.result = null; // the terminal `result` event, when the run got that farthis.eventCount = 0; // JSON events accepted — 0 means the agent never really ran+ this.turn = -1; // index of the model response being read; -1 until the firstthis._seen = new Set();+ this._turnMarked = false; // Copilot: the CLI sent turn_start events, so messages do not count turns+ this._messageId = null; // Claude: message.id of the response being read+ this._toolResultSince = false; // Claude: a tool result came back since the last assistant event}/** First skill of the plugin under test, normalized (`genpage`), or null. */@@ -98,17 +119,30 @@ class TranscriptParser {const m = rawName.match(/^([^:]+):(.+)$/);const name = m ? m[2] : rawName;const ofPlugin = m ? m[1] === this.pluginName && this.pluginSkills.has(name) : this.pluginSkills.has(name);- this.skillCalls.push({ raw: rawName, name, ofPlugin });+ // A request seen before any turn marker (a transcript that starts mid-run) is read as the first turn.+ this.skillCalls.push({ raw: rawName, name, ofPlugin, turn: Math.max(this.turn, 0) });+ }++ // See TURNS in the header: a new response is told from another block of the same one by `message.id`.+ _claudeTurn(messageId) {+ const startsNextTurn = this.turn < 0+ || (messageId && this._messageId ? messageId !== this._messageId : this._toolResultSince);+ if (startsNextTurn) this.turn += 1;+ this._messageId = messageId || null;+ this._toolResultSince = false;}_claude(ev) {if (ev.type === 'system' && ev.subtype === 'init' && Array.isArray(ev.skills)) {this.loadedSkills = ev.skills.slice();} else if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {+ this._claudeTurn(ev.message.id);for (const c of ev.message.content) {if (c.type === 'tool_use' && c.name === 'Skill' && c.input) this._skill(c.id, c.input.skill);else if (c.type === 'text' && typeof c.text === 'string') this.text = c.text;}+ } else if (ev.type === 'user') {+ this._toolResultSince = true;} else if (ev.type === 'result') {this.result = { subtype: ev.subtype, isError: ev.is_error === true, turns: ev.num_turns, costUsd: ev.total_cost_usd };}@@ -116,7 +150,11 @@ class TranscriptParser {_copilot(ev) {const d = ev.data || {};- if (ev.type === 'assistant.message') {+ if (ev.type === 'assistant.turn_start') {+ this._turnMarked = true;+ this.turn += 1;+ } else if (ev.type === 'assistant.message') {+ if (!this._turnMarked) this.turn += 1;for (const r of d.toolRequests || []) {if (r.name === 'skill' && r.arguments) this._skill(r.toolCallId, r.arguments.skill);}diff --git a/evals/model-apps/routing/run-routing.js b/evals/model-apps/routing/run-routing.jsindex d6beef600..9d3fa84f0 100644--- a/evals/model-apps/routing/run-routing.js+++ b/evals/model-apps/routing/run-routing.js@@ -15,6 +15,13 @@// it the moment a plugin skill is invoked (see lib/agents.js for the isolation flags and// lib/transcript.js for the event shapes). Cost is therefore ~one model turn per trial.//+// A case is graded on the first plugin skill the agent asks for, at ANY turn. The decision of its FIRST turn+// is reported beside the grade and never in place of it: the tool menu is read-only (no file writes, no+// shell), so a request that is not for the plugin can go "turn 0 looks at the empty workspace and decides no+// skill applies, turn 1 asks for a skill because nothing else can do the work". The case fails on that+// request, and its line says the first turn chose none, so a stand-in can be told from a description that+// pulls the request in (lib/grade.js; EVAL_GUIDE.md → "What counts as the decision").+//// NOT part of the per-PR gate: it needs model credentials, is non-deterministic, and costs money.// See EVAL_GUIDE.md → "Cadence" and .github/workflows/model-apps-agent-evals.yml.//@@ -34,7 +41,7 @@ const { spawn, spawnSync } = require('node:child_process');const { TIERS } = require('../lib/eval-args.js');const { TranscriptParser, AGENTS } = require('./lib/transcript.js');const { buildInvocation, quoteForCmd } = require('./lib/agents.js');-const { summarizeCase, validateEvals } = require('./lib/grade.js');+const { summarizeCase, validateEvals, decisionOf } = require('./lib/grade.js');const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');const PLUGIN_DIR = path.join(REPO_ROOT, 'plugins', 'model-apps');@@ -210,20 +217,32 @@ function copilotSkillInventory({ bin, binArgs = [], pluginDir, env, cwd }) {}/**- * Launch one agent run and resolve when it ROUTED, finished, timed out, or failed to start.+ * Launch one agent run and resolve when it ROUTED, finished, timed out, or failed to start — and,+ * for a run the harness had to kill, once the agent has closed, so the caller may remove the trial's+ * working directory at once. A kill takes effect a moment after it is sent, and until then the agent+ * still holds that directory (on Windows removing it failed with `EBUSY`); so the wait is for the+ * process to exit and its pipes to end. It is bounded (`closeWaitMs`): an agent that will not die, or a+ * grandchild that keeps a pipe open, must not hold the whole run, and the result is the same either way.* Never rejects: every failure becomes `trial.error`, which grading excludes from the pass rate.* `loadedSkills` / `loadError` carry a preflight's skill inventory for agents whose transcript does* not report it (Copilot); a `loadError` fails the trial before any model call is made.*- * Two seams exist for the tests, and neither changes what a run does:+ * Four seams exist for the tests, and none changes what a run does:* `clock` the timer pair the `timeoutMs` deadline runs on. A test that must fire the deadline at* a chosen moment (after the agent has printed its first event, say) passes its own,* rather than racing a real timer against how long a loaded machine takes to start Node.* `onStart` called once, right after the process is launched, with `{ child, parser }`, so a test* can tell when the parser has seen a line and when the killed process has really exited.+ * `kill` what ends the agent (default `killTree`). A test that must have an agent die late, or not+ * at all, passes its own to see that the trial waits for the close and that the wait ends.+ * `closeWaitMs` the bound on that wait (default `CLOSE_WAIT_MS`); a test shortens it. It runs on the+ * real timer, never on `clock`, which stays the trial's deadline alone.*/const REAL_CLOCK = { setTimeout, clearTimeout };-function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plugin, agent, loadedSkills = null, loadError = null, clock = REAL_CLOCK, onStart = null }) {+// A killed process closes within tens of milliseconds (40 ms at most in 40 measured runs of an agent stand-in on+// Windows), so seconds are ample; a longer bound only costs a run whose agent really cannot be ended.+const CLOSE_WAIT_MS = 5000;+function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plugin, agent, loadedSkills = null, loadError = null, clock = REAL_CLOCK, onStart = null, kill = killTree, closeWaitMs = CLOSE_WAIT_MS }) {return new Promise((resolve) => {const started = Date.now();const parser = new TranscriptParser(agent, plugin);@@ -251,11 +270,22 @@ function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, pluglet buf = '';let timedOut = false;let settled = false;+ // `closed`: the 'close' event has fired, so the process has exited and its pipes have ended. finish() can run+ // long before that (at the routing decision, at the deadline), right after it sends the kill.+ let closed = false;+ let afterClose = null;+ const resolveWhenClosed = (outcome) => {+ if (closed) { resolve(outcome); return; }+ // The outcome is already decided, so the wait changes nothing but WHEN the caller hears of it. It runs on the+ // real timer: `clock` is the trial's deadline, and a test that controls it must not control this.+ const giveUp = setTimeout(() => { afterClose = null; resolve(outcome); }, closeWaitMs);+ afterClose = () => { clearTimeout(giveUp); resolve(outcome); };+ };const finish = (extra = {}) => {if (settled) return;settled = true;clock.clearTimeout(timer);- killTree(child);+ kill(child);let error = extra.error || null;// "none" is a DECISION only when the run ended on its own without choosing a plugin skill.// A run cut off by the timeout has not decided anything — even if it streamed events (an@@ -282,7 +312,7 @@ function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plugconst missing = plugin.pluginSkills.filter((s) => !loaded.includes(`${plugin.pluginName}:${s}`) && !loaded.includes(s));if (missing.length) error = `plugin skills not loaded: ${missing.join(', ')} (check --plugin-dir)`;}- resolve({+ resolveWhenClosed({routedTo: parser.routedTo,skillCalls: parser.skillCalls,loadedSkills: loaded,@@ -309,6 +339,7 @@ function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plugchild.stderr.on('data', (c) => { stderr += c.toString('utf8'); });child.on('error', (err) => finish({ error: `could not start ${bin}: ${err.message}` }));child.on('close', (code) => {+ closed = true;if (buf) parser.push(buf);const tail = stderr.trim().split(/\r?\n/).slice(-3).join(' | ');// A run that ends without routing is a valid "none" outcome only if it ended SUCCESSFULLY.@@ -319,6 +350,8 @@ function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plug} else {finish();}+ // A trial that finished earlier is waiting for exactly this.+ if (afterClose) afterClose();});child.stdin.on('error', () => { /* agent exited before reading the prompt; 'close' reports it */ });child.stdin.end(prompt);@@ -432,8 +465,9 @@ async function runRouting(opts, { runTrial = runTrialWithAgent, evalsData, writewrite('TAP version 13');write(`# agent ${opts.agent} · model ${opts.model || '(cli default)'} · runs ${opts.runs} · threshold ${opts.thresholdLabel || opts.threshold}`);write(`1..${cases.length}`);- const summary = { pass: 0, fail: 0, error: 0, trials: 0, trialErrors: 0, costUsd: 0 };+ const summary = { pass: 0, fail: 0, error: 0, trials: 0, trialErrors: 0, costUsd: 0, delayedTrials: 0, delayedCases: 0 };const caseResults = [];+ const spread = (counts) => Object.entries(counts).map(([k, v]) => `${k}×${v}`).join(', ');cases.forEach((c, i) => {const ts = byCase.get(c.id);const s = summarizeCase(c, ts, opts.threshold);@@ -441,13 +475,22 @@ async function runRouting(opts, { runTrial = runTrialWithAgent, evalsData, writesummary.trials += ts.length;summary.trialErrors += s.errors.length;for (const t of ts) if (t.result && typeof t.result.costUsd === 'number') summary.costUsd += t.result.costUsd;- const dist = Object.entries(s.outcomes).map(([k, v]) => `${k}×${v}`).join(', ') || 'no valid trials';- const head = `#${c.id} [${c.tier}] expect ${c.expect === null ? 'none' : c.expect} — ${s.passes}/${s.valid} (${dist})`;+ const delayedTrials = Object.values(s.delayed).reduce((n, v) => n + v, 0);+ summary.delayedTrials += delayedTrials;+ if (delayedTrials) summary.delayedCases += 1;+ const dist = spread(s.outcomes) || 'no valid trials';+ const later = spread(s.delayed);+ // The first turn's decision is printed only where a later request makes it differ from the grade; where+ // nothing was asked for late the two are the same and the line reads as it always did (the results file+ // carries `initial` for every case).+ const firstTurn = later ? ` · first turn: ${s.initial.passes}/${s.initial.valid} (${spread(s.initial.outcomes)})` : '';+ const head = `#${c.id} [${c.tier}] expect ${c.expect === null ? 'none' : c.expect} — ${s.passes}/${s.valid} (${dist})${firstTurn}${later ? ` · later: ${later}` : ''}`;write(`${s.status === 'pass' ? 'ok' : 'not ok'} ${i + 1} - ${head}`);if (s.status !== 'pass' || s.errors.length) {write(' ---');write(` prompt: ${yamlStr(c.prompt)}`);if (c.trap) write(` trap: ${yamlStr(c.trap)}`);+ if (later) write(` later: ${yamlStr(`${later} — asked for only after a first turn that chose none; counted in the grade, as is any skill the agent asks for`)}`);for (const e of [...new Set(s.errors)]) write(` error: ${yamlStr(e)}`);write(' ...');}@@ -456,12 +499,18 @@ async function runRouting(opts, { runTrial = runTrialWithAgent, evalsData, write}caseResults.push({id: c.id, tier: c.tier, prompt: c.prompt, expect: c.expect, accept: c.accept || [],- status: s.status, rate: s.rate, passes: s.passes, valid: s.valid, outcomes: s.outcomes, errors: s.errors,- trials: ts.map((t) => ({ routedTo: t.routedTo, skills: (t.skillCalls || []).map((k) => k.raw), timedOut: !!t.timedOut, error: t.error || null, durationMs: t.durationMs })),+ status: s.status, rate: s.rate, passes: s.passes, valid: s.valid, outcomes: s.outcomes, delayed: s.delayed, initial: s.initial, errors: s.errors,+ trials: ts.map((t) => {+ const d = decisionOf(t);+ return { routedTo: t.routedTo, initial: d.initial, delayed: d.delayed, turn: d.turn, skills: (t.skillCalls || []).map((k) => k.raw), timedOut: !!t.timedOut, error: t.error || null, durationMs: t.durationMs };+ }),});});write(`# cases ${cases.length} (pass ${summary.pass}, fail ${summary.fail}, error ${summary.error})`);write(`# trials ${summary.trials} (errors ${summary.trialErrors})`);+ if (summary.delayedTrials) {+ write(`# later fallbacks: ${summary.delayedTrials} trial(s) in ${summary.delayedCases} case(s) chose a plugin skill only after a first turn that chose none (counted in the grade; the first-turn decision is shown beside each case)`);+ }// Only runs that reach their `result` event report cost; trials killed at the routing decision// never do, so this is a lower bound and is labelled as one.if (summary.costUsd) write(`# cost >= $${summary.costUsd.toFixed(2)} (killed trials do not report cost)`);diff --git a/evals/model-apps/routing/tests/descriptions.test.js b/evals/model-apps/routing/tests/descriptions.test.jsnew file mode 100644index 000000000..18cd34213--- /dev/null+++ b/evals/model-apps/routing/tests/descriptions.test.js@@ -0,0 +1,122 @@+'use strict';+// What an agent routes on is the `description:` of each skill and agent, and the live routing eval measures+// that with a model. These offline tests pin what the descriptions must keep doing together, so an edit+// to one thing cannot quietly break the other:+// 1. they rule out what is not theirs — a generic or standalone React or web app, the other Power+// Platform products, and a request that rules out Power Platform, Dataverse and model-driven apps+// altogether — in words a request can be matched against;+// 2. they keep every phrase a positive case routes on, and the sentence that sends a request to the+// other skill.+// Whether a model reads them the way they are meant is what `run-routing.js` is for.+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const { frontmatterDescription } = require('../run-routing.js');++const PLUGIN_DIR = path.resolve(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps');+const skillDescription = (name) => frontmatterDescription(fs.readFileSync(path.join(PLUGIN_DIR, 'skills', name, 'SKILL.md'), 'utf8'));+const AGENT_FILES = fs.readdirSync(path.join(PLUGIN_DIR, 'agents')).filter((f) => f.endsWith('.md')).sort();+const agentDescription = (file) => frontmatterDescription(fs.readFileSync(path.join(PLUGIN_DIR, 'agents', file), 'utf8'));++// The rule-out is worded around the request a user actually types ("No Power Platform, Dataverse or+// model-driven app"), and is not "when the user says not": a positive request can carry a "not" about the+// other skill ("do not create another app") or about the schema ("do not change its Dataverse schema").+const RULED_OUT = /rules out Power Platform, Dataverse, or model-driven apps \(for example "no Power Platform"\)/;+const NOT_GENERIC = /Do not use it for a generic(?: or standalone)? (?:React or web|web or React) app/;+const NOT_OTHER_PRODUCTS = /Power Pages, canvas apps, or Power Automate/;++test('the authoring skills rule out a generic web or React app and the other Power Platform products', () => {+ for (const skill of ['genpage', 'app-builder']) {+ const description = skillDescription(skill);+ assert.match(description, NOT_GENERIC, `${skill}: a generic or standalone React or web app`);+ assert.match(description, NOT_OTHER_PRODUCTS, `${skill}: Power Pages, canvas apps and Power Automate`);+ assert.match(description, RULED_OUT, `${skill}: a request that rules out Power Platform, Dataverse and model-driven apps`);+ }+});++test('/genpage says why it cannot take a standalone project, and where a Power Apps code app belongs', () => {+ const description = skillDescription('genpage');+ assert.match(description, /\(including a Power Apps code app\)/);+ assert.match(description, /A generative page only runs inside a model-driven app, and this skill cannot scaffold a standalone project/);+});++test('every agent description is scoped to generative pages of a model-driven app', () => {+ assert.ok(AGENT_FILES.length >= 6, `expected the plugin agents, found ${AGENT_FILES.join(', ')}`);+ for (const file of AGENT_FILES) {+ const description = agentDescription(file);+ assert.match(description, /Works only on generative pages in a Power Apps model-driven app\. Never use it for a generic React or web app/, file);+ assert.match(description, RULED_OUT, file);+ }+});++// Each phrase is one a committed positive case routes on; the second column says which kind of request+// loses its match if the phrase goes.+const KEPT = {+ genpage: [+ ['Creates, updates, and deploys Power Apps generative pages for model-driven apps', 'what the skill is'],+ ['build, retrieve, or update a page in an existing Microsoft Power Apps model-driven app', 'a page added to, or edited in, an app that already exists'],+ ['"generative page"', 'a request that names generative pages'],+ ['"page in a model-driven"', 'a request for a page in a model-driven app'],+ ['"genux"', 'a request that says genux'],+ ['use /app-builder instead', 'a whole app, which is not this skill'],+ ],+ 'app-builder': [+ ['Builds and edits a model-driven Power Apps app from a natural-language intent', 'what the skill is'],+ ['tables, columns, relationships, adaptive forms with sub-grids, views, Choice-column charts, business rules, business process flows', 'a data-model or form edit, and a business process flow'],+ ['generative page intents for overview/dashboard surfaces', 'a whole app that also has a dashboard page'],+ ['an app module + sitemap', 'navigation of a new app'],+ ['can download a deployed app back into an editable spec to change it', 'a change to an app that is already deployed'],+ ['"build an app for X"', 'a request to build an app'],+ ['"create a model-driven app"', 'a request that names a model-driven app'],+ ['"make me an app to manage Y"', 'a request that does not name the platform'],+ ['"add a business process flow"', 'a business process flow added to an existing app'],+ ['"edit/add to my app"', 'an edit to an app'],+ ['use /genpage instead', 'a standalone page in an existing app, which is not this skill'],+ ],+};++for (const [skill, phrases] of Object.entries(KEPT)) {+ test(`/${skill} keeps every phrase a positive case routes on`, () => {+ const description = skillDescription(skill);+ for (const [phrase, why] of phrases) assert.ok(description.includes(phrase), `${skill}: "${phrase}" is gone — ${why}`);+ });+}++test('each skill still names the other in its boundary sentence, so the pair keeps pointing at each other', () => {+ assert.match(skillDescription('genpage'), /This skill stands alone and does not require \/app-builder/);+ assert.match(skillDescription('app-builder'), /This skill stands alone and does not require \/genpage/);+});++// ---------- the committed cases that guard those sentences ----------++const CASES = require('../evals.json').evals;+const NEGATIVES = CASES.filter((c) => c.expect === null);+const POSITIVES = CASES.filter((c) => c.expect !== null);+const RULES_OUT_THE_PLATFORM = /\b(?:no|not|nothing to do with)\b[^.]*\b(?:Power Platform|Power Apps|Dataverse|model-driven app)\b/i;+const NOT_ABOUT_THE_PLATFORM = /\b(?:Do not|not just|not a standalone)\b/;++test('the cases include a generic React request that rules out Power Platform, as a negative', () => {+ const generic = NEGATIVES.filter((c) => /generic React/i.test(c.prompt) && /\bNo Power Platform\b/.test(c.prompt));+ assert.equal(generic.length, 1, 'the request the rule-out sentences exist for');+ assert.ok(generic[0].trap, 'a negative says which mis-route it guards against');+});++test('the cases include several negatives that rule out the platform in words, and a stack the descriptions are written in', () => {+ const ruledOut = NEGATIVES.filter((c) => RULES_OUT_THE_PLATFORM.test(c.prompt));+ assert.ok(ruledOut.length >= 5, `expected at least 5 negatives that rule out Power Platform, Power Apps, Dataverse or a model-driven app, found ${ruledOut.length}`);+ assert.ok(NEGATIVES.some((c) => /Fluent UI/.test(c.prompt) && /React/.test(c.prompt)), 'a plain web app in the stack /genpage is described with');+ assert.ok(NEGATIVES.some((c) => /code app/i.test(c.prompt)), 'a Power Apps code app, which the /genpage description names as not its own');+ assert.ok(NEGATIVES.some((c) => /React/.test(c.prompt) && /app to manage/.test(c.prompt)), 'a generic "app to manage Y", which is the /app-builder trigger phrase');+});++test('the rule-out example the descriptions quote is in negatives only, and positives that carry a "not" about something else stay', () => {+ assert.deepEqual(POSITIVES.filter((c) => /\bno Power Platform\b/i.test(c.prompt)).map((c) => c.id), []);+ // A positive request can say "do not create another app" or "do not change its Dataverse schema". The+ // rule-out sentence must not be read widely enough to take those away.+ const withNot = POSITIVES.filter((c) => NOT_ABOUT_THE_PLATFORM.test(c.prompt));+ assert.ok(withNot.length >= 4, `expected at least 4 positives with a "not" about another skill or the schema, found ${withNot.length}`);+ assert.ok(withNot.some((c) => c.expect === 'genpage') && withNot.some((c) => c.expect === 'app-builder'), 'from both sides of the boundary');+ assert.ok(withNot.some((c) => /Dataverse/.test(c.prompt)), 'one that says "not" next to Dataverse');+});diff --git a/evals/model-apps/routing/tests/fake-agent-turns.js b/evals/model-apps/routing/tests/fake-agent-turns.jsnew file mode 100644index 000000000..042ea33ee--- /dev/null+++ b/evals/model-apps/routing/tests/fake-agent-turns.js@@ -0,0 +1,59 @@+'use strict';+// Stand-in for an agent CLI in run-routing tests whose run takes MORE THAN ONE turn: it looks at its+// (empty) workspace first and only then acts — the shape of the runs that made the routing eval tell a+// first-turn decision from a later one. fake-agent.js covers the single-turn shapes. Reads the prompt+// from stdin like the real CLIs, then behaves according to FAKE_AGENT_MODE:+// claude-look-then-route turn 0 reads the workspace (a text block and a tool call of ONE response,+// as two events), a tool result comes back, turn 1 asks for a skill, then the+// process stays alive (the runner must kill it at the skill request)+// copilot-look-then-route the same in Copilot's JSON events, with turn_start / turn_end around each turn+// claude-look-then-answer turn 0 reads the workspace, turn 1 answers in text and the run ends successfully+// copilot-look-then-answer the same in Copilot's JSON events+// FAKE_AGENT_SKILL names the skill turn 1 asks for (default genpage).+const mode = process.env.FAKE_AGENT_MODE;+const skill = process.env.FAKE_AGENT_SKILL || 'genpage';+const out = (o) => process.stdout.write(`${JSON.stringify(o)}\n`);+const claudeSkills = ['model-apps:app-builder', 'model-apps:genpage', 'model-apps:report-issue', 'model-apps:telemetry'];++function claude(finalTurn) {+ out({ type: 'system', subtype: 'init', skills: claudeSkills });+ out({ type: 'assistant', message: { id: 'msg_01', role: 'assistant', content: [{ type: 'text', text: 'No skill applies; I will look at the workspace first.' }] } });+ out({ type: 'assistant', message: { id: 'msg_01', role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_01', name: 'Glob', input: { pattern: '**/*' } }] } });+ out({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_01', content: 'No files found' }] } });+ if (finalTurn === 'route') {+ out({ type: 'assistant', message: { id: 'msg_02', role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_02', name: 'Skill', input: { skill: `model-apps:${skill}` } }] } });+ setInterval(() => {}, 1000);+ return;+ }+ out({ type: 'assistant', message: { id: 'msg_02', role: 'assistant', content: [{ type: 'text', text: 'There is no tool here to build that.' }] } });+ out({ type: 'result', subtype: 'success', num_turns: 2, total_cost_usd: 0.001 });+ process.exit(0);+}++function copilot(finalTurn, prompt) {+ out({ type: 'user.message', data: { content: prompt.trim() } });+ out({ type: 'assistant.turn_start', data: { turnId: '0' } });+ out({ type: 'assistant.message', data: { messageId: 'm1', content: '', toolRequests: [{ toolCallId: 'toolu_01', name: 'view', arguments: { path: '<workspace>' } }] } });+ out({ type: 'tool.execution_start', data: { toolCallId: 'toolu_01', toolName: 'view', arguments: { path: '<workspace>' } } });+ out({ type: 'tool.execution_complete', data: { toolCallId: 'toolu_01', success: true } });+ out({ type: 'assistant.turn_end', data: { turnId: '0' } });+ out({ type: 'assistant.turn_start', data: { turnId: '1' } });+ if (finalTurn === 'route') {+ out({ type: 'assistant.message', data: { messageId: 'm2', content: '', toolRequests: [{ toolCallId: 'toolu_02', name: 'skill', arguments: { skill } }] } });+ setInterval(() => {}, 1000);+ return;+ }+ out({ type: 'assistant.message', data: { messageId: 'm2', content: 'There is no tool here to build that.', toolRequests: [] } });+ out({ type: 'assistant.turn_end', data: { turnId: '1' } });+ out({ type: 'result', exitCode: 0, usage: { premiumRequests: 1 } });+ process.exit(0);+}++let prompt = '';+process.stdin.on('data', (c) => { prompt += c; });+process.stdin.on('end', () => {+ const [agent, , , final] = String(mode).split('-');+ if (agent === 'claude') claude(final);+ else if (agent === 'copilot') copilot(final, prompt);+ else { process.stderr.write(`unknown FAKE_AGENT_MODE ${mode}\n`); process.exit(3); }+});diff --git a/evals/model-apps/routing/tests/initial-decision.test.js b/evals/model-apps/routing/tests/initial-decision.test.jsnew file mode 100644index 000000000..b9a7bd858--- /dev/null+++ b/evals/model-apps/routing/tests/initial-decision.test.js@@ -0,0 +1,414 @@+'use strict';+// The routing eval grades the WHOLE trial: the first model-apps skill the agent asks for, at ANY turn. That+// is the grade it always had, and these tests keep it exactly as strict. What was added is a separate signal,+// the INITIAL decision — the skill the agent asked for in its first turn, or none — reported beside the+// grade and never in place of it.+//+// WHY the signal: the agent runs with a cut-down tool menu (skill, view, glob, grep: no file writes, no+// shell). A request that is plainly not for the plugin ("a generic React dashboard, no Power Platform") can+// get the right answer first — no skill applies, the agent looks at the empty workspace to start the work+// itself — and then, with nothing to build with, ask for a skill as a stand-in. The grade counts that+// request, so the case fails, and the initial decision says the first turn was right: a reader can tell the+// stand-in from a description that pulls the request in.+// WHY the grade must not move: a negative case exists to fail when the agent reaches for the plugin on a+// request that is not for it. If the first turn decided, any trial that reads the workspace first would slip+// past every negative case. These tests pin the split at each layer: which turn a transcript's skill request+// came in, that the grade of every committed case is the original one, how a trial and a case report the+// initial decision, how the runner prints it, and the whole path against a fake agent that looks before it+// acts.+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { setTimeout: sleep } = require('node:timers/promises');++const { TranscriptParser, parseTranscript } = require('../lib/transcript.js');+const { decisionOf, gradeTrial, summarizeCase } = require('../lib/grade.js');+const { parseArgs, runRouting, spawnTrial, DEFAULTS } = require('../run-routing.js');++const PLUGIN = { pluginName: 'model-apps', pluginSkills: ['app-builder', 'genpage', 'report-issue', 'telemetry'] };+const read = (name) => fs.readFileSync(path.join(__dirname, 'transcripts', name), 'utf8');+const without = (text, pattern) => text.split('\n').filter((line) => !pattern.test(line)).join('\n');+const turnsOf = (parser) => parser.skillCalls.map((c) => c.turn);++// ---------- which turn asked for the skill ----------++test('transcript(copilot): a skill asked for after a turn that only looked at the workspace is turn 1', () => {+ const p = parseTranscript('copilot', read('copilot-look-then-skill.jsonl'), PLUGIN);+ assert.equal(p.routedTo, 'genpage');+ assert.deepEqual(p.skillCalls.map((c) => [c.name, c.turn]), [['genpage', 1]]);+});++test('transcript(copilot): without turn_start events each assistant.message is its own turn', () => {+ const noMarkers = without(read('copilot-look-then-skill.jsonl'), /assistant\.turn_(start|end)/);+ assert.deepEqual(turnsOf(parseTranscript('copilot', noMarkers, PLUGIN)), [1]);+ assert.deepEqual(turnsOf(parseTranscript('copilot', read('copilot-app-builder.jsonl'), PLUGIN)), [0]);+ assert.deepEqual(turnsOf(parseTranscript('copilot', without(read('copilot-app-builder.jsonl'), /assistant\.turn_start/), PLUGIN)), [0]);+});++test('transcript(claude): the content blocks of one response share a turn, and the next response is the next turn', () => {+ const p = parseTranscript('claude', read('claude-look-then-skill.jsonl'), PLUGIN);+ assert.deepEqual(p.skillCalls.map((c) => [c.raw, c.turn]), [['model-apps:genpage', 1]]);+ // A text block and the skill call of the first response are two events of one turn.+ assert.deepEqual(turnsOf(parseTranscript('claude', read('claude-genpage.jsonl'), PLUGIN)), [0]);+});++test('transcript(claude): without message ids a tool result is what separates one response from the next', () => {+ const noIds = read('claude-look-then-skill.jsonl').replace(/"id":"msg_\d+",/g, '');+ assert.doesNotMatch(noIds, /msg_/);+ assert.deepEqual(turnsOf(parseTranscript('claude', noIds, PLUGIN)), [1]);+ assert.deepEqual(turnsOf(parseTranscript('claude', read('claude-genpage.jsonl'), PLUGIN)), [0], 'two events with nothing between them are one response');+});++test('transcript: a skill asked for in the same response as a workspace read is still the first turn', () => {+ const copilot = new TranscriptParser('copilot', PLUGIN);+ copilot.push(JSON.stringify({ type: 'assistant.turn_start', data: { turnId: '0' } }));+ copilot.push(JSON.stringify({ type: 'assistant.message', data: { content: '', toolRequests: [+ { toolCallId: 'a', name: 'view', arguments: { path: '.' } },+ { toolCallId: 'b', name: 'skill', arguments: { skill: 'genpage' } },+ ] } }));+ assert.deepEqual(turnsOf(copilot), [0]);+ const claude = new TranscriptParser('claude', PLUGIN);+ claude.push(JSON.stringify({ type: 'assistant', message: { id: 'msg_01', content: [{ type: 'tool_use', id: 'a', name: 'Read', input: {} }] } }));+ // The tool result of the first call can arrive before the response has finished streaming.+ claude.push(JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'a', content: 'x' }] } }));+ claude.push(JSON.stringify({ type: 'assistant', message: { id: 'msg_01', content: [{ type: 'tool_use', id: 'b', name: 'Skill', input: { skill: 'model-apps:genpage' } }] } }));+ assert.deepEqual(turnsOf(claude), [0], 'one message id is one response, whatever arrived between its blocks');+});++test('transcript: a built-in skill in the first turn does not make the plugin skill of the next turn a first-turn decision', () => {+ const p = new TranscriptParser('copilot', PLUGIN);+ const ask = (turnId, id, skill) => {+ p.push(JSON.stringify({ type: 'assistant.turn_start', data: { turnId } }));+ p.push(JSON.stringify({ type: 'assistant.message', data: { toolRequests: [{ toolCallId: id, name: 'skill', arguments: { skill } }] } }));+ };+ ask('0', 'a', 'brainstorming');+ ask('1', 'b', 'app-builder');+ assert.deepEqual(p.skillCalls.map((c) => [c.name, c.ofPlugin, c.turn]), [['brainstorming', false, 0], ['app-builder', true, 1]]);+});++// ---------- the grade is the whole trial, exactly as it was before the first turn was told apart ----------++const call = (name, turn, ofPlugin = true) => ({ raw: name, name, ofPlugin, turn });+const trialOf = (...calls) => ({ routedTo: (calls.find((c) => c.ofPlugin) || {}).name || null, skillCalls: calls });+const NEGATIVE = { id: 21, prompt: 'p', expect: null };+const POSITIVE = { id: 1, prompt: 'p', expect: 'genpage' };+const CASES = require('../evals.json').evals;+const caseById = (id) => CASES.find((c) => c.id === id);+// The negatives among the first 20 committed cases: the assertions the first-turn signal must leave as strict+// as they were.+const ORIGINAL_NEGATIVES = [3, 12, 13, 14, 15];++// The rule as it stood before the first turn was told apart, written out here so that nothing under test can+// move it: the first plugin skill the agent asked for, at any turn, must be one the case accepts.+const ORIGINAL_RULE_PASSES = (evalCase, trial) => {+ const accepted = [evalCase.expect, ...(evalCase.accept || [])].map((s) => (s == null ? 'none' : s));+ return accepted.includes(trial.routedTo == null ? 'none' : trial.routedTo);+};+const TRIAL_SHAPES = [+ trialOf(),+ ...['genpage', 'app-builder', 'report-issue', 'telemetry'].flatMap((skill) => [0, 1, 2].map((turn) => trialOf(call(skill, turn)))),+ trialOf(call('bash', 0, false), call('genpage', 1)),+ trialOf(call('brainstorming', 0, false)),+ { routedTo: 'genpage' },+ { routedTo: null },+];+const shapeLabel = (trial) => JSON.stringify(trial.skillCalls ? trial.skillCalls.map((c) => `${c.name}@${c.turn}`) : trial.routedTo);+// Enough shapes for every kind of three-trial case verdict: none, each of two skills in the first and in a+// later turn, and the two forms of a trial that carries only `routedTo`.+const VERDICT_SHAPES = [+ trialOf(), trialOf(call('genpage', 0)), trialOf(call('genpage', 1)), trialOf(call('app-builder', 0)), trialOf(call('app-builder', 1)),+ { routedTo: 'genpage' }, { routedTo: null },+];++test('the original negative cases are still negatives, and case 1 still expects /genpage', () => {+ for (const id of ORIGINAL_NEGATIVES) assert.equal(caseById(id).expect, null, `#${id}`);+ assert.equal(caseById(1).expect, 'genpage');+});++test('decisionOf: the first plugin skill is split by the turn that asked for it', () => {+ assert.deepEqual(decisionOf(trialOf(call('genpage', 0))), { initial: 'genpage', delayed: null, eventual: 'genpage', turn: 0 });+ assert.deepEqual(decisionOf(trialOf(call('genpage', 1))), { initial: null, delayed: 'genpage', eventual: 'genpage', turn: 1 });+ assert.deepEqual(decisionOf(trialOf(call('bash', 1, false))), { initial: null, delayed: null, eventual: null, turn: null });+ assert.deepEqual(decisionOf(trialOf()), { initial: null, delayed: null, eventual: null, turn: null });+ // The first PLUGIN skill decides, whatever was asked for before it.+ assert.equal(decisionOf(trialOf(call('bash', 0, false), call('app-builder', 1), call('genpage', 2))).delayed, 'app-builder');+ // A trial that carries only `routedTo` (a canned trial, an older results file) has no turn to split by.+ assert.deepEqual(decisionOf({ routedTo: 'genpage' }), { initial: 'genpage', delayed: null, eventual: 'genpage', turn: 0 });+ assert.deepEqual(decisionOf({ routedTo: null }), { initial: null, delayed: null, eventual: null, turn: null });+});++test('gradeTrial: a plugin skill asked for after a first turn that chose none is still the routing decision', () => {+ const fallback = trialOf(call('genpage', 1));+ const graded = gradeTrial(NEGATIVE, fallback);+ assert.equal(graded.status, 'fail', 'a negative case fails when the agent reaches for the plugin, in whatever turn');+ assert.equal(graded.outcome, 'genpage');+ assert.equal(graded.delayed, 'genpage');+ assert.match(graded.reason, /^routed to genpage \(asked for only after its first turn\), expected none$/);+ assert.equal(gradeTrial(NEGATIVE, trialOf(call('genpage', 0))).status, 'fail', 'and in the first turn');+ assert.equal(gradeTrial(NEGATIVE, trialOf()).status, 'pass');+ assert.equal(gradeTrial(POSITIVE, trialOf(call('genpage', 1))).status, 'pass', 'a right skill asked for late still passes a positive case, as it did');+ assert.equal(gradeTrial(POSITIVE, trialOf(call('genpage', 0))).status, 'pass');+ assert.equal(gradeTrial(POSITIVE, trialOf(call('app-builder', 0))).status, 'fail');+ assert.equal(gradeTrial(POSITIVE, trialOf(call('app-builder', 1))).status, 'fail');+});++test('gradeTrial: the initial decision is reported beside the grade and does not change it', () => {+ const late = gradeTrial(NEGATIVE, trialOf(call('genpage', 1)));+ assert.deepEqual(late.initial, { outcome: 'none', status: 'pass' }, 'the first turn chose none, which is what a negative case wants');+ const lateRight = gradeTrial(POSITIVE, trialOf(call('genpage', 1)));+ assert.equal(lateRight.status, 'pass');+ assert.deepEqual(lateRight.initial, { outcome: 'none', status: 'fail' }, 'the right skill came, but not in the first turn');+ const first = gradeTrial(POSITIVE, trialOf(call('genpage', 0)));+ assert.deepEqual([first.status, first.initial, first.delayed], ['pass', { outcome: 'genpage', status: 'pass' }, null]);+ const wrong = gradeTrial(NEGATIVE, trialOf(call('genpage', 0)));+ assert.deepEqual([wrong.status, wrong.initial, wrong.delayed], ['fail', { outcome: 'genpage', status: 'fail' }, null]);+});++test('gradeTrial: an errored trial stays an error, with no decision of either kind', () => {+ const graded = gradeTrial(NEGATIVE, { routedTo: null, error: 'boom', skillCalls: [] });+ assert.equal(graded.status, 'error');+ assert.equal(graded.initial, undefined);+});++test('gradeTrial: a trial that carries only routedTo is graded as before, and that is its initial decision too', () => {+ assert.equal(gradeTrial(POSITIVE, { routedTo: 'genpage' }).status, 'pass');+ assert.equal(gradeTrial(NEGATIVE, { routedTo: 'genpage' }).status, 'fail');+ assert.equal(gradeTrial(NEGATIVE, { routedTo: null }).status, 'pass');+ const graded = gradeTrial(NEGATIVE, { routedTo: 'genpage' });+ assert.deepEqual([graded.initial, graded.delayed], [{ outcome: 'genpage', status: 'fail' }, null]);+ assert.equal(graded.reason, 'routed to genpage, expected none');+});++test('the grade of every committed case is the original one, whatever turn the agent asked for its skill in', () => {+ assert.ok(CASES.length >= 35, 'the original cases and the ones added since');+ for (const evalCase of CASES) {+ for (const trial of TRIAL_SHAPES) {+ const want = ORIGINAL_RULE_PASSES(evalCase, trial) ? 'pass' : 'fail';+ assert.equal(gradeTrial(evalCase, trial).status, want, `#${evalCase.id} ${shapeLabel(trial)}`);+ }+ // The verdict of a case, at the default threshold: 2 of 3 trials must pass the original rule.+ for (const a of VERDICT_SHAPES) {+ for (const b of VERDICT_SHAPES) {+ for (const c of VERDICT_SHAPES) {+ const passing = [a, b, c].filter((trial) => ORIGINAL_RULE_PASSES(evalCase, trial)).length;+ const s = summarizeCase(evalCase, [a, b, c], 2 / 3);+ assert.equal(s.status, passing >= 2 ? 'pass' : 'fail', `#${evalCase.id} ${[a, b, c].map(shapeLabel).join(' ')}`);+ assert.equal(s.passes, passing);+ }+ }+ }+ }+});++test('summarizeCase: the whole trial is graded, and the initial decision is counted beside it', () => {+ const trials = [trialOf(call('genpage', 1)), trialOf(call('app-builder', 1)), trialOf(), trialOf(call('genpage', 1))];+ const s = summarizeCase(NEGATIVE, trials, 2 / 3);+ assert.equal(s.status, 'fail', 'three of the four trials reached for the plugin, after a first turn that did not');+ assert.equal(s.passes, 1);+ assert.deepEqual(s.outcomes, { genpage: 2, 'app-builder': 1, none: 1 });+ assert.deepEqual(s.delayed, { genpage: 2, 'app-builder': 1 });+ assert.deepEqual(s.initial, { passes: 4, valid: 4, rate: 1, outcomes: { none: 4 } });+ // The same lateness on a positive case: it passes, and the initial decision says it was late.+ const late = summarizeCase(POSITIVE, [trialOf(call('genpage', 1)), trialOf(call('genpage', 1)), trialOf(call('genpage', 0))], 2 / 3);+ assert.equal(late.status, 'pass');+ assert.deepEqual(late.initial, { passes: 1, valid: 3, rate: 1 / 3, outcomes: { none: 2, genpage: 1 } });+ const clean = summarizeCase(NEGATIVE, [trialOf(), trialOf()], 1);+ assert.deepEqual(clean.delayed, {}, 'nothing later, nothing to report');+ assert.deepEqual(clean.initial, { passes: 2, valid: 2, rate: 1, outcomes: { none: 2 } });+});++test('summarizeCase: an errored trial counts in neither signal, and a case of errors has no rate in either', () => {+ const errored = { ...trialOf(call('genpage', 1)), error: 'timed out' };+ const s = summarizeCase(NEGATIVE, [errored, trialOf()], 1);+ assert.deepEqual(s.delayed, {});+ assert.equal(s.valid, 1);+ assert.deepEqual(s.initial, { passes: 1, valid: 1, rate: 1, outcomes: { none: 1 } });+ const all = summarizeCase(NEGATIVE, [errored], 1);+ assert.equal(all.status, 'error');+ assert.equal(all.rate, null);+ assert.deepEqual(all.initial, { passes: 0, valid: 0, rate: null, outcomes: {} });+});++// ---------- the transcripts of an agent that reads the workspace first and then asks for a skill ----------++const FIXTURES = { copilot: 'copilot-look-then-skill.jsonl', claude: 'claude-look-then-skill.jsonl' };+const trialFromFixture = (agent) => {+ const parsed = parseTranscript(agent, read(FIXTURES[agent]), PLUGIN);+ return { routedTo: parsed.routedTo, skillCalls: parsed.skillCalls };+};++test('a transcript that reads the workspace and then asks for /genpage fails every original negative case, in both CLIs', () => {+ for (const agent of Object.keys(FIXTURES)) {+ const trial = trialFromFixture(agent);+ assert.deepEqual(decisionOf(trial), { initial: null, delayed: 'genpage', eventual: 'genpage', turn: 1 }, agent);+ for (const id of ORIGINAL_NEGATIVES) {+ const graded = gradeTrial(caseById(id), trial);+ assert.equal(graded.status, 'fail', `${agent} #${id}`);+ assert.equal(graded.outcome, 'genpage', `${agent} #${id}`);+ assert.deepEqual(graded.initial, { outcome: 'none', status: 'pass' }, `${agent} #${id}: no plugin skill in the first turn, reported beside the failure`);+ }+ assert.equal(gradeTrial(caseById(1), trial).status, 'pass', `${agent}: the /genpage case still passes, as it did`);+ assert.equal(gradeTrial(caseById(2), trial).status, 'fail', `${agent}: and the /app-builder case still fails`);+ }+});++// ---------- the runner's report ----------++const EVALS = { evals: [+ { id: 21, tier: 'smoke', prompt: 'generic react dashboard, no Power Platform', expect: null, trap: 'a disclaimer that still names the plugin' },+ { id: 1, tier: 'smoke', prompt: 'add a page to my app', expect: 'genpage' },+] };+const collect = () => {+ const lines = [];+ return { write: (l) => lines.push(l), text: () => lines.join('\n') };+};+const fallbackTrials = () => [trialOf(call('genpage', 1)), trialOf(call('genpage', 1)), trialOf(), trialOf(call('app-builder', 1))];+const trialsFor = () => ({+ 21: fallbackTrials(),+ 1: [trialOf(call('genpage', 0)), trialOf(call('genpage', 0)), trialOf(call('genpage', 0)), trialOf(call('genpage', 0))],+});+const runner = (byId) => async (_opts, c) => byId[c.id].shift();++test('runRouting: a negative case whose agent looked first and then asked for a skill fails, and says its first turn chose none', async () => {+ const out = collect();+ const file = path.join(os.tmpdir(), `routing-initial-${process.pid}.json`);+ try {+ const { exitCode, results } = await runRouting({ ...DEFAULTS, runs: 4, out: file }, { evalsData: EVALS, plugin: PLUGIN, write: out.write, runTrial: runner(trialsFor()) });+ assert.equal(exitCode, 1, out.text());+ assert.match(out.text(), /^not ok 1 - #21 \[smoke\] expect none — 1\/4 \(genpage×2, none×1, app-builder×1\) · first turn: 4\/4 \(none×4\) · later: genpage×2, app-builder×1$/m);+ assert.match(out.text(), /^ok 2 - #1 \[smoke\] expect genpage — 4\/4 \(genpage×4\)$/m, 'a case with no later fallback reads as it always did');+ assert.match(out.text(), /^# cases 2 \(pass 1, fail 1, error 0\)$/m);+ assert.match(out.text(), /^# later fallbacks: 3 trial\(s\) in 1 case\(s\) chose a plugin skill only after a first turn that chose none \(counted in the grade; the first-turn decision is shown beside each case\)$/m);+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));+ assert.equal('grade' in saved, false, 'there is one grade, and it is the whole trial');+ const negative = saved.cases.find((c) => c.id === 21);+ assert.equal(negative.status, 'fail');+ assert.equal(negative.rate, 1 / 4);+ assert.deepEqual(negative.outcomes, { genpage: 2, none: 1, 'app-builder': 1 });+ assert.deepEqual(negative.delayed, { genpage: 2, 'app-builder': 1 });+ assert.deepEqual(negative.initial, { passes: 4, valid: 4, rate: 1, outcomes: { none: 4 } });+ assert.deepEqual(negative.trials.map((t) => [t.initial, t.delayed, t.turn]), [[null, 'genpage', 1], [null, 'genpage', 1], [null, null, null], [null, 'app-builder', 1]]);+ assert.equal(negative.trials[0].routedTo, 'genpage', 'routedTo is still the first plugin skill of the run');+ const positive = saved.cases.find((c) => c.id === 1);+ assert.deepEqual(positive.initial, { passes: 4, valid: 4, rate: 1, outcomes: { genpage: 4 } });+ assert.equal(positive.trials[0].turn, 0);+ assert.equal(results.summary.fail, 1);+ assert.equal(results.summary.delayedTrials, 3);+ assert.equal(results.summary.delayedCases, 1);+ } finally {+ fs.rmSync(file, { force: true });+ }+});++test('runRouting: every original negative case fails on a run that read the workspace first and then asked for /genpage, in both CLIs', async () => {+ const cases = ORIGINAL_NEGATIVES.map(caseById);+ for (const agent of Object.keys(FIXTURES)) {+ const out = collect();+ const trials = Object.fromEntries(cases.map((c) => [c.id, Array.from({ length: 3 }, () => trialFromFixture(agent))]));+ const { exitCode, results } = await runRouting({ ...DEFAULTS, runs: 3, agent }, { evalsData: { evals: cases }, plugin: PLUGIN, write: out.write, runTrial: runner(trials) });+ assert.equal(exitCode, 1, `${agent}\n${out.text()}`);+ assert.equal(results.summary.fail, cases.length, agent);+ assert.equal(results.summary.pass, 0, agent);+ for (const c of cases) {+ assert.match(out.text(), new RegExp(`^not ok \\d+ - #${c.id} \\[${c.tier}\\] expect none — 0/3 \\(genpage×3\\) · first turn: 3/3 \\(none×3\\) · later: genpage×3$`, 'm'), `${agent} #${c.id}`);+ }+ }+});++test('runRouting: a positive case whose agent asks for the right skill only in turn 1 passes, and says it came late', async () => {+ const out = collect();+ const { exitCode } = await runRouting({ ...DEFAULTS, runs: 3 }, {+ evalsData: { evals: [caseById(1)] }, plugin: PLUGIN, write: out.write,+ runTrial: runner({ 1: [1, 2, 3].map(() => trialFromFixture('copilot')) }),+ });+ assert.equal(exitCode, 0, out.text());+ assert.match(out.text(), /^ok 1 - #1 \[smoke\] expect genpage — 3\/3 \(genpage×3\) · first turn: 0\/3 \(none×3\) · later: genpage×3$/m);+});++test('runRouting: a case that failed on later fallbacks says in its block that they are counted', async () => {+ const out = collect();+ const evalsData = { evals: [{ id: 21, tier: 'smoke', prompt: 'react, no Power Platform', expect: null, trap: 'a disclaimer' }] };+ const { exitCode } = await runRouting({ ...DEFAULTS, runs: 2 }, {+ evalsData, plugin: PLUGIN, write: out.write,+ runTrial: runner({ 21: [trialOf(call('genpage', 1)), trialOf(call('genpage', 1))] }),+ });+ assert.equal(exitCode, 1);+ assert.match(out.text(), /^not ok 1 - #21 \[smoke\] expect none — 0\/2 \(genpage×2\) · first turn: 2\/2 \(none×2\) · later: genpage×2$/m);+ assert.match(out.text(), /^ {2}later: "genpage×2 — asked for only after a first turn that chose none; counted in the grade, as is any skill the agent asks for"$/m);+});++test('runRouting: --compare compares the grade, as before, and adds no note about the first turn', async () => {+ const prev = path.join(os.tmpdir(), `routing-prev-grade-${process.pid}.json`);+ try {+ fs.writeFileSync(prev, JSON.stringify({ cases: [{ id: 21, rate: 0.75 }] }));+ const out = collect();+ await runRouting({ ...DEFAULTS, runs: 4, compare: prev, eval: 21 }, { evalsData: EVALS, plugin: PLUGIN, write: out.write, runTrial: runner(trialsFor()) });+ assert.match(out.text(), /^# delta #21: 0\.75 → 0\.25$/m);+ assert.doesNotMatch(out.text(), /# note:/);+ } finally {+ fs.rmSync(prev, { force: true });+ }+});++test('the initial decision is only ever reported: no option and no trial field makes it the grade', async () => {+ const fail = (message) => { throw new Error(message); };+ assert.equal('grade' in DEFAULTS, false);+ for (const argv of [['--grade', 'initial'], ['--grade', 'eventual']]) {+ assert.throws(() => parseArgs(argv, { fail }), /unknown argument "--grade"/, argv.join(' '));+ }+ // Nor through the programmatic seam the tests use.+ const out = collect();+ const { exitCode } = await runRouting({ ...DEFAULTS, runs: 4, grade: 'initial' }, { evalsData: EVALS, plugin: PLUGIN, write: out.write, runTrial: runner(trialsFor()) });+ assert.equal(exitCode, 1, out.text());+ assert.match(out.text(), /^not ok 1 - #21 /m);+});++// ---------- the whole path against a fake agent that looks before it acts ----------++const FAKE_TURNS = path.join(__dirname, 'fake-agent-turns.js');+const hasExited = (child) => child.exitCode !== null || child.signalCode !== null;++async function until(condition, what) {+ const deadline = Date.now() + 60000;+ while (!condition()) {+ if (Date.now() > deadline) assert.fail(`${what} did not happen within 60000ms`);+ await sleep(10);+ }+}++function lookFirstTrial(mode, agent) {+ let child;+ const trial = spawnTrial({+ agent, bin: process.execPath, binArgs: [FAKE_TURNS], args: [], env: { FAKE_AGENT_MODE: mode },+ prompt: 'Build a generic React dashboard website. No Power Platform.', cwd: os.tmpdir(), timeoutMs: 60000, plugin: PLUGIN,+ loadedSkills: agent === 'copilot' ? PLUGIN.pluginSkills : undefined,+ onStart: (s) => { child = s.child; },+ });+ return { trial, child: () => child };+}++test('spawnTrial: an agent that looks at its workspace and then asks for a skill is graded on that request, in both CLIs', async () => {+ for (const agent of ['claude', 'copilot']) {+ const run = lookFirstTrial(`${agent}-look-then-route`, agent);+ const t = await run.trial;+ assert.equal(t.error, null, agent);+ assert.equal(t.routedTo, 'genpage', agent);+ assert.deepEqual(decisionOf(t), { initial: null, delayed: 'genpage', eventual: 'genpage', turn: 1 }, agent);+ const graded = gradeTrial(NEGATIVE, t);+ assert.equal(graded.status, 'fail', `${agent}: the request is the routing decision, as it always was`);+ assert.deepEqual(graded.initial, { outcome: 'none', status: 'pass' }, `${agent}: reported beside it, the first turn chose none`);+ // `*-look-then-route` never exits on its own, so it has gone only because the runner killed it at the request.+ await until(() => hasExited(run.child()), `the ${agent} agent being killed at its skill request`);+ }+});++test('spawnTrial: an agent that looks at its workspace and then answers in text decided none, with nothing later', async () => {+ for (const agent of ['claude', 'copilot']) {+ const t = await lookFirstTrial(`${agent}-look-then-answer`, agent).trial;+ assert.equal(t.error, null, agent);+ assert.equal(t.routedTo, null, agent);+ assert.deepEqual(decisionOf(t), { initial: null, delayed: null, eventual: null, turn: null }, agent);+ }+});diff --git a/evals/model-apps/routing/tests/run-routing.test.js b/evals/model-apps/routing/tests/run-routing.test.jsindex f098bd2a7..7ddd69bcc 100644--- a/evals/model-apps/routing/tests/run-routing.test.js+++ b/evals/model-apps/routing/tests/run-routing.test.js@@ -172,10 +172,22 @@ async function until(condition, what) {const hasExited = (child) => child.exitCode !== null || child.signalCode !== null;-// A killed agent is torn down by the OS a moment AFTER the trial resolves, and until then it still holds-// its working directory: removing it straight away failed with `EBUSY: resource busy or locked, rmdir-// …routing-fake-…` on a loaded Windows machine (Node 22, one run in twenty). So a directory is removed-// by retrying while it is reported in use, up to a bound — never by hoping a kill has finished.+// A promise that must settle, raced against a bound: a run that never ends becomes a failure that says what+// never ended, not a test that hangs until the CI job's own timeout.+async function withinLimit(promise, what, ms = WAIT_LIMIT_MS) {+ let timer;+ const limit = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${what} did not happen within ${ms}ms`)), ms); });+ try {+ return await Promise.race([promise, limit]);+ } finally {+ clearTimeout(timer);+ }+}++// spawnTrial resolves only once the agent it killed has closed (the tests below pin that), so the agent no+// longer holds the trial's directory when this runs. The retry stays for a directory that some other process+// on the machine has open for a moment — Windows reports that as `EBUSY` or `EPERM` — and it is bounded, so+// a directory that stays in use fails the test instead of hanging it.async function removeWhenFree(dir) {const deadline = Date.now() + WAIT_LIMIT_MS;for (;;) {@@ -209,11 +221,19 @@ function manualClock() {return clock;}-function fakeTrial(mode, { prompt = 'build me a page', timeoutMs = 20000, agent = 'claude', env = {}, loadedSkills, loadError, clock, onStart } = {}) {+// `atResolve(child)` runs the moment the trial's promise settles, before the folder is removed. The order+// matters: removing the folder retries while it is in use, so on Windows it waits for the agent itself and+// would hide whether the agent was still running when the trial resolved.+function fakeTrial(mode, { prompt = 'build me a page', timeoutMs = 20000, agent = 'claude', env = {}, loadedSkills, loadError, clock, onStart, kill, closeWaitMs, atResolve } = {}) {const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'routing-fake-'));+ let child;return spawnTrial({agent, bin: process.execPath, binArgs: [FAKE], args: [], env: { FAKE_AGENT_MODE: mode, ...env },- prompt, cwd, timeoutMs, plugin: PLUGIN, loadedSkills, loadError, clock, onStart,+ prompt, cwd, timeoutMs, plugin: PLUGIN, loadedSkills, loadError, clock, kill, closeWaitMs,+ onStart: (s) => { child = s.child; if (onStart) onStart(s); },+ }).then((trial) => {+ if (atResolve) atResolve(child);+ return trial;}).finally(() => removeWhenFree(cwd));}@@ -247,6 +267,87 @@ test('spawnTrial: prompt reaches the agent on stdin; a routed agent is killed atawait until(() => hasExited(child), 'the routed agent being killed');});+// spawnTrial used to resolve the moment it killed the agent. A kill takes effect a moment later, and until+// then the agent still holds its working directory: a caller that removed the trial's folder as the trial+// ended got `EBUSY: resource busy or locked, rmdir …` on Windows (14 of 40 trials in a measured run). So the+// trial is over only when the agent has closed. None of the checks below needs a stopwatch: a process's exit+// code is set when it has really ended, so it still reads null if the trial resolved before that.+test('spawnTrial: the agent it killed at the decision has closed by the time the trial resolves', async () => {+ let exited;+ const t = await fakeTrial('route-then-hang', { prompt: 'make me an app', atResolve: (child) => { exited = hasExited(child); } });+ assert.equal(t.routedTo, 'app-builder');+ assert.equal(t.error, null);+ assert.equal(exited, true, 'the routed agent was still running when the trial resolved');+});++test('spawnTrial: the agent it killed at the deadline has closed by the time the trial resolves', async () => {+ const clock = manualClock();+ let parser;+ let exited;+ const trial = fakeTrial('init-then-hang', { timeoutMs: 1500, clock, onStart: (s) => { parser = s.parser; }, atResolve: (child) => { exited = hasExited(child); } });+ try {+ await until(() => parser.eventCount >= 1, 'the parser reading the init event');+ clock.fire();+ const t = await trial;+ assert.equal(t.timedOut, true);+ assert.match(t.error, /timed out before routing/);+ assert.equal(exited, true, 'the cut-off agent was still running when the trial resolved');+ } finally {+ if (clock.armed) clock.fire();+ await trial.catch(() => {});+ }+});++test('spawnTrial: a slow-dying agent is waited for — the trial ends when it has closed, not when it was told to die', async () => {+ // The kill lands 300 ms after the decision, so the agent is certainly still running right after it: a trial+ // that did not wait for the close would resolve with the agent alive.+ const killLater = (child) => { setTimeout(() => child.kill(), 300); };+ let exited;+ const t = await fakeTrial('route-then-hang', { prompt: 'make me an app', kill: killLater, atResolve: (child) => { exited = hasExited(child); } });+ assert.equal(t.routedTo, 'app-builder');+ assert.equal(t.error, null);+ assert.equal(exited, true, 'the trial resolved while the agent was still running');+});++test('spawnTrial: the wait for the agent to close is bounded — one that will not die cannot hold the run', async () => {+ // A kill that does nothing leaves the agent running for good. The trial must still end, after the bound, with+ // its routing decision intact. The agent is ended here, the moment the trial resolves, so that nothing is left+ // running and the folder can be removed.+ let child;+ let exited;+ const trial = fakeTrial('route-then-hang', {+ prompt: 'make me an app', kill: () => {}, closeWaitMs: 300,+ onStart: (s) => { child = s.child; },+ atResolve: (c) => { exited = hasExited(c); c.kill(); },+ });+ try {+ const t = await withinLimit(trial, 'a trial whose agent never closes resolving', 20000);+ assert.equal(t.routedTo, 'app-builder', 'the decision survives the wait');+ assert.equal(t.error, null);+ assert.equal(exited, false, 'the agent was still running — the trial gave up waiting for it');+ } finally {+ if (child && !hasExited(child)) child.kill();+ await until(() => hasExited(child), 'the stubborn agent being ended');+ }+});++test('spawnTrial: a run that ends on its own, or never starts, is not held for the close wait', async () => {+ // The wait is for an agent that was just killed. One that exited by itself, and one that never started, have+ // closed (or are about to) already: with a close wait of ten minutes these still resolve at once, so the+ // 30 s limit is only a hang detector.+ const closeWaitMs = 10 * 60 * 1000;+ const answered = await withinLimit(fakeTrial('answer', { closeWaitMs }), 'a self-ending run resolving', 30000);+ assert.equal(answered.error, null);+ assert.equal(answered.routedTo, null);+ const crashed = await withinLimit(fakeTrial('crash', { closeWaitMs }), 'a crashing run resolving', 30000);+ assert.match(crashed.error, /exited 3 before any routing decision/);+ const missing = await withinLimit(spawnTrial({+ agent: 'claude', bin: path.join(os.tmpdir(), 'definitely-not-an-agent.exe'), args: [], env: {},+ prompt: 'x', cwd: os.tmpdir(), timeoutMs: 5000, plugin: PLUGIN, closeWaitMs,+ }), 'a run that cannot start resolving', 30000);+ assert.match(missing.error, /could not start|exited/);+});+test('spawnTrial: a text answer ends the run as a "none" decision', async () => {const t = await fakeTrial('answer');assert.equal(t.routedTo, null);diff --git a/evals/model-apps/routing/tests/transcripts/claude-look-then-skill.jsonl b/evals/model-apps/routing/tests/transcripts/claude-look-then-skill.jsonlnew file mode 100644index 000000000..6953c5a96--- /dev/null+++ b/evals/model-apps/routing/tests/transcripts/claude-look-then-skill.jsonl@@ -0,0 +1,5 @@+{"type":"system","subtype":"init","cwd":"<workspace>","session_id":"00000000-0000-0000-0000-000000000000","tools":["Glob","Grep","Read","Skill"],"skills":["model-apps:app-builder","model-apps:genpage","model-apps:report-issue","model-apps:telemetry","design"],"plugins":[{"name":"model-apps","path":"<plugin>","source":"model-apps@inline","version":"2.16.0"}]}+{"type":"assistant","message":{"id":"msg_01","role":"assistant","content":[{"type":"text","text":"None of the available skills applies, so I will look at the workspace first."}]}}+{"type":"assistant","message":{"id":"msg_01","role":"assistant","content":[{"type":"tool_use","id":"toolu_21","name":"Glob","input":{"pattern":"**/*"}}]}}+{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_21","content":"No files found"}]}}+{"type":"assistant","message":{"id":"msg_02","role":"assistant","content":[{"type":"tool_use","id":"toolu_22","name":"Skill","input":{"skill":"model-apps:genpage","args":"Build a generic React dashboard website."}}]}}diff --git a/evals/model-apps/routing/tests/transcripts/copilot-look-then-skill.jsonl b/evals/model-apps/routing/tests/transcripts/copilot-look-then-skill.jsonlnew file mode 100644index 000000000..15a1d5ba0--- /dev/null+++ b/evals/model-apps/routing/tests/transcripts/copilot-look-then-skill.jsonl@@ -0,0 +1,11 @@+{"type":"session.tools_updated","data":{"model":"example-model"}}+{"type":"user.message","data":{"content":"Build a generic React dashboard website using mock property data. No Power Platform, Dataverse or model-driven app."}}+{"type":"assistant.turn_start","data":{"turnId":"0","interactionId":"00000000-0000-0000-0000-000000000001"}}+{"type":"assistant.reasoning","data":{"content":"The user rules out Power Platform, so none of the available skills apply. I will look at the workspace first."}}+{"type":"assistant.message","data":{"messageId":"m1","interactionId":"00000000-0000-0000-0000-000000000001","content":"","toolRequests":[{"toolCallId":"toolu_11","name":"view","arguments":{"path":"<workspace>"}}]}}+{"type":"tool.execution_start","data":{"toolCallId":"toolu_11","toolName":"view","arguments":{"path":"<workspace>"}}}+{"type":"tool.execution_complete","data":{"toolCallId":"toolu_11","success":true}}+{"type":"assistant.turn_end","data":{"turnId":"0"}}+{"type":"assistant.turn_start","data":{"turnId":"1","interactionId":"00000000-0000-0000-0000-000000000001"}}+{"type":"assistant.message","data":{"messageId":"m2","interactionId":"00000000-0000-0000-0000-000000000001","content":"","toolRequests":[{"toolCallId":"toolu_12","name":"skill","arguments":{"skill":"genpage"}}]}}+{"type":"tool.execution_start","data":{"toolCallId":"toolu_12","toolName":"skill","arguments":{"skill":"genpage"}}}diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 096a31060..8b1b9192d 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.16.0",+ "version": "2.17.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex 096a31060..8b1b9192d 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.16.0",+ "version": "2.17.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex e982321c9..2d72160de 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -111,7 +111,10 @@ Phase 1 specified an unreachable interactive flow for ~2.5 months. The same vali**one-sided tool declaration**: tool names are host-specific and every host silently ignores a nameit does not recognize, so a capability named only in one scheme is absent on the other host and theagent launches without it. `TaskCreate`/`TaskUpdate`/`TaskList` are the live example — no published-alias table lists them, so `todo` must be declared alongside. Both skills also support **unattended+alias table lists them, so `todo` must be declared alongside. Recognizing a name is not delivering the+tool, though: a Copilot CLI session gave `genpage-page-builder` no task tool at all, so an agent's+task-tracking step says what to do without one (`references/agent-interaction-contract.md`, pinned by+`scripts/tests/agent-task-tracking.test.js`). Both skills also support **unattendedruns** (Copilot autopilot / Claude auto-accept) via`scripts/resolve-interaction-mode.js`; suppressing a prompt never authorizes destructive work.For the end-to-end flow,@@ -134,7 +137,15 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`scripts/write-page-plan.js` for why the app-builder page plan is not `genpage-*`.- **`scripts/lib/spec-lint.js`** — pure App Spec guardrail (`lintAppSpec → { ok, errors,warnings }`): errors block the plan gate (e.g. the relationship-name-vs-lookup-name- collision Dataverse rejects), warnings teach.+ collision Dataverse rejects), warnings teach. The access advice is worded for what a spec can+ know (`lib/app-access.js`): no `personas[]` says the spec authors no security role and who can+ open the app only as a condition — a spec for a new app and an extension of an app that already+ has roles look alike, and the app's own roles are the ones associated with it, which a spec with+ no personas leaves as they are — except that the marks a download writes (`app.uniqueName`, a+ page or dashboard id) make it say the spec most likely edits an existing app. A new table (an `entities[]`+ entry not marked `existing`) that no persona privilege and no `roleGrants[]` entry covers gets+ one "no access declared" warning, the check an extension that leaves `personas[]` out on purpose+ still needs.- **`scripts/lib/app-source-path.js`** — shared resolver for page `codeFile` and web-resource`contentPath` reads/uploads and hashing. Validation/lint share its lexical rule; the resolverrequires a relative, regular file inside the canonical app folder and refuses source symlinks@@ -181,29 +192,52 @@ the pipeline and delegates each script's **behavioral spec** to the entries belodeclares; a translation the spec leaves out is never required or changed. A caption the published form holds onlyin ANOTHER language does not stand in for the declared one: a missing caption is a mismatch, not a pass, and so isa caption missing in a language the form's read carries (a language the read carries no label in at all is- unverified, below); a label the spec does not write is not compared. **A string label is never held to a guessed+ read from a translation export, below); a label the spec does not write is not compared. **A string label is never held to a guessedlanguage.** A build run with `--language-code` in an organization whose base language is another one publishes itscaptions in the flag's language, so verify it with the same flag (or pin `languageCode` in the spec): told nothing,verify holds them to the organization's language, and either the failure says so or, when the read carries no- label in that language, the captions are listed as unverified. When no language can be established at all —+ label in that language, the export is asked for them (below). When no language can be established at all —the organization cannot be read — the string labels are listed under `unverified` (the output, and the resultJSON beside `missing`), neither passed nor failed, with the reason and the flag that settles it: the build'sfallback to 1033 is a choice for a build, and for verify it would be a guess that passes a stale caption asreadily as it fails a correct one (`resolveLanguageCode`'s `undetermined` hook replaces it). Everything else is- still checked, label maps included. **A language the form's read does not carry is never reported missing.** The platform+ still checked, label maps included. **A language the form's read does not carry is never reported missing — a+ translation export reads it.** The platformdecides which languages' labels go into the FormXML a caller reads, and it can return fewer than the form stores —measured: a form built and published with Spanish (3082) captions in an organization whose base language is English- (1033) keeps both languages (a translation export finds them), yet its published FormXML, with or without an- `Accept-Language` for the other language, carries every label in 1033 alone. When no label of the form's FormXML — on any- element, a field's included — is in the language a label is compared in, the labels compared in that language are listed- under `unverified` too (`form-labels:<table>.<form> (… in language 3082 … not compared: the environment's form read- returns labels only in 1033, so labels written in 3082 cannot be read back from it. Check … in Power Apps with that- language, or verify in a language the read carries)`), neither passed nor failed, with `ok` and the exit status unchanged;- a label map is compared at the languages the read carries and the others are listed the same way (`verifySpec`'s- `carriedLanguages`, `parseFormTopology`). A language the read does carry is compared exactly as above — a stale caption in- it still fails — and a form whose read carries no label at all names no language, so its missing caption is a- mismatch as ever. Translations are not read another way (a translation export, `RetrieveLocLabels`): what a caller's- FormXML cannot show is not verified. Field order and anchor adjacency are not verified. A field's `readOnly`/`hidden` flag goes on+ (1033) keeps both languages, yet its published FormXML, with or without an+ `Accept-Language` for the other language, carries every label in 1033 alone (nor does `RetrieveLocLabels` apply to a form's+ `formxml`: HTTP 400). When no label of the form's FormXML — on any+ element, a field's included — is in the language a label is compared in, the labels compared in that language are looked up in+ ONE translation export of the app's solution (`lib/translation-labels.js`; `POST …/solutions/Microsoft.Dynamics.CRM.ExportTranslation`+ with `{ "SolutionName": "<uniquename>" }` — bound to the `solutions` collection, the unbound action answers 404 — whose answer is a+ base64 zip holding `CrmTranslations.xml`, an Excel 2003 XML spreadsheet; its `Localized Labels` sheet has one row per caption,+ `Entity name | Object ID | Object Column Name | <one column per provisioned language, headed by its LCID>`, a tab's or section's row being+ the one whose Object ID is the `id` the element has in the FormXML and whose column is `displayname`, an empty cell meaning no caption in that+ language). They are matched by the table and the `id` of the tab or section the form's read matched (`parseFormTopology` keeps it), in the+ language the spec declares: the text it holds is the declared one → the caption passes; another text, or an empty cell, is a+ `form-topology` mismatch (`… is deployed with label "Antiguo" in language 3082 (the translation export of solution 'S' shows it; the form+ read does not carry language 3082), the spec declares label: "Resumen" in language 3082`); a label map is compared the same way, language+ by language, and the languages the read carries stay compared from the read (`verifySpec`'s `carriedLanguages`). **What the export cannot+ settle stays unverified, as it was before verify read exports, and never passes:** it fails or is not readable with certainty (an+ HTTP error, an answer that holds no archive, an archive or a workbook that is damaged or is not the platform's — `lib/zip-read.js` reads+ the archive and `lib/strict-xml.js` the workbook, both strict and dependency-free, and a row or cell they do not recognise makes the+ WHOLE export unreadable, never a skipped row: every element and attribute of the `Localized Labels` sheet must be one the platform writes,+ where it writes it — a prefixed or unknown element, a namespace declaration, a Number-typed caption, a workbook nested deeper than the+ platform's or an archive whose entries do not lie end to end is refused, and refused while it is read, before it can cost the process its+ memory), the FormXML gives the element no GUID id, the export has no row for it (the+ solution's tables are exported, not only its forms, but a form of another table is no proof of this one) or more than one, or no column+ for the language (it is not provisioned): the entry then says why — `A translation export of solution 'S' could not be read (…)` or+ `… was read, but it cannot settle them: …` — before what to check in Power Apps; `ok` and the exit status are unchanged. **What it+ costs:** one `ExportTranslation` request, made only when some caption needs it (a build and verify in the language the read carries, or a spec with no labels, make+ none), once per verify pass whatever the number of forms (the pass shares one promise), and sent ONCE — never again on a throttled,+ unavailable or timed-out answer (`isTranslationExport` is the `sendOnce` rule of the verify and build HTTP clients), because it is a long+ action and a re-send would start a second export beside the first. Measured live: 7.5–11.2 s and a 5 KB zip (44 KB of XML) for a solution+ of one table, more as the solution grows — it exports every label of every form of its tables — and it reads the PUBLISHED layer (a caption+ saved and not published is not in it, which is what verify checks); Microsoft Learn documents the export for an unmanaged solution, which is what the build makes. A workbook of more than 32 MiB (about+ 75,000 rows; reading it costs ~15 bytes of memory per byte of XML) is not read. A language the read does carry is compared exactly as+ above, from the read — a stale caption in it still fails — and a form whose read carries no label at all names no language, so its missing+ caption is a mismatch as ever, with no export. Field order and anchor adjacency are not verified. A field's `readOnly`/`hidden` flag goes on**every** cell the form holds of the field — in a section, in a maker's tab or section, in the form**header and footer**, and in a tab's own header and footer (`tabheader`/`tabfooter`): on a form a maker placed afield on twice, the first cell alone left the second editable or visible. `applyFieldControlOptions` visits each@@ -372,6 +406,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belobuttons** (`commands[]` — functional JS on-click + static hidden/disabled, incl. **flyout/split-buttonmenus** via `type`+`children[]`), and **dashboards** (`dashboards[]` — chart/list/iframe/webresourcetiles) with **sitemap placement** (a `dashboard` subarea auto-pins the dashboard as an app component).+ A tile the spec does not size is built 1 column by 12 rows (`dashboardComponent`), because the app draws+ a one-row tile as its title bar alone; an authored `colspan`/`rowspan` wins, and a rebuild never resizes+ the tiles of a dashboard that exists. The cells are read back from the real bundle in+ `dashboard-roundtrip.test.js`.It also builds **business process flows** (`businessProcessFlows[]` — the staged process bar on arecord): a `workflows` row of category 4 / type 1 / businessprocesstype 0 whose XAML the SDK compilesfrom ordered `stages[]`/`steps[]`, activated in the same push. The phase is additive@@ -538,8 +576,8 @@ the pipeline and delegates each script's **behavioral spec** to the entries belonothing; and sending it again cannot write a page twice: a create's ids are minted before the first send (a send that was in fact processed meets itself on them and is rolled back whole), and an update's turn carries one identity from whichthe SDK derives its messages' ids. An update's send goes through the SDK's version check again, so a page someone saved during the wait is refused as `VERSION_CONFLICT` and not written over — which is why the backend sends it again one push at a time and theHTTP client does not replay the request itself: an update's writes carry `If-Match: *`, and `lib/sdk-http-client.js` re-sends a `$batch` only when it is made of conditional deletes (or, for a 429, of column creates). The wait is the schedule that client gives every throttled- request (`throttleBackoffMs`: 1 s, 2 s, 4 s, 8 s, 8 s, plus jitter) or the answer's `Retry-After` when that asks for longer, **waited whole** — the client's cap of a minute is for its own retries — inside **one budget of five minutes for the waiting a throttled page write costs a build run**- (`lib/throttle-budget.js`): the build makes it and hands it to every page write (`args.throttle`; a resumed create that brings an earlier payload up to date hands the same budget — the one it was given, or the one it made for itself — on to the update it makes, so that update does not start five minutes of its own; the upload script, which is not a build, spends a budget of its own for its write and announces a long wait on stderr as `WARNING: …`), and the build's own waits before it runs a phase again after a throttle come out of the same budget, so a service that keeps asking for a minute cannot cost one page twenty silent minutes. **The budget bounds the waiting the build's OWN layers add — the page backend's resends of a page's `$batch`, which the HTTP client never re-sends, and the build's phase restarts — and not all the waiting a run does.** The production HTTP client keeps its own schedule for the requests it re-sends — a read, a publish, a delete, a column create: at most five re-sends, each waiting 1, 2, 4, 8 and 8 s or the answer's `Retry-After` when that asks for longer, up to a minute — exactly as it did before the budget existed, and none of it is drawn from the budget: charging it would halt a throttled build that succeeds today. So a run's total waiting is not bounded by the five minutes, and each request keeps the bound it always had (`sdk-build-pages-deploy.test.js` pins it: ten minutes of waiting, five of them inside the budget, and a build that succeeds).+ request (`throttleBackoffMs`: 1 s, 2 s, 4 s, 8 s, 8 s, plus jitter) or the answer's `Retry-After` when that asks for longer, **waited whole** — the client's cap of a minute is for a client that has no budget — inside **one budget of five minutes for the waiting a throttled page write costs a build run**+ (`lib/throttle-budget.js`): the build makes it and hands it to every page write (`args.throttle`; a resumed create that brings an earlier payload up to date hands the same budget — the one it was given, or the one it made for itself — on to the update it makes, so that update does not start five minutes of its own; the upload script, which is not a build, makes a budget of its own for its run and hands it to its backend, so that its write and its backend's HTTP client draw from it, and announces a long wait on stderr as `WARNING: …`), and the build's own waits before it runs a phase again after a throttle come out of the same budget, so a service that keeps asking for a minute cannot cost one page twenty silent minutes. **The budget bounds all the waiting a run does for a throttle — the HTTP client's waits as well as the backend's and the build's.** The production HTTP client (`lib/sdk-http-client.js`) draws every wait it takes before it sends a throttled request again — a read, a publish, a delete or a column create answered HTTP 429, alone or as every operation of a `$batch` — from the run's budget (`deps.throttle`: the build hands it to the client its SDK is made over and to the page backend, which gives it to the client it makes; the upload script hands its backend one). Such a wait is what the answer's `Retry-After` asks, **whole** — the client's own cap of a minute is for a client with no budget — or its schedule (1, 2, 4, 8 and 8 s) when that is longer, and it is placed on the clock: the requests the build sends at once are throttled together and wake together, so their waits overlap, and the budget is charged for the time the run waited and not for the sum. A wait that does not fit is **not taken**: the throttled answer comes back as it came — the SDK reports the 429 it is, a refusal that started nothing, and not a failure of the transport, which it would treat as an unknown outcome — and the client tells the budget what the service asked (`decline`; the SDK's error holds no headers), which the build's retry loop reads: the build stops with `throttle-budget-exhausted`, saying what the service asked, on the last run as on the first, and does not run the phases again to meet the same answer. The line the client says about a wait it refused (`refusedWait`, on the `warn` seam) is the fact alone — what the service asked, and that the request was not sent again — and gives no advice on what to run: a request the client refuses can follow a write that committed (the upload's publish follows its create, where the same command again would make a second page), so the way on is the caller's to give — the build's halt says a later run continues, and the upload's result names the page that was saved and the command that finishes it (`--page-id <id>` added). **After the budget has refused a wait no step of the engine starts.** The refusal can be swallowed on its way up — a best-effort step reports a failure and goes on, and the column change set's fallback answers a refused request with others — and the run would keep sending requests to a service that asked it to hold back, and could end as a success. So the engine's runner (`makeRunner({ throttle })` in `lib/entity-provision.js`: the build makes one for each run of the phases and hands it the run's budget) stops the phase with the budget's halt at the next step — `run`, and each item of its `mapLimit` (`stopIfRefused` is the same check for code that must decide before it writes, as the column change set does): a best-effort step does not run and reports it as a warning, the next required step stops the build, and the retry loop reports `throttle-budget-exhausted` as it does for any refusal of the budget. The guarantee is at the grain of the engine's steps. A step that is already running finishes; what pays what the run owes is let through (`settling`: the name column's length of a table the run created, which no later run can set — a run that finds the table leaves its name column as it is, so a stop would leave the table at the platform's default for good — and which is therefore paid in the settlement of a halted data-model phase and in the pass that completes one, where the refusal of one table's update does not keep the next table's from being set; the publishes and lengths the retry loop settles after a halt use runners of their own); and a runner given no budget never stops, as before. What is not throttling keeps its own schedule and is not drawn from the budget — a 5xx (a customization lock or a SQL deadlock victim is a 500, a gateway's hiccup a 502, 503 or 504) whatever `Retry-After` it carries, a reset connection, the re-send of a deadlock victim — and so does a client that is given no budget: the pcf plugin's copy of the file has none, and neither has the client of any script but the build and the page upload (`dataverseRequest`'s own two re-sends, after 2 s and 4 s, are not the client's). `sdk-http-client.test.js` and `sdk-build-pages-deploy.test.js` pin it: ten minutes of throttling in all stop the build with the budget's halt, a client with no budget waits as it always did, and a run that waits less than the five minutes succeeds.The SDK's error carries no headers, so `watchThrottles` listens to the answers of the page's `$batch` as they pass (a delegating Proxy over the client, as theapp-component scope and the guards over it are: every other member is read from the client and runs on it, so a client whose methods keep private state, or a frozen one,works through it, and nothing is written to the client) — at@@ -549,7 +587,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloA **resumed** create is not sent again this way: an earlier request is open, and the refusal is judged by reading the page, as above. A throttle that outlasts the waits — or whose next wait does not fit what is left of the budget — is reported as`outcome: 'nothing'` with the 429 as its cause and — alone among the errors a page write raises — **without** `transient: false` (`throttledError`), carrying `statusCode: 429` and what the last answer asked (`retryAfterMs`, and `retryNotBefore`: the moment before which nothing may be sent), so the build runs the phase again (`isTransientHalt` reads the 429 from the cause chain) and **waits for what the service asked, not for its own shorter backoff**(`throttleAskOf`, build-model-app.js); a wait that does not fit the budget is not taken, and the build stops with `throttle-budget-exhausted` — a transient halt that says the service asked to wait N seconds and that a later run continues. A wait of more than five seconds is announced on stderr (`⚠ …`, through the `warn` seam: stdout carries the JSON result). Nothing was written, so the page is sent once, by the run- that gets through. A 502, 503 or 504 is not waited out as a throttle: an intermediary answered, so the write may have committed and it is *unknown*, settled by reading the page as above; only the `Retry-After` it carries is waited for *before* that read, so a request still on its way has had the time to land — a wait that is counted in the budget (at most a minute, at most what is left) and never stops the write. A write that was throttled and then taken says so in the `warnings` of its result (which the build prints with the page's name), so a build that paused for a while says why.+ that gets through. The reads that come before any send are treated alike when the budget refused them: an update's read of the page it is about to change, and the read behind `read`, `describe` and `delete`, throttled until the budget had no room to wait for them, are `GENPAGE_UNREADABLE` with `statusCode: 429` and what the service asked — and, like the write's, **without** `transient: false` — so the build stops with `throttle-budget-exhausted` for them as well, instead of reporting a page that cannot be read; a read that failed any other way, or whose sends ran out while the budget still had room, is final, as it was. A 502, 503 or 504 is not waited out as a throttle: an intermediary answered, so the write may have committed and it is *unknown*, settled by reading the page as above; only the `Retry-After` it carries is waited for *before* that read, so a request still on its way has had the time to land — a wait that is counted in the budget (at most a minute, at most what is left) and never stops the write. A write that was throttled and then taken says so in the `warnings` of its result (which the build prints with the page's name), so a build that paused for a while says why.**Every other page-write error carries `transient: false`** (with `outcome`, `nothing` or `unknown`, and the page's `pageId` whenever the write got as far as the send), on the error itself: the build re-runs a phase when a failurereads as transient (`isTransientHalt`, build-model-app.js, by the rule of `lib/retry-policy.js`), and an error that says `transient: false` — on itself or anywhere along its causes — is never run again, so without the marker a re-run would send a write again. A *publish* that fails after a write is not an error: it is returned (`publish.kind: 'failed'`) with thepage's id, because the caller must still record that the page exists. It carries the failure itself as a non-enumerable `cause`, which is what the build decides from. The build halts on it as `pages-publish-failed` (re-runnable: the page is reused and published, not written again) and the@@ -562,7 +600,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belofails there**, and a code that is raised nowhere any more fails too. The pages phase's refusals that quote a page's name (or another app's, or a navigation key) and that a run again cannot change — the scan's refusals of a page's source (`pages-malformed-navref`, `pages-nav-parity`, `pages-stray-pageref`, `pages-dangling-navref`,`pages-source-not-utf8`, `pages-blank-provenance`, `pages-griffel-shorthand`), the identity and duplicate-name conflicts (`pages-identity-conflict`, `pages-duplicate-name-create`), the creation receipt that cannot be saved (`pages-creation-receipt-failed`), a page another app holds(`pages-shared-across-apps`) and an update that answers with another page's id (`pages-update-identity-mismatch`) — are `RETRY.NEVER`: a page called "SQL Timeout Report" would otherwise make any of them read as a SQL timeout, and the page- would be run three more times, after every earlier phase, with a log that blames the service. The halts that wrap a failure of the service (`pages-publish-failed`, `pages-existence-failed`, `pages-sitemap-read-failed`, `pages-shared-check-failed`) follow it: a 429 or a 503 is run again, a refusal is not. A listing that fails *before*+ would be run three more times, after every earlier phase, with a log that blames the service. The halts that wrap a failure of the service (`pages-publish-failed`, `pages-existence-failed`, `pages-sitemap-read-failed`, `pages-shared-check-failed`, `pages-read-throttled`) follow it: a 429 or a 503 is run again, a refusal is not. A listing that fails *before*anything is written leaves nothing to duplicate, and is retried like any transient halt. A transient halt *later* in the same run (a 503 on a later read or write, say) still re-runs the whole build,which reads each page again — as each rebuild does — and a page that already holds its content is not written (and is published only if this workspace did not record that this very content was published), so its history does not record the prompt again.**All of the build's Dataverse access is via the SDK** (see "Dataverse Access From Scripts" for the@@ -587,7 +625,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belocreates anything: a record whose key and id already have a **creation receipt** — the create was acknowledged and only the removal of its record failed — is consumed first, without proving the pageagain (a page edited since its create no longer holds what was sent, and that proof would halt the build over a page it made and recorded); otherwise the page is there and holds what a create under the id sent (its name and its source, read) — it is **adopted** (a creation receipt is written, the record consumed, and the page isupdated like any page that build created, which also brings what an earlier create sent — another model, an older name — to what this build asks for); there and holding something else — a conflict- (`pages-identity-conflict`: not adopted, not updated); not there — the create is sent again under the SAME id (a first send still in flight collides on it), and when the key is bound to another page+ (`pages-identity-conflict`: not adopted, not updated); a page that cannot be read is a conflict as well, unless the read was throttled and the run's budget had no room to wait for it — the build then stops for a later run (`pages-read-throttled`, which the retry loop reports as `throttle-budget-exhausted`) and the record stays; not there — the create is sent again under the SAME id (a first send still in flight collides on it), and when the key is bound to another pageinstead, nothing is created and **the record is kept**: an absence is one snapshot, not proof that the request which would make the page cannot still land. The page that lands later is then found by therecord — adopted for its key if the key is free, or reported as an unused page this build made (it has a creation receipt, so teardown finds it) when the key is bound to another one. A pending record isintent, not ownership: it is not a receipt, so it never authorizes an update (`readPageOwnership` does not see it). Teardown deletes a page it finds under a pending id — in the saved layer, so a page that@@ -804,38 +842,41 @@ the pipeline and delegates each script's **behavioral spec** to the entries belodescription have), so a spec that leaves the description out or carries the `""` a download writes never blanksone a maker typed; the spec wins over a text changed in Maker, as it does for those. The unique name is the app'sidentity and is never written: a spec that pins `app.uniqueName` (a download does) is renamed, one that does not- names a different app. **The header is written only while both texts are plain text.** Both columns are localizable,- and a plain write of the base-language text has not been measured to keep the translations beside it, so a name or- description that comes back as one text per language — or as any other value that is not a string — is never sent:- not as a map (these are String columns), and not replaced by a scalar. The SDK's one header PATCH carries the- artifact's `name` AND `description` whichever of them an edit changed (pinned in- `app-header-text-real-bundle.test.js`), so leaving that one field alone is not enough: while either text is not- plain **no header edit is made at all** — not the other text's, and not a requested routing description — and each- edit the spec asked for is reported as not applied, with the reason (change it in Power Apps). That is a warning,- never a halt: the push is the navigation alone, as for a rebuild with no edit. A localized text the spec's own text- already equals needs no edit and no word. **That whole-header hold is the chosen policy, and the SDK is the reason:**- it has no partial header write — its PATCH is built from the whole workspace copy and the row token that conditions it- is private to it. The plugin therefore cannot send only the one plain field that changed: a PATCH of its own would- need a row token read afresh (a blind overwrite of whatever changed since the fetch), and taking the text that is not- plain off the copy for the SDK to leave out would lean on an SDK internal — the serializer dropping `undefined` — whose- failure (a re-vendor that writes `name: ''`) blanks an app's name. A plain edit beside a text that is not plain is- held back, with a warning, rather than sent alone. Writing only the changed field needs an SDK operation (a partial- header write): a follow-up, after which the hold can be narrowed to the one field (the real-bundle pin that the PATCH- carries both texts fails the day the bundle makes it partial).- **The hold is on the workspace copy, and the SDK decides for itself whether the header is written** (`lib/app-header-text.js`).- Its push reads the app's header and compares it with the copy; its "write needed" flag starts true and only a 2xx+ names a different app. **A text that is not plain is never sent, and it holds nothing else back.** Both columns are+ localizable, and a plain write of the base-language text has not been measured to keep the translations beside it, so+ a name or description that comes back as one text per language — or as any other value that is not a string — is never+ edited and never sent: not as a map (these are String columns), and not replaced by a scalar. Its own edit is reported+ as not applied, with the reason (change it in Power Apps) — a warning, never a halt; a localized text the spec's own+ text already equals needs no edit and no word. The other text and a requested routing description are applied as usual:+ the SDK's header PATCH carries only the texts that changed (cds-maker-sdk 9a0c9f03; pinned in+ `app-header-text-real-bundle.test.js`), so a localized name beside a changed plain description writes the description+ alone and leaves every translation of the name as it is, and the reverse. (While the SDK wrote the whole copy in every+ header PATCH, one text that was not plain held the whole header back, and this paragraph said so.)+ **A text that is not plain is kept off the wire by being taken off the workspace copy**, right before the push+ (`takeNonPlainTextOffCopy`, called by `pushAppHeader`, `removeElement('app', id, '/name')`): the SDK neither compares nor+ writes a text that is not on its copy — now its documented contract, where it was once an SDK internal (the serializer+ dropping `undefined`) whose failure, a re-vendor that writes `name: ''`, would blank an app's name; the real-bundle+ tests pin it, and that the push saves, leaves the copy clean and that a plain fetch brings the maker's text back. The+ texts to take off are what `applyAppHeader` answers as `held`; it edits the copy no further than the edits themselves.+ The push is where they come off — not the edit — because a copy that holds an edit no push follows is refused by the next+ run (`refuseUnpushedAppCopy`): the routing description of a page-backed app is pushed only when it changed.+ **Taking it off the copy is what makes it safe when the SDK's own read fails** (`lib/app-header-text.js`).+ The SDK's push reads the app's header and compares it with the copy; its "write needed" flag starts true and only a 2xxanswer sets it, so a read that cannot be made (HTTP 503 or 403, a thrown error) leaves it true, and an empty 200 is- compared with an empty header, which differs: the header is written from the copy as it is, a text that is not plain- included — even when the build edited nothing. So the HTTP client every SDK is made- with (`lib/maker-sdk.js` is the one way a script makes one) refuses a PATCH of an app module row whose `name` or+ compared with an empty header, which differs: it then writes every text the copy holds, the text that is not plain+ included — which is why the hold on the edit alone was never enough. With the text off the copy, only the other text is+ written then (the copy's own, on the row's token, as for a plain header), and the build goes on.+ So the HTTP client every SDK is made+ with (`lib/maker-sdk.js` is the one way a script makes one) still refuses a PATCH of an app module row whose `name` or`description` is not a string, before any byte is sent: `APP_HEADER_NOT_PLAIN_TEXT`, an `SdkError` the bundle rethrows- as it is, marked `transient: false` (the build never runs the phase again on its own for it). Nothing is sent, and the- SDK writes the header before the navigation, so the push wrote nothing of the sitemap either; the copy is reset to the- server's, the halt is `app-shell failed: …` (or `pages failed: …` at the finalizer) with that code, and its message says- the header holds a text that is not plain, that nothing was written, and that the SDK only tried because its own- comparison read failed — so a re-run normally succeeds. Pinned over the real bundle for each way that read fails, a- localized and an array-valued text, and both complete push sites, in `app-header-text-real-bundle.test.js`. No PATCH the- build makes carries a map, a list or a scalar over a text that is not plain.+ as it is, marked `transient: false` (the build never runs the phase again on its own for it). It is the last line of+ defence, for a push of a copy the build did not clean — the page backend's push of the app, which fetches its own copy —+ and the build's own push never meets it. Nothing is sent, and the SDK writes the header before the navigation, so the+ push wrote nothing of the sitemap either; the halt is `… failed: …` with that code, and its message says the header holds+ a text that is not plain, that nothing was written, and that the SDK only tried because its own comparison read failed — so+ a re-run normally succeeds. Pinned over the real bundle for each way that read fails, a localized and an array-valued text, in+ `app-header-text-real-bundle.test.js` (the build's push goes on without the text; a push of the copy as the SDK holds it is+ refused).**The guard stands in front of every door the SDK's client has, not only `patch`.** A PATCH of the app module row thatrides in a raw change set (`sdk.dataverse.postBatch`, which sends the body a caller rendered through the client's`postRaw`, or the same text through `post`) or in `patchRaw` is refused the same way — the same typed, non-transient@@ -1624,7 +1665,15 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo(`relationshipCollisions: 'warn'` and `columnValues: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:Nthat share a schema name, an AutoNumber column with no format, a `required` that is not `true`, `false` or `"recommended"` — isverified, with a warning that names the fix, and is never refused before anything is read (the build, the lint and the- provisioning gate keep these as errors). It works through a throwaway SDK workspace, never the folder's `.maker-workspace` (which belongs to+ provisioning gate keep these as errors). **Every `WARNING:` line it prints on stderr — those findings, the spec's other warnings, and a page+ workspace it could not remove — is also in the result JSON's optional `warnings` array** (the same messages, without the prefix, in the order+ printed; left out when there is none, as `unverified` is), so a caller that reads only the JSON loses none of them. It is there on a failed+ verification and on a refused spec (`{ ok: false, errors, warnings }`, whose warnings are printed too) as on a passed one, and changes neither+ `ok` nor the exit status; a run that stops on an unexpected error prints that error on stderr and no JSON, as ever. **The result JSON is pure ASCII**+ (`emitResult`'s `{ ascii: true }`): every character above U+007E — the em dash of a warning, a Spanish label or a Japanese form name in a+ message — is a `\uXXXX` escape that any JSON parser reads back as the original text, because Windows PowerShell 5.1 decodes a child's stdout+ with the OEM code page and garbles a raw one; stderr is for people and is not escaped (`verify-model-app.test.js` pins both on the process, for a+ refused spec and, over `tests/helpers/fake-verify-preload.js`, for a completed verification). It works through a throwaway SDK workspace, never the folder's `.maker-workspace` (which belongs tothe environment it was first opened for): every read it makes goes to the server, so it verifies anyenvironment the app is deployed to and creates or binds nothing in the folder. It only READS the build'sbaseline, `last-applied.json`, from `--workspace`, and only when that baseline describes this@@ -1633,6 +1682,15 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloview's **column set** (parsed from `layoutxml`; every spec column must be deployed — an extra deployedcolumn passes by design, so a column REMOVED from the spec, which the additive `reconcileView` leavesin place, is not flagged), plus **relationship** and **command-bar existence** (previously unchecked).+ A relationship is verified by its **identity**, not its name: the answer has to state its schema name, its+ type, both its tables and, for a 1:N, its lookup column — for an N:N, its intersect table and the column each+ table has in it — and all of them have to match (`compareRelationship`, `lib/relationship-metadata.js`; an N:N's+ intersect table has to equal the spec's `intersectEntityName` when the spec names one, and any table the+ answer states will do when it names none). An answer that leaves a part out — a row without its+ lookup, an N:N row without its intersect table, an exact read that answers an empty body — does not pass: the+ check fails and says what the answer lacked. It is not listed `unverified`, which leaves `ok` and the exit+ status as they were; a relationship nobody identified must not read as a pass. (A reader that lists plain+ names, as older test doubles do, stays a name-only reader; the plugin's own reader never does.)Content checks are additive + reader-gated (they only fire when the reader supplies `layoutxml` /`entityRelationships` / `commandBar`), so existence-only callers are unaffected. A view filter'sChoice label is expected as the value the **environment** gives it, which needs the reader's@@ -1667,10 +1725,21 @@ the pipeline and delegates each script's **behavioral spec** to the entries belothe published read carries none of is set aside; a tile, a cell, an attribute, any text, a caption in alanguage it carries, and a FormXML that is not one well-formed XML document are still changes, and twoequal texts are the same dashboard as before. That is the read of a user whose own language is the- base one; live, for a user whose language was the other one, the published read carried both languages,- in another order than the saved read, and one cell's caption in that language differed between the two- layers — so for that user the dashboard stays unverified, as it was: it fails closed, never passed without- proof. **App membership is checked on the published layer:** sitemap tables union `app.tables`+ base one. For a user whose own language is the other one, live, the published read carried both+ languages, that user's own first, and one cell's caption in that language was worded another way than the+ saved read's, on a dashboard nothing had written since its publish — a read is the platform's projection+ for its reader, and no text says which of two captions is the caption. The platform's own token does: the+ published row (`queryRecords` answers its `@odata.etag` beside the FormXML) and the saved read answer the+ same `@odata.etag` until the saved layer is written (live-measured: a write moves the saved read's token+ and not the row's, even a write that puts the content back; a publish moves both to one new token). When+ the two answer the same token and the published read carries more than one language (the base-language+ user's never does), the saved layer IS the published row, and the reads are compared in everything but+ their captions: a tile, a cell, an element, an attribute and any other text still differ. With another+ token, none, or a published read of one language, the texts decide as above. So that user's published+ dashboard is verified, one with a change saved and not published (a new token) is not, and the+ base-language user's result is as it was. It fails closed where the token cannot say: a row that answers+ none, or a dashboard saved after its publish and put back, is unverified until it is published. **App+ membership is checked on the published layer:** sitemap tables union `app.tables`must have type-1 rows; each `app.mainForms` table gets an `app-main-forms` check comparing resolvedactive Main IDs with classified type-60 members. Missing members fail with “re-run the build”,extras fail with the Maker Forms remedy, and unreadable/unclassifiable membership is unverified,@@ -1772,7 +1841,25 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloan ASCII console preview for the in-conversation approval gate, this is durable Markdown for reviewand archival. It is **rendered, never hand-written** — the freehand version drifted from the specand shrank to a counts summary. Also returns `warnings[]` naming design gaps (no jobs captured, a- job with no covering surface, no generative pages) so the orchestrator surfaces them in chat.+ job with no covering surface, no generative pages, a new table no persona and no `roleGrants[]`+ entry grants a privilege on) so the orchestrator surfaces them in chat. Its Security section keeps+ two questions apart — who can open the APP (the roles associated with it) and who can use the+ TABLES the spec introduces (privileges) — and never calls the app administrator-only on the+ strength of a spec with no personas alone: that is a claim about the deployed app. With `--env` it+ reads, read-only, the roles the app has associated with it (`lib/app-roles.js`: the SDK's+ saved-layer app lookup — which finds an app that was saved and never published, so a draft is not+ reported as one that does not exist — then the association rows,+ `appmodules(<id>)/appmoduleroles_association`, through `collectionRows`, the plugin's one reader of+ a paged collection) and lists them. A persona's role counts as associated with the app unless the+ persona opts out (`appAccess: false`): a build removes that association, so the document says so+ rather than listing the role as one the app will have. A `roleGrants[]` entry that gives `roleId`+ is matched to the role of that id, and is certain; an entry that names only a role, and a persona,+ are matched by name only, as "may be", with every role of that name listed — role names repeat+ across business units, so a name alone is never certain. The administrator-only conclusion is+ drawn only from that read — an app the environment has with no role, or one it does not have yet+ that the spec gives none. A read that fails or answers something that is no list of roles (a+ refusal, a 404 for a draft's roles, a row that names no role) is reported in the document and in+ `warnings` as "not checked", never as "no roles"; it never fails the command.- **`scripts/vendor/cds-maker-sdk.cjs`** — the SDK vendored as a self-contained headless bundle(rebuild via `scripts/_vendor-build/`); **`scripts/lib/sdk-http-client.js`** injects an`az`-token HttpClient. No browser, no relay — the SDK reuses the designer's own serializers.@@ -1785,6 +1872,24 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`findExistingColumns`, `relationshipExists`, `artifactIdentityQuery`) rather than a parallelimplementation, so the plan cannot disagree with what the apply then does; it is read-only, and`--no-live-plan` restores the offline, spec-only listing.+- **A relationship is reused only when the environment states its whole identity.** The build skips the create+ of a relationship that is already there — and a dry run marks it `= reuse` — only when the answer states its+ schema name, its type, both its tables and, for a 1:N, its lookup column, for an N:N its intersect table and the+ column each table has in it, and each equals what the spec declares+ (`compareRelationship` in `lib/relationship-metadata.js`, used by `relationshipExists` and the data-model+ phase). A part the answer leaves out — a collection row without its lookup, an N:N row without its intersect+ table, a typed read that answers `{}` — is not "nothing contradicts": the relationship is unproven, and a name+ is the one thing another relationship can share (a 1:N and an N:N between the same tables derive the same one;+ an N:N made elsewhere under the same name and tables can sit on another intersect table). The probe then answers "could not+ tell" (`? unknown` in a dry run), the create is tried, collides on the name, and the build reads the+ relationship itself: it is reused when that read states everything and matches, and when that read is+ incomplete too the build halts — final, since a run again reads the same answer — and leaves the relationship+ as it is. A complete answer for another relationship halts as it always did (`relationship-name-taken`). An N:N's+ intersect table is held to the spec's `intersectEntityName` only when the spec names one (the SDK creates it+ under that name, or under the lower-cased schema name when none is given); a spec that names none is held to+ none, because a download never writes one and a relationship adopted with `existing: true` has the intersect+ table its maker chose — the answer still has to state it. The SDK's own relationship projection+ (`fetchEntityMetadata`) lists an N:N without its intersect table, so it never proves one.- **Bounded parallelism in the read-heavy and publish-heavy paths.** Each item below has tests that countrequests and prove the overlap (`verify-parallel-checks`, `verify-page-code-batch`,`download-parallel-reads`, `teardown-publish-once`, `table-columns-in-create`, and the check-auth tests),@@ -1792,7 +1897,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belooutput is compared with byte for byte. Every fan-out is`mapLimit` (`lib/entity-provision.js`; its `firstInOrder` option makes the thrown error thelowest-numbered task's, deterministically), never an unbounded `Promise.all`, and each request still- retries its own 429s (`lib/sdk-http-client.js`) — so a throttled environment slows the pass down rather+ retries its own 429s (`lib/sdk-http-client.js`, inside the run's throttle budget when it has one) — so a throttled environment slows the pass down ratherthan being hit by a burst.- **Verify** (`lib/verify-spec.js`) runs its checks as ordered tasks on a pool of 4(`verifySpec(spec, read, { concurrency })`). Each task reports into its own buffer and the report is@@ -1865,7 +1970,9 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`lib/sdk-http-client.js`). It never sends it again after another transient status or a lost answer (a change set cancommit behind those), so such a refusal costs one request and then the per-column path's own 429 retries, never aburst; a change set still refused with a 429 once the attempts are spent falls back the same way, with a warning- that says the table was throttled rather than that the request failed. The columns are not put in+ that says the table was throttled rather than that the request failed. A refusal the run's throttle budget made — it had no room for the wait the 429 asked for, and the client handed the answer back and told+ the budget (`lib/throttle-budget.js`) — is not that fallback: the service asked the run to hold back, so the columns are NOT created one by one, no request of a column's own is sent, and the phase stops with+ the budget's halt (`throttle-budget-exhausted`; `createColumnsInOneRequest`'s `stop`, which is the runner's `stopIfRefused`). The columns are not put inthe table's own create request, which Dataverse also accepts (an `Attributes` array beside the primary nameattribute, [Create columns](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-column-definitions-using-web-api#create-columns)):a table create that carries columns is not a request the previous release ever sent, and an environment can treat it@@ -1932,9 +2039,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloa run will not set either).Last, because `updateColumn` starts by reading the column WITH its labels, and a label-bearing metadata read ahead ofa labelled create is what strips non-base languages (measured; see `findExistingColumns`): within one attempt, nothing- labelled in more than one language is created after it (the one thing that is, an alternate key over the name column —- below — carries one label, which a read cannot strip). The build's automatic retry of a transient halt (a 429, a- lock) runs the phase again as a second attempt. The attempt that created the table sets its length in the halt path+ labelled in more than one language is created after it, except one kind of alternate key over the name column (below): the+ key labelled in several languages that cannot fit beside the name column before the step, which is made after it because it+ cannot be made before. (A key with one label, which is also made after it, has nothing for a read to strip.) The build's+ automatic retry of a transient halt (a 429, a lock) runs the phase again as a second attempt. The attempt that created the table sets its length in the halt pathtoo; when that step fails as well (the lock that stopped the phase can still be held), the table is **owed** itslength. `provisionDataModel` records it (`owedLengths`, a Map of `{ table, column, asked, tried, tableId, columnId? }`,which `runSdkBuild` hands to the phase and puts on the halt it throws, the way it carries the publishes an attempt owes@@ -1977,6 +2085,17 @@ the pipeline and delegates each script's **behavioral spec** to the entries belothese requests, wherever in the payment it is made: a 404 from any of them leaves the column as it is, with the samewarning (`(the table the build created changed — kept)`) and the debt dropped. Nothing is resolved by name once the tableis proved, except the one read that asks which table answers to the name.+ **A refusal of the run's throttle budget does not drop what the build owes.** Once the budget has refused to wait for a+ throttled request, the engine's runner starts no more steps of the phase (`makeRunner`; see the throttle budget above) —+ but the length step is not one of them (`settling`): no later run can set the length, since a run that finds the table+ leaves its name column alone, so every table the run owes one is paid in the pass that completes the phase as it is+ after a halt, and the refusal of one table's update does not keep the next table's from being set. A key over the name+ column is a step of the phase, so it is not made in that run: the build stops with `throttle-budget-exhausted`, the table+ has the length it was given, and the next run, which finds the table, makes the key. A step the runner stopped before it+ began is never taken for a length that was set: `alignPrimaryNameLength` answers `notStarted` (the stop as its error,+ nothing sent), the debt stays in `owedLengths` and is not marked `tried`, so the settlement a build that stops for good+ makes pays it, and a key waiting for it is not asked for (`runBestEffort`'s `onFailure` is how the step learns it;+ `throttle-engine-stop.test.js` and `table-columns-in-create.test.js` pin it).When no retry follows, the CLI makes one last try at a length that no attempt got as far as setting(the last one halted before its data-model phase; `settleOwedLengths`, silent unless it fails), as it settles owedpublishes; a process killed outright, or a later run, finds the table and leaves its name column alone. What the retry@@ -2056,12 +2175,16 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloonly: a recommended column is not a Business Required field) and the plan document (`required`, `recommended`). A downloaded spec carries no`required` at all (`download-model-app.js` reads no `RequiredLevel`), so it passes whatever the live columns hold.Pinned by `column-required-gate.test.js`.- - **Alternate keys over the name column.** The platform validates a key when it is created, and a key may hold at- most 900 bytes — 2 for each character of a text column- ([Dataverse alternate keys](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys)) —- so a key over a name column an environment made 850 characters long is refused. A key that holds a table's primary+ - **Alternate keys over the name column.** The platform validates a key when it is created, and the size it holds is bounded: the+ platform's own answer to a key that is too large names the limit (HTTP 400, code `0x80060895`, "Index size exceeded the size limit of+ 1700 bytes. The key is too large. Try removing some columns or making the strings in string columns shorter."), 2 bytes for each+ character of a text column ([Dataverse alternate keys](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys)+ documents 900; 1,700 is what the environment this was measured on enforced, so the build uses the number only to know that a key+ cannot fit — `KEY_BYTES_LIMIT`, `lib/app-spec.js` — and the platform does the refusing). The 850 characters an environment may make of a+ new name column are 1,700 bytes by themselves: measured, a key over that column **alone** is accepted, and one that holds **any other+ column** beside it is refused (a column of one character, of a hundred). A key that holds a table's primaryname column, when the spec gives that column a length and the key's label **goes out in one language**- (`keyWaitsForNameLength`, `lib/app-spec.js`), is therefore made after the length steps and not with its+ (`keyWaitsForNameLength`, `lib/app-spec.js`), is made after the length steps and not with itstable, for a table whose length is still to be set: one this attempt created, or one an earlier attempt left owed.What counts is what is sent — not the shape of the value, and not the language the build is authored in: the SDK writesa string as one `LocalizedLabels` entry in the build's language, and a language map as one entry per language it names,@@ -2071,12 +2194,16 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloknow the build's language, and the apply cannot disagree about it. Such a key is made only when the length stepcame out right (`ok`, or `already N`). When it did not, the key is not sent: its own step fails with`BuildHalt` code `alt-key-name-length-not-set` (`recoverable`), whose text names the table, the length and why the- step failed — not the platform's refusal of the key, which says nothing of the length — and which is raised around the+ step failed — not the platform's refusal of the key, which says nothing of the length — and what to do, in the proven / inconclusive+ words below (`keyRoomAtAskedLength`, `lib/entity-provision.js`): a key proven too large at the length asked is created by no run as the+ spec has it, and of any other key setting the length MAY make room, which the stop does not promise. The warning of the length step that+ failed names each key that waits for it in the same words (`alignPrimaryNameLength`), instead of claiming the key cannot be created+ while the column is that long. The halt is raised around thestep's failure with the policy that failure gives (`retry: retryPolicyFor(…)`, `lib/retry-policy.js`) and the step'sHTTP status, so a 429, a lock or a 503 is retried by the build and a refusal, or a failure marked `transient: false`, isnot; the halt's own words (the key's name) never decide — a halt's code names it and is no type, where an error's own`code` would read as a refusal of its kind.- The retry then finds the length owed, sets it, and makes the key. A key made after the read that carries labels is+ The retry then finds the length owed, sets it, and asks for the key. A key made after the read that carries labels issafe because its label is one label, which a read has nothing to strip. That was measured for a create straight afterthe read and for a label in the base language; it has not been measured separately for a label in another language(a build authored in one, or a map that names one), where the key is the same request as every other label of such@@ -2085,17 +2212,47 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloholds, `keyWaitsForNameLength` does not), as every multi-language create in this file does: it cannot follow the readthat sets the length without risking the otherlanguages, and the length cannot be set without that read (the SDK's update needs the column's whole definition,- which only that read provides). So its first build can still stop where the platform refuses the key for the length- of its column, and then `alternateKeyAheadOfLength` warns — only when the key fails — naming the key, the languages its- label goes out in, why it was made first, and what to do: run the build again (the length is set as the build stops, so- the run that follows finds the table with it and makes the key), or label the key in one language. Where the environment- keeps the length asked, the key is made and nothing is said. Every other key —+ which only that read provides). **Except** where the environment made the name column too long for the key to fit beside the+ others: the platform refuses such a key ahead of the step, and the first build used to stop there for the run that followed to+ make it. `keyHasRoomOnlyAfterLength` (`lib/app-spec.js`) says from the spec when the length can decide that — the key holds the name+ column, cannot fit while that column is 850 characters, and may fit at the length the spec asks; the size is a floor+ (`keyBytesAtLeast`: each column counts as the build creates it — a single line of text 2 bytes a character, a `Text` column at its+ `maxLength` or the SDK's default of 100, and an `AutoNumber` column or a column that gives no `type` at 100 whatever `maxLength` it+ carries, because the build sends a `maxLength` only for `Text` and `Memo` — `maxLengthSent`, the one rule `columnOptions` follows too;+ any other column counts one byte, so that what the floor shows is certain: what the platform counts for the other types a key can hold+ was not measured, and one byte changes nothing for a key that fits at the length asked) — and only for such a key does the build read the column, with one typed+ `…/StringAttributeMetadata?$select=MaxLength` GET (no labels: the kind of read the build keeps ahead of its labelled creates), before it asks for+ the key (`keyMustWaitForShorterNameColumn`, `lib/entity-provision.js`). Where the column reads too long for the key, the key waits for the+ length step like a key labelled in one language and is made after it, with both labels; where the environment kept the length asked, or the read+ fails, the key is made ahead of the step, where it always was. A key over the name column alone fits even at 850 characters, and one too large at+ the length the spec asks would be refused after the step as well, so neither is read for. **Why only then, and not every key over the name+ column:** the loss that keeps such a key ahead of the step did not reproduce in the live measurement (0 of 18 creates made right after a read+ that carries labels lost a language), while a key made after the length step kept both languages (9 of 9, and 2 of 2 in a new process) — so+ "after the step" cannot be shown safe where the loss does exist, and a key that fits keeps the place that never risked it; the one key that+ cannot be made there is the one that moves. A key that was not known to be too large and that the platform then refuses for its size (an+ environment whose limit is smaller, a read that failed, or a column the floor counts at one byte that the platform counts at more) is made where+ it always was, and `alternateKeyAheadOfLength` warns — only when the key fails — naming the key, the languages its label goes out in, why it was+ made first, and what to do, which depends on what the floor proves at the length the spec asks. **Proven too large** (the floor is over the+ limit): such a key is made there too (waiting makes no room for it), and the warning says so — the bytes its columns take at that length, that+ running the build again does not create it, and to take a column out of the key or make its text columns shorter. **Inconclusive** (the floor+ is within the limit — it counts a column that is not text, or one the spec does not describe, at one byte, so a name column of 849 characters+ beside an Integer column counts 1,699 bytes and is refused all the same): the warning promises nothing — running the build again may create the+ key (the length is set as the build stops) if the asked length leaves room for it; it states the floor, and says to compare the platform's error+ with the sizes of the key's columns if the next run is refused the same way. Neither offers a label in one language as a way out: that changes+ where a key is made, not its size. The same two wordings (`keyRoomAtAskedLength`) are what the stop for a key that waited for a length step+ that failed, and that step's warning, say of the key (above). Where the environment+ keeps the length asked and the key is made, nothing is said. Every other key —over another column, over the name column of a table that already existed or was found after its create (neverwritten to), or in a spec that gives no length — is made with its table, as it always was; a spec that keys a namecolumn without a `primaryAttribute.maxLength` leaves the column as the environment made it, so the reference tellsan author to give one. `planFor` and the provision-entities plan list a waiting key after the length steps, where a- table the build creates has it; the count is unchanged. `table-columns-in-create.test.js` pins the order (against a- stub that refuses a key over 900 bytes), the failure, the language rule, the warning, and the retry.+ table the build creates has it, and a key labelled in several languages with its table — whether the environment makes the build move+ it is known only to the build, and the count is the same either way. `table-columns-in-create.test.js` pins the order (against a+ stub that answers a key that is too large as the platform does: at 1,700 bytes, and at 900 for an environment that enforces the documented+ limit), the failure, the language rule, the warning and the stop for a key whose length step failed (proven and inconclusive, and that+ the run after agrees with each), the read and the retry,+ and that the floor counts each column as the real bundle creates it, for every type the build creates; `app-spec-key-size.test.js` pins the+ size rule.The end-to-end flow (Phase 0 working dir → Phase 1 author **in the main loop** per`references/authoring-flow.md` → Phase 2 narrated SDK build → Phase 3 verify & iterate; **edit** an@@ -2146,7 +2303,7 @@ references/ ← Shared reference docsapp-spec-schema.md ← The App Spec contract (always-present fields) — /app-builderapp-spec-schema-advanced.md ← Conditional App Spec fields (business rules, BPFs, commands, web resources, global choices, dashboards, roleGrants)authoring-flow.md ← /app-builder Phase 1 authoring playbook, run in the main loop (not a subagent)- agent-interaction-contract.md ← Agents are headless: no AskUserQuestion / plan mode inside a Task subagent+ agent-interaction-contract.md ← Agents are headless: no AskUserQuestion / plan mode inside a Task subagent; a declared tool is not always a delivered one (task tracking is optional)data-caching.md ← Rule 15 on-mount fetch: de-dupe + cache (loaded conditionally)localization.md ← Multi-language + RTL pattern (loaded conditionally)supported-dependencies.md ← Versioned package list for generated pages@@ -2170,7 +2327,7 @@ scripts/apps.js ← the replacement for `pac model list` and `pac model create` that /genpage and /app-builder run (`pac-replaced-docs.test.js` pins that their text names this script, not the `pac` commands): the environment's model-driven apps and a new app that opens on generative pages, through the bundled SDK. `list` prints each app's id, name, unique name, description and two facts, apart: `published` (it has a row in the published layer: users can open it) and `unpublishedChanges` (it has a saved row that is not published) — drafts included; `pac`'s "(Saved - Not Published)" is neither of them (see the spec section) and never part of the name. `create --name --solution --page-id <guid> [--page-id …] [--unique-name] [--description] [--publish]` makes the app with one area "Main", one group "Pages" and a sub-area per page, titled with the page's stored name; the app and its sitemap join the solution (a system solution such as `Default` holds them already: `systemSolution: true`); it is published only with `--publish`. The default public view of each table the pages read (the tables come from each page's own configuration, the views from the page backend: the definition `placeInApp` pins with) joins the app's components in the create itself — `components.views` of the app the SDK creates, written by the same AddAppComponents that adds the sitemap — as `pac model genpage upload --app-id` pinned them; the output says what was pinned (`dataSources`, `pinnedViews`), a table with no default public view or a page held as raw files is named in `warnings`, and a page that cannot be read refuses the create before the first write. Every check — no page id, a page that does not exist, a solution that does not exist or is managed, a taken unique name, an unreadable base language — is a refusal printed as `{ ok: false, code, error, written: false }` before the first write; a failure after the push began reads the platform back and prints what is actually left of this create (its rows are recognised by their ids, and a row that holds the unique name under another id is named apart)list-tables.js ← the replacement for `pac model list-tables` (the skills' and agents' text runs this script: `pac-replaced-docs.test.js`): the environment's tables — the SDK's `findTables(term)` for each comma-separated `--search` term, a few reads at a time, joined without repeats; `--exact` keeps the tables whose logical name IS a term and names the terms no table has (`missing`), from one read of every table; `--type custom|standard|all` is `pac`'s own filter, `custom` through the SDK's `customOnly` option. One pure-ASCII JSON line of `{ logicalName, displayName, schemaName, isCustom }` rows. An answer that is no list of tables — a 2xx with no `value` list: a sign-in page, `{}`, `null` — fails `TABLES_UNREADABLE` (exit 1) instead of reading as "no tables, every searched one missing" (`lib/collection-answers.js`)add-page-to-solution.js ← Adds GenPages and optional connection references to a solution- solution-settings.js ← Deployment settings: `template` writes the settings file of a solution or a package (pac's own format), `import` imports a package and applies the settings in the same import — the SDK first, `pac solution create-settings` / `import --settings-file` only where it refuses (pac is given a private copy of the settings the run read, owner-only on every platform and removed however the process ends, never the file's path); ExportSolution, StageSolution and ImportSolution are each sent exactly once — but for an ImportSolution the platform refused to start because another operation held its customization lock (HTTP 429 with one of the customization-lock error codes whose documented text is "Cannot start …"), which is sent again under a new job id once `importjobs(<id>)` shows the refused send's job does not exist (at most five sends and five minutes in all, a `Retry-After` waited whole or the retry ended; `importAttempts` / `importRefusals` in the output) — every text it prints has the settings file's values taken out, and everything it prints or writes the access tokens the run sent (an HTTP 200 can be a failed staging whose message quotes what it was given), and a failed import names its job and the job log's reason; one pure-ASCII JSON line with `source`+ solution-settings.js ← Deployment settings: `template` writes the settings file of a solution or a package (pac's own format), `import` imports a package and applies the settings in the same import — the SDK first, `pac solution create-settings` / `import --settings-file` only where it refuses (pac is given a private copy of the settings the run read, owner-only on every platform and removed however the process ends, never the file's path); ExportSolution, StageSolution and ImportSolution are each sent exactly once — but for an ImportSolution the platform refused to start because another operation held its customization lock (HTTP 429 with one of the customization-lock error codes whose documented text is "Cannot start …", or with `0x80071151` and "Cannot start …" words), which is sent again under a new job id once the refused send's job proves that nothing of the package was applied — `importjobs(<id>)` does not exist (404) or, for `0x80071151`, read once at once, is a finished job whose log says the import failed with that error before it processed the solution or any component (`lib/import-job-proof.js`); a job that proves nothing ends the retry with a sentence that says why and what to do, and so does a fifth `0x80071151` refusal, whose job is not read (at most five sends and five minutes in all — asked again after every wait — a `Retry-After` waited whole or the retry ended; `importAttempts` / `importRefusals` in the output) — every text it prints has the settings file's values taken out, and everything it prints or writes the access tokens the run sent (an HTTP 200 can be a failed staging whose message quotes what it was given), and a failed import names its job and the job log's reason; one pure-ASCII JSON line with `source`provision-entities.js ← CLI wrapper for entity provisioning (solution + data-model + sample-data; --language-code)provision-solution.js ← Creates a Dataverse solution via the SDKwrite-page-plan.js ← app-builder Phase 1.5: projects an App Spec into the genpage-plan.md read by page-builder workers@@ -2178,10 +2335,10 @@ scripts/build-model-app.js ← app-builder: narrated, idempotent SDK build (dry-run default; --stage data|ui|app|publish; --changed-only; --language-code)download-model-app.js ← app-builder: pull a deployed app into an editable spec (edit flow; takes the build's --language-code: the language the navigation titles are read in, when the spec on disk pins none and the base language cannot be read)teardown-model-app.js ← app-builder: classifier-safe reverse-of-build teardown- verify-model-app.js ← app-builder: reconcile the spec against the deployed app (takes the build's --language-code: the language its form labels were written in)+ verify-model-app.js ← app-builder: reconcile the spec against the deployed app (takes the build's --language-code: the language its form labels were written in; its result JSON is pure ASCII and lists every `WARNING:` line it printed in an optional `warnings` array)preview-form.js ← app-builder: ASCII form wireframe for authoring reviewpreview-app.js ← app-builder: ASCII whole-app design preview (data model + sitemap + forms + page-intents + design)- write-app-spec-doc.js ← app-builder: renders the readable model-app-plan.md design doc from app-spec.json+ write-app-spec-doc.js ← app-builder: renders the readable model-app-plan.md design doc from app-spec.json (`--env` also reads, read-only, the roles the app has associated with it; a read that fails is reported in the document, never fatal)ai-preflight.js ← app-builder: preflight AI feature availability (admin-gate report)run-tests.js ← one-command plugin + SDK regression runnersmoke-eval.js ← scripted live smoke eval (build → assert → teardown)@@ -2195,11 +2352,11 @@ scripts/check-griffel-styles.js ← /genpage and /app-builder: a page's `makeStyles` calls hold none of the ten shorthands Griffel's runtime drops (lib/griffel-styles.js; see "Griffel shorthands" below)capture-fixture.js ← Copies /genpage working dir into an eval fixture and runs both runnerslib/- entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column; the primary name column's length is always sent (100 unless the spec gives one), its required level is asked in the create when the spec states one (and said applied only when the SDK confirms it) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; and `mapLimit`, the bounded fan-out every parallel path reuses+ entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column (unless the run's throttle budget refused to wait for the change set: the phase then stops, `stop`); the primary name column's length is always sent (100 unless the spec gives one), its required level is asked in the create when the spec states one (and said applied only when the SDK confirms it) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; `makeRunner`, whose runner stops the phase at the next step once the run's throttle budget has refused a wait (`stopIfRefused`: `run` and each item of its `mapLimit`; a step that pays the name column length a table the run created is owed is let through); and `mapLimit`, the bounded fan-out every parallel path reusesretry-policy.js ← when the build runs a failed phase again, decided from what the SERVICE said and never from what the maker named: `RETRY` (`NEVER` — a refusal of the spec, an identity or ownership conflict, an approval, a prerequisite, a file on the maker's machine; `SERVICE` — what the failure it wraps says), `judgeFailure(error, { declares })` (an explicit `transient: false` anywhere along the causes wins; then the HTTP status 429, 502, 503, 504; then a condition the service names by the `error.code` of its answer — `TRANSIENT_SERVICE_CODES`, a SQL deadlock victim (the generic SQL error code `0x80044150` AND the platform's `Sql Number: 1205` — the last SQL number the answer gives — in the service's own answer, `isDeadlockVictimAnswer`), and the lag of a column the spec creates (`declares`) — on any status; then a timeout or reset of the transport (by Node's own code when the error carries one, by its words only when it has none); then **any other HTTP status is final** whatever the answer's words say; then the SDK's or plugin's own type — a refusal, whatever it quotes (bar the SDK's wrapper of a failed publish, read by the status of the answer it embeds); then, only for a failure that carries no status at all, the service's own words, never a halt's message), `throttleAskOf` (what a throttled failure asks of the next send: `retryAfterMs` and `retryNotBefore`), `retryPolicyFor` / `retryFrom` (the policy a halt is raised with), `refusal` / `serviceFailure` (the errors the engine itself makes; `serviceFailure`'s `answered` records the OData error of an answer the engine read with a request of its own — its `code` and `message`, nothing else — and the rule reads that code as it reads the SDK's) and `withCause` (the failure a by-value result carries); `BuildHalt` takes `retry`, `retryText` and `statusCode`; build-model-app.js `isTransientHalt` is its one reader, and `tests/halt-retry-policy.test.js` holds every halt in the sources to a row of its table- throttle-budget.js ← the budget a run allows itself for the waiting its OWN retry layers add when a service throttles — five minutes, shared by the page backend's waits between the sends of a page write (a `$batch` the HTTP client never re-sends) and the build's own waits before it runs a phase again (the upload script's write makes one of its own) (`makeThrottleBudget({ totalMs, warn })`: `fits`, `spend`, `announce` for a wait longer than five seconds, on the `warn` seam the build wires to stderr; `waitDoesNotFit`, the sentence of the `throttle-budget-exhausted` halt: what the service asked, how much is spent, that a later run of the same command continues); it only counts, each layer waits with its own seam. It is NOT a bound on all the waiting of a run: the HTTP client's own re-sends of a throttled read, publish, delete or column create keep their own schedule and are not drawn from it+ throttle-budget.js ← the budget a run allows itself for the waiting it does when a service throttles — five minutes, shared by the HTTP client's waits before it sends a throttled read, publish, delete or column create again (`deps.throttle` of `lib/sdk-http-client.js`), the page backend's waits between the sends of a page write (a `$batch` the HTTP client never re-sends) and the build's own waits before it runs a phase again (the upload script makes one for its run) (`makeThrottleBudget({ totalMs, warn })`: `fits(ms, at)` and `spend(ms, at)`, which answers what the wait added — a wait the client PLACES on the clock (`at`) adds only what runs past the waits placed before it, because requests sent together are throttled together and wake together, while the backend's and the build's, which wait one at a time, place nothing and add whole; `announce` for a wait longer than five seconds, on the `warn` seam the build wires to stderr; `decline` / `declined`, where the client says that a wait did not fit — in the words of `refusedWait`: what the service asked and that the request was not sent again, with no advice on what to run, because a refused request can follow a write that committed — and the build's retry loop and the engine's runner read it (the loop to stop with the halt, the runner so that no step starts after it), since the answer the client hands back carries nothing of what the service asked; `note`; `waitDoesNotFit`, the sentence of the `throttle-budget-exhausted` halt: what the service asked, how much is spent, that a later run of the same command continues); it only counts, each layer waits with its own seam. What is not drawn from it is a wait that is not for a throttle — a 5xx, a reset connection, a deadlock victim's re-send — and the waits of a client given no budgetprovision-input.js ← Input validation for entity provisioning (the entry gate of `/genpage` and `/app-builder`; it applies `app-spec.js`'s own `primaryNameLengthProblem`, `autoNumberFormatProblem` and `requiredValueProblem`, so a name-column length, an AutoNumber column with no format and a `required` that is not `true`, `false` or `"recommended"` are refused here exactly as in `validateAppSpec`)- dataverse-auth.js ← Shared auth + HTTP helpers (`az account get-access-token`, memoized per process and replaced on a 401 — a synchronous `az` call, which a caller running other probes beside the request opts out of with `refreshOn401: false`; responses decoded as UTF-8 once; a request that fails is reported as `{ error, code? }` — the message and, when Node gave one, Node's own error code (the failures this module words itself have none), which `lib/sdk-http-client.js` reads to decide whether the request is worth sending again; an answer that is not a success, and a transport failure's text, come back from `dataverseRequest` with every token the call sent taken out — the one `scrub` of `sdk-http-client.js`, a success untouched; an environment URL is used only as a Dataverse https origin, `dataverseOrigin`; a request path must stay under `/api/data/v9.2/` as both the client and the server resolve it, `webApiUrl`), the Azure CLI token for the Power Apps service (`getPowerAppsToken`: the same read for another resource, memoized apart from the Dataverse token and asked for only by the Power Apps service client and the connectivity preflight), plus the CLI arg contract (parseArgs/validateFlags, and `readLanguageCodeFlag` — the `--language-code` / `--languageCode` flag as an LCID, which `verify-model-app.js` reads exactly as the build does) and the result printer (`emitResult`, whose `{ ascii: true }` option writes stdout JSON as pure ASCII for a script an agent reads off a console)+ dataverse-auth.js ← Shared auth + HTTP helpers (`az account get-access-token`, memoized per process and replaced on a 401 — a synchronous `az` call, which a caller running other probes beside the request opts out of with `refreshOn401: false`; responses decoded as UTF-8 once; a request that fails is reported as `{ error, code? }` — the message and, when Node gave one, Node's own error code (the failures this module words itself have none), which `lib/sdk-http-client.js` reads to decide whether the request is worth sending again; an answer that is not a success, and a transport failure's text, come back from `dataverseRequest` with every token the call sent taken out — the one `scrub` of `sdk-http-client.js`, a success untouched; every token read from the Azure CLI, and every one `dataverseRequest` sends, is noted in `lib/output-redaction.js`, which keeps it out of everything the process writes, and `emitResult` cleans its own text the same way; an environment URL is used only as a Dataverse https origin, `dataverseOrigin`; a request path must stay under `/api/data/v9.2/` as both the client and the server resolve it, `webApiUrl`), the Azure CLI token for the Power Apps service (`getPowerAppsToken`: the same read for another resource, memoized apart from the Dataverse token and asked for only by the Power Apps service client and the connectivity preflight), plus the CLI arg contract (parseArgs/validateFlags, and `readLanguageCodeFlag` — the `--language-code` / `--languageCode` flag as an LCID, which `verify-model-app.js` reads exactly as the build does) and the result printer (`emitResult`, whose `{ ascii: true }` option writes stdout JSON as pure ASCII for a script an agent reads off a console)process-runner.js ← how every script starts az/pac/npm/npx/git: the executable is resolved to an absolute path on PATH, never the project folder, and started without a shell (a Windows batch shim runs through cmd.exe with its arguments checked — except a launcher that only forwards to the native program beside it, the Windows MSI's two-line `pac.cmd` (`@echo off` / `"%~dp0pac.launcher.exe" %*`): it is recognised by its exact lines — `@echo off` on a line of its own, then the forwarding line, as `cmd` reads lines, so a one-line `@echo off "%~dp0x.exe" %*`, which is an `echo`, is not one — and the program beside it (`forwardedProgram`) and that program is started directly, so a `%` or a double quote reaches it unchanged; every other batch file keeps the checked route and its refusal of them); `killProcessTree` ends a stalled child AND everything it started (`taskkill /T /F` on Windows, where `pac.cmd` is cmd.exe → pac.exe, looked up with the System32 folder first on PATH so a PATH without it cannot leave the tree running, and with its window hidden; SIGKILL to the descendants `ps` lists elsewhere, each only once `ps -o lstart= -p` shows its pid still has the start time the listing saw — a descendant that exited meanwhile can have its pid given to an unrelated process; best effort, since two processes can share a one-second start time and the moment between that read and the signal is not covered), through the same audited calls; a child that has already exited is only asked to die, never ended by its pid, which may be another process's by then; synchronous, and it never throws. `spawnResultTree` is `spawnResultSync`'s asynchronous twin (same result shape, never rejects) for a call that may have to be ended: one that outlasts its `timeout`, or writes past `maxBuffer`, has its whole tree ended through `killProcessTree` before the call settles (`ETIMEDOUT`, `ENOBUFS`), after a short wait for the pipes of what was ended; the error says whether they closed (`containment`: `confirmed`, or `unconfirmed` when a process that outlived the ended tree still holds them, with the `pid` the call was started as)cli-failure.js ← how a CLI child failed (timeout / missing / failed), the Azure CLI budget (60 s, `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`), so a slow `az` is never reported as missing or signed out; `commandArg` writes an argument of a command a message tells you (or the agent) to paste so that, run from PowerShell (Windows PowerShell 5.1 or PowerShell 7) or a POSIX shell, the program gets it unchanged as one argument — bare when it is plain, single-quoted otherwise (a path from an untrusted checkout can hold `;`, `$(…)` or backticks) — or not at all when no spelling does that in every one of those shells: a quote or a line break, and the values Windows PowerShell changes on their way to a native program (a `"`, white space with a final `\`, the empty value) or both PowerShells read as the stop-parsing token (`--%`), all measured. `commandArgOrPlaceholder` then writes a placeholder and names the value outside the commandnearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators)@@ -2232,9 +2389,10 @@ scripts/page-publish-records.js ← `page-published.<hash>.json`, one file per app and environment in the build workspace: per page, the hash of the content (`contentFingerprint`) it was last PUBLISHED with and the version number of every one of its file rows and of its own row (the plain reads `genpage.fileVersions` and `genpage.projectVersions`), written only after a publish seen to take effect, and with versions only when they were read on both sides of a read-back of the page's published copy (`genpage.publishedDiffers`), were the same set, and the copy held the content and the compiled output the draft held when it was published (`runtimeSha256`). The build hands the hash back to `genpage.update` as `publishedFingerprint` only for a page whose rows read now are exactly the recorded set at the recorded versions (`sameFileVersions`), so an unchanged page is not published again and a page published, renamed or saved from elsewhere is; a cache, never an authority — anything missing, damaged, for other content, without versions or with a moved version reads as "not known to be published" and costs one publish, and the schema (3) is the proof's version: a record of an earlier schema is read for its hashes and skips nothing; it grants and blocks nothing (`readPublishedPages` never throws, `writePublishedPages` failing is one warning)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; 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; `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, 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). 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- app-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 the workspace copy's header whenever its own comparison read of it cannot be made (503, 403, a thrown error, an empty 200). 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 `sdk-build.js`'s warnings share+ 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). 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+ output-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; text only, bytes pass), 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). `redactOutput(text)` is what the file writers call (`safe-fs.js` `writeFileSafe` and `appendFileSafe`, `apply-snapshot-store.js` `writeFileAtomic`) 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`) 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. Not read: other encodings of a token (percent-encoding, base64, entities), a token another process obtained, bytes, a token written in two separate calls to `write`, and the end of a part a formatter cut short. `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` makes+ app-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 itthrowaway-sdk.js ← `withThrowawaySdk({ env, prefix, httpClient? }, run)`: the bundled SDK, made through `maker-sdk.js`, over a throwaway workspace folder (made by `temp-workspace.js`) that is removed whichever way the run ends (a constructor, a storage or a module that throws included); `run(make)` gets a `make(extra)` for more instances over the same folder and the one client (`make({ languageCode })` is a writer). The one copy of what `apps.js`, `list-tables.js` and `list-languages.js` each wrote outcollection-answers.js ← `requireCollectionAnswers(client, { reads, unreadable })`: the HttpClient the SDK is given, with one addition — a 2xx answer to a read `reads(url)` selects must be a collection (`{ value: [...] }`), or the read throws what `unreadable` says; `unreadableAnswer(error)` finds that error, itself or under the SDK's `ConnectionError`. `guardTableLists(client, makeError)` is its policy for the one read of the environment's table list (`/EntityDefinitions?…`, which only `findTables()` makes), and `maker-sdk.js` applies it to every SDK a script makes: the SDK's `findTables()` is `body.value ?? []`, and the bundle is not edited@@ -2244,6 +2402,7 @@ scripts/power-apps-service-client.js ← the HttpClient for the SDK's connection and connector reads: GET only, https only, a host allowlist that is exactly the hosts the SDK's connectivity code calls, redirects never followed, the Azure CLI token for the Power Apps service read only for a request that passed and never in a message, a body, a header or a key the service answers with (it is scrubbed, in whole and by part)sdk-first.js ← the rule `list-connections.js`, `connector.js` and `solution-settings.js` share: read through the SDK, and through `pac` for the SDK's typed refusals (`sdkFirst`, `CONNECTIVITY_REFUSALS`) — an error counts only when it IS the bundle's `SdkError` (an HTTP body that carries a refusal's code does not); any other failure is thrown with the SDK's own code. An environment outside the Public cloud is judged from its host first (`connectivityCloudOf`, pinned to the bundle by a table of hosts) and answered by `pac` at once, with the code the SDK would give. What the SDK could not clean up before it refused (`readCleanupWarnings`: a staged copy of the package it could not delete, with its upload id) is carried across the fallback — as `warnings` on the answer, or attached to the error `pac` throws when it fails — so `solution-settings.js` shows it for `template` and `import` alike (an import's, sanitized once)pac-fallback.js ← runs a `pac` fallback command through `process-runner.js` (`spawnResultTree`) within a fixed time limit (`PAC_READ_TIMEOUT_MS`, 3 minutes; `PAC_IMPORT_TIMEOUT_MS`, 60) — a call that runs out has its whole process tree ended before it is reported, and the message says what the runner confirmed — "`pac` and every process that held its output were stopped" — and, when the pipes did not close, that a process `pac` started may still be running — reads the JSON `pac` prints after its header, and keeps pac's sign-in banner and version lines out of every failure text (`pacErrorText`)+ import-job-proof.js ← what the import JOB of an import the platform refused to start proves about whether it applied anything, for `solution-settings.js`' resend of an import refused with `0x80071151` ("Cannot start …"): `proveRefusedImport({ status, body })` — a 404 is proof (the job never existed), a 200 is proof only through `refusedBeforeAnyComponent(row)`: `completedon` set, `data` read as ONE XML document by `strict-xml.js` (a pattern would miss a `processed="true"` after a `>` in a value) with the root `importexportxml` saying `succeeded="failure"` and `errorcode="-2147020463"` exactly, at least one `solutionManifest` and every one `processed="false"`, and no other element but `upgradeHandler` / `validateHandler` marked anything but `"false"`; anything else is `{ proven: false, why, reason }` with the reason in fixed words and numbers, never a text the platform wrote. Never throws; a log of more than 8 MiB is not read. `tests/import-job-proof.test.js` holds it to twins of the 347 captured job-row states (`tests/helpers/import-job-logs.js`) — it accepts exactly the 8 final rows of refused imports — and to each clauseprivate-folder.js ← a folder, and a file in it, that only the current user can use — the copy of a settings file that `pac solution import` is given: POSIX modes 0700 and 0600, set and read back; Windows an access list with the current user's SID as its ONE entry (`icacls /reset`, `/inheritance:r`, `/grant:r *<SID>:(OI)(CI)F`, read back as SDDL through `icacls /save`, the file's too before a byte is written; the SDDL aliases of the system accounts are compared as the SIDs they stand for, and `LA`/`LG` — the machine's own Administrator and Guest — only when the machine itself writes the user's SID that way, `spellingOf`), `whoami` and `icacls` looked up in the Windows folder's System32 alone through `process-runner.js`; whatever cannot be set or read back is an error with a `reason` (a tool, a step, a number — never a path or a value) and nothing is writtenexit-cleanup.js ← a synchronous cleanup that runs if the process ends while a run's work is going — `process.exit`, an uncaught error, SIGINT, SIGTERM, SIGHUP, SIGBREAK — after which the process ends as it would have: BY the signal on POSIX (raised again once our listeners are off), with STATUS_CONTROL_C_EXIT (0xC000013A, 3221225786) on Windows, where a Ctrl+C is a console event and `process.kill` would end it with the status 1 of a failure; a program that has a handler of its own for the signal — one-shot and self-removing ones included, however they were put on the list — keeps the decision (ours is first in line, so that it sees them all, and stays first: a handler the program PREPENDS later is put behind it again before the call returns, `keepFirst`, which never puts back a cleanup that was released while it was being moved); a KILLED process runs nothing, which is its stated limittypescript-compiler.js ← loads the vendored TypeScript 5.8.3 compiler (vendor/typescript/) for the SDK's page compile: lazily, once, only after its bytes match PROVENANCE.json@@ -2258,23 +2417,27 @@ scripts/odata.js ← OData literal escaping helpersgenpage-sdk.js ← the one generative-page backend, over the bundled SDK (`makeGenpageSdk(env, deps)`; it replaced the `pac model genpage` wrapper): `enumerateEnv` (every page of the environment, drafts included, with the name its own row holds — `unescapePacName` reads back the `\"` an earlier release's pac stored), `enumeratePages(appId)` (an app's navigation, saved or published layer), `read(id)` (the page as the SDK projects it, from the server), `create` (the id is minted on the client — or taken from a caller resuming a create, which passes what it sent before (`sentBefore`) and hears the new send through `beforeSend(id, { name, sourceSha256 })` before anything is sent — one atomic change set, published and proven; an unknown outcome is settled by reading the id, and sent once more under the same id; a page found under a resumed id is recognised by the name and source a create sent (`holdsWhatWasSent`), and what it still holds of an earlier create is converged by the update path) and `update` (writes only what differs, records the new turn under one identity, publishes — except a page that already holds the content and is given the `publishedFingerprint` of that content as published, which is left as it is (`publish.kind: 'skipped'`); every result of `create` and `update` carries the `fingerprint` of the content, for a caller that keeps one, and — for a caller that asks (`runtimeEvidence: true`) and a page it publishes — the `runtimeSha256` of the compiled output the draft held just before the publish; a publish that fails is returned with the failure itself as a non-enumerable `cause`; an unknown outcome is read, and sent once more only if nothing landed), `placeInApp(appId, { pages, dataSources, finish, finishIfUnpublished, beforeAppWrite })` (an app edit: the page becomes a sub-area of its navigation, and the default public view of each table the page reads joins the app's components — those views and nothing else of the app's components, since the push is limited to what the edit owns (`app-component-scope.js`); `finish` is a caller completing an earlier placement: it publishes the app even when nothing is left to write, and proves the page in the PUBLISHED navigation; `finishIfUnpublished` is the same for a caller with no record of an earlier run — it asks the app: a page the saved navigation already names is left alone when the published navigation shows it, and the app is published, and the page proved, when it does not; `beforeAppWrite` is an async function awaited once right before the call first writes the app — its push, or its publish when there is nothing to push — and never called for a placement that writes and publishes nothing: the build hands it the request that publishes the tables whose forms the app's publish ships, since only the placement knows when it is about to write and what it sends, so it is called with `{ pushes, entityTables, mainFormsByTable }` — whether the app is pushed at all, the tables whose Main forms the push adds (none for an SDK this backend made: its transport limits the push to the views it pins; for a lent SDK, whose push is not limited, the tables of the Entity entries of the navigation the push sends, the server's: `entityTablesOfSiteMap`), and the Main-form list the pushed app carries (a fetched app carries none); the edits are only in the throwaway workspace copy by then, so a hook that throws leaves the app as it was and the call throws what the hook threw), `removeFromApp(appId, pageId, { allowEmpty })` (takes every GenPage entry that names the page out of the saved navigation, whichever area and group; the page, its views and every other entry stay, and no component is added to the app; the app is published and the page proved gone from the PUBLISHED navigation, and a removal that was saved and never published is finished by running it again; a navigation left with no entry at all is refused (`GENPAGE_NAVIGATION_WOULD_BE_EMPTY`) unless `allowEmpty` — the platform accepts one on an app that exists, so this is a judgement, not a rule of the platform), `describe(pageId)` (a page's name, `dataSources` — `null`, not "none", for a page the SDK holds as raw files, which `read` refuses — and the size of its folder and conversation), `delete(pageId)` (the SDK's delete of the project row, its files and then its conversation messages, after the page is read and every app's navigation, published AND saved, is scanned for it — `GENPAGE_IN_APP` names the apps, `GENPAGE_APPS_UNREADABLE` when an app that could hold it cannot be read; what a failed delete did is judged by reading the page again, and "deleted" is only reported once it is read back as gone), `runtimeTypes(dataSources, { detail })` (the SDK's RuntimeTypes generator), `defaultViews(tables)` and `baseLanguage()`, `fileVersions(pageIds)` (the versionnumber of every file row of each page, from the PLAIN collection in chunks of 50 — one `Map<row id, version>` per page, `null` for a page whose rows are none, repeated, or not exact; the publish record's reader, see `lib/page-publish-records.js`; `{ ok: false, error }` when the read fails), `projectVersions(pageIds)` (the versionnumber of each page's OWN row, from the PLAIN collection in chunks of 50 — `Map<page id, version>`, `null` for a page whose row is absent, repeated or not exact: a page's name lives in the row and in none of its files, so a rename moves no file's version), `publishedDiffers(pageId, args, expected)` (what the page's PUBLISHED copy differs from the content `args` names — the source, name, data sources, model and bindings, normalized as `update` normalizes them — read back with plain reads of the published layer, the page's row, its file rows and the bytes of the source and `config.json`, and compared with `planEdits`, the same definition of "holds that content" `update` uses on the draft; given `expected.runtimeSha256`, `compiled output` is named too when the published copy's compiled bytes do not hash to it: `{ ok: true, differing: [field…], fingerprint }`, empty when it holds it, and `{ ok: false, error }` when it cannot be told — no published copy, a failed read, a page not laid out as a page is; the build brackets it with two reads of `fileVersions` and `projectVersions` before it records a publish), `discardWorkspaces()` and `dispose({ waitMs })` (close the throwaway workspace's storage, so work still running cannot write into it or put it back, and remove it once the storage calls under way have settled; the folder is made by `temp-workspace.js`, so one a killed run could not remove is removed by the next run's sweep; both answer `{ left }`, the folders still on disk, and `dispose()` joins every cleanup an earlier call started — within `waitMs` — and also closes the backend). A caller may lend an SDK of its own (`deps.sdk`), whose workspace is then its owner's to close, and whose transport is its owner's too: a page edit through it is not limited to the components it owns. Every page-write error carries `transient: false` and `outcome`, and `pageId` once the write got as far as the send, but one — a throttle (HTTP 429) that outlasted the waits or whose next wait did not fit the run's budget (`throttledError`, carrying `statusCode: 429`, and `retryAfterMs` / `retryNotBefore` when the last answer asked for a wait; a first send refused with a 429 — as a whole request, or as the one failing part of a change set answered HTTP 200 — is waited out and sent again, on the HTTP client's schedule or the answer's `Retry-After` whole, six sends in all, from the budget `args.throttle` carries: `pushThroughThrottle`), which wrote nothing and is left for the build to run again; only a failure that proves nothing was written is `nothing` (`PRE_WRITE_REFUSALS`, a 4xx, a change set whose COMPLETE answer is one 400, 403 or 404: `refusedWith`), every other error at or after the send is `unknown`. The text of a page is made from its bytes once (`sourceText`) and then used as it is. The pure helpers (`sourceText`, `dataSourcesOf`, `pageFolderFiles`, `genPagesOfSiteMap`, `entityTablesOfSiteMap`, `writeOutcome`, `contentFingerprint`, `watchThrottles` — the wrapper that lets the backend read the `Retry-After` of a refused `$batch`, and what a change set refused as a whole proved) are exported for the callers and the testsworkspace-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 settled- left-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, 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 too+ left-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 hereapp-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 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. Shared by genpage markers and later callers+ 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. Every text it writes or appends has the access tokens the process obtained taken out first (`lib/output-redaction.js` `redactOutput`; bytes are written as they are): 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)verify-spec.js ← spec-vs-deployed reconciliation core (checks are ordered tasks on a pool of 4)build-journal.js ← durable JSONL build journal (resume diagnostics)form-preview.js ← form wireframe rendererapp-preview.js ← whole-app design renderer (data model + sitemap + forms + page-intents + design)app-spec-doc.js ← pure App Spec → readable Markdown design doc (model-app-plan.md)+ app-access.js ← pure: what an App Spec says about who can open the APP (the roles associated with it) and who can use the TABLES it introduces (`personas[]` and `roleGrants[]` privileges): the marks of an existing app a download writes (`existingAppMarkers`), the new tables nothing grants (`uncoveredTables`), which personas get the app and which opt out with `appAccess: false` (`personaAppAccess`), the sentences the lint and the design document share, and the model of what a read of the environment means for the spec (`appAccessModel`: the roles read, each with what in the spec may be it — a `roleGrants[]` entry that gives `roleId` is matched by id and is certain, an entry that names only a role and a persona are matched by name only, as "maybe" — and the grants no associated role matches)+ app-roles.js ← read-only: the roles associated with an app (`appmoduleroles`) — verify's `appIdFor` / `appRoleIdsFor` (moved here unchanged), and `appRolesOf` for the design document: `{ state: 'read' | 'absent' | 'unreadable' }`, never a throw; the app is found in the saved layer (`resolveArtifact`, which finds a draft), the roles are read through `collectionRows`, and an answer that is no list of roles is `unreadable`, never "no roles"schema-facts.js ← pure data-model provisioning fact extractor for evalspageref-resolver.js ← PAGEREF_<key> → GenPageId nav resolverpage-manifest.js ← durable <app>_pagemanifest read/writesitemap-pages.js ← pure GenPageId extractors (the TEXT readers `sitemapGenPages` / `sitemapGenPageIds`, which only refuse or report; `navigationGenPageIds`, which reads the navigation ELEMENTS through `strict-xml.js` and is what a page is deleted by) + fail-closed fetchSitemap MEMBERSHIP reader + navigationProof (page ownership proof, read as navigation, from either app layer — or from the saved layer alone, for an app that was never published and so has no published one) + cross-app scan (every other app's published AND saved navigation — the saved layer in one request — and the apps that were never published, listed in one more; a never-published app with no sitemap component is looked up by the name its sitemap carries); a read that fails is reported by value with the error itself as a non-enumerable `cause` (`withCause`), for the halt raised around it to decide from- strict-xml.js ← `readXmlElements(xml, wanted, { spans? })`: ONE strict reader of ONE XML document, in one pass, no dependency — comments, CDATA sections, processing instructions and attribute values are data, never elements; anything that is not exactly one well-formed document (or that the SDK's own xmldom would read differently) is `{ ok:false, detail }` with no element at all. With `spans`, each element also says where it is in the text (`start`, `end`), for `formxml-layers.js`. `tests/strict-xml-oracle.test.js` holds it to xmldom over a generated corpus- formxml-layers.js ← `sameFormXmlAcrossLayers(published, saved)`: whether a systemform's saved FormXML (RetrieveUnpublished) is its published one in the languages the published read carries — a caption in another language is set aside, anything else that differs (and a FormXML that is not one well-formed document, read by `strict-xml.js`) is a change; what verify's dashboard check decides "published" by+ strict-xml.js ← `readXmlElements(xml, wanted, { spans?, maxDepth?, elementOnly? })`: ONE strict reader of ONE XML document, in one pass, no dependency — comments, CDATA sections, processing instructions and attribute values are data, never elements; anything that is not exactly one well-formed document (or that the SDK's own xmldom would read differently) is `{ ok:false, detail }` with no element at all. `maxDepth` refuses a document nested deeper than the caller allows (each answered element carries its ancestors' names, so depth costs its square), `elementOnly(name)` refuses text, CDATA, comments and instructions directly inside the elements it names; without them nothing changes. With `spans`, each element also says where it is in the text (`start`, `end`), for `formxml-layers.js`. `tests/strict-xml-oracle.test.js` holds it to xmldom over a generated corpus+ formxml-layers.js ← `sameFormXmlAcrossLayers(published, saved, versions?)`: whether a systemform's saved FormXML (RetrieveUnpublished) is its published one in the languages the published read carries — a caption in another language is set aside, anything else that differs (and a FormXML that is not one well-formed document, read by `strict-xml.js`) is a change; and, for a published read that carries more than one language (the read of a user whose own language is the organization's second one, which orders and words the captions its own way) whose `versions` say the published row and the saved read answer the same `@odata.etag` (the saved layer has not been written since the publish), in everything but the captions, of any language; what verify's dashboard check decides "published" by+ zip-read.js ← `readZipEntry(archive, name, { maxArchiveBytes?, maxEntryBytes? })`: ONE strict reader of ONE entry of a ZIP archive held in memory, no dependency (`node:zlib`). The archive has to agree with itself — end record, central directory, local header, sizes, CRC-32 — and its entries have to lie end to end, from the first byte to the central directory (each the local header, the data, and the data descriptor its flags announce, with the central directory's numbers), the deflate stream filling its data exactly; ZIP64, an archive in parts, an encrypted entry, a name twice, data that inflates past the size the archive declares, bytes that belong to no entry: a `ZipReadError`. The data is found from the LOCAL header's own lengths (the platform's export has an extra field there that its central directory does not). What `translation-labels.js` opens a translation export with+ translation-labels.js ← the captions of a solution's forms in EVERY provisioned language, from ONE translation export: `readTranslationLabels(sdk.dataverse, solutionName)` → `{ ok: true, languages, lookup(table, id) }` or `{ ok: false, reason }` (it never throws); `parseTranslationWorkbook(xml)` reads `CrmTranslations.xml`, an Excel 2003 XML spreadsheet, with `strict-xml.js` and rules of its own (the `Localized Labels` sheet is validated whole first — every element and attribute the platform's, in its place — and a row, cell, type or element it does not recognise makes the WHOLE workbook unreadable; depth, name length and element counts are bounded while it reads); `settleCaption(export, { entity, id, lcid, text })` judges one caption (same, different, or unsettled with the reason); `isTranslationExport(method, url)` is the `sendOnce` rule that keeps the request from being sent twice. What `verify-spec.js` compares a tab's or a section's caption with in a language the form's own read does not carry (`readerFor`'s `translationLabels`)sitemap-merge.js ← pure: re-attach an existing app's rewritten sitemap to its live nodes (ids + everything the spec cannot describe), keep designer nav edits the spec did not makedeployed-baseline.js ← `.maker-workspace/last-applied.json`: the spec last applied or downloaded, stamped with its environment + app and the dashboard/page ids deployed there, each page with the hash of the source the pages phase read and sent (what the build's Griffel check compares a later source with)ai-candidates.js ← selects good-candidate tables for auto row-summary mode@@ -2285,7 +2448,7 @@ scripts/content-hash.js / hash.js ← content-aware phase diff: fold on-disk .tsx/contentPath byte hashes into the diff (changed-only); `recordedContentSha` reads a page's recorded hash back (the build's pages phase compares it with the page's source to tell an unchanged page from a changed one)classify-changes.js ← changed-only: classify a spec diff → fast (page-content) | full | noop + sticky debtapply-snapshot.js ← changed-only: pure eligibility state machine (identity bind, debt, tombstone, generation CAS)- apply-snapshot-store.js ← changed-only: atomic snapshot write (writeFileAtomic, also the baseline's) + workspace lease + invalidate/claim/tombstone/delete + distrust marker. `acquireLease` is the one exclusive-create-and-reclaim protocol for a lock file in a workspace: the snapshot lease (`apply-snapshot.lock`) and the build's pages lock (`pages-<app>.lock`, `sdk-build.js` `acquireAppPagesLease`) both use it, the pages lock with the owner record of `process-owner.js` and a stricter rule for "stale" — a lock left by a build that was killed is released by the next build, which says so (`released the pages lock for '<app>': the build that held it (pid …) is no longer running`), but only when that build is provably gone; a lock whose pid runs, another machine's, one with no readable record, is refused in the words it always had, and none is ever taken by age+ apply-snapshot-store.js ← changed-only: atomic snapshot write (writeFileAtomic, also the baseline's and the page ownership and publish records', with the access tokens the process obtained taken out of its text, `lib/output-redaction.js`) + workspace lease + invalidate/claim/tombstone/delete + distrust marker. `acquireLease` is the one exclusive-create-and-reclaim protocol for a lock file in a workspace: the snapshot lease (`apply-snapshot.lock`) and the build's pages lock (`pages-<app>.lock`, `sdk-build.js` `acquireAppPagesLease`) both use it, the pages lock with the owner record of `process-owner.js` and a stricter rule for "stale" — a lock left by a build that was killed is released by the next build, which says so (`released the pages lock for '<app>': the build that held it (pid …) is no longer running`), but only when that build is provably gone; a lock whose pid runs, another machine's, one with no readable record, is refused in the words it always had, and none is ever taken by ageapply-snapshot-index.js ← changed-only: build result.created → snapshot artifact mapworkspace-paths.js ← the `.maker-workspace` name + the guard that gates destructive --clear-workspace cleanupworkspace-binding.js ← a persistent `.maker-workspace` belongs to the environment it was first opened for (only `--apply` opens it; a dry run uses a temporary workspace): turns the SDK's `WORKSPACE_ORG_MISMATCH`, and a manifest the JSON parser rejects, into the build's halt (both environments as origins, the safe remedies — the teardown one only for another environment that was built in, with the folder printed on its own line; a folder that was only opened gets no build-there/teardown advice; a folder with no usable environment is moved aside, not deleted; never clears or re-binds) and into the dry run's warning@@ -3174,8 +3337,8 @@ Residual limits, accepted deliberately:a heritage keyword only where the head of a class or an interface leads to it, read back to `class` or `interface` — `class C implements (B) {` — and is a name where a `{` that nothing closed, a `;`, a `:`, an `=`, a modifier or a decorator stands before it: `class C { implements() { … } }`, `{ extends() { … } }`and `{ a: implements, m() { … } }` have the body and the head of a function, and a name read whole, with a letter beyond ASCII or a `#` in it (`{ a: café, m() { … } }`, `{ a: this.#item, m() { … } }`), no more makes a comma a heritage's than an ASCII one does; a Unicode escape, which is its own guess, and a window that endsfirst leave the list open; a class or an interface that is complete before the name or the comma — the value of a property, `{ Adapter: class extends Base {}, render() { … } }`, the initializer of a field, a declaration that no `;` ends, `class Q {}` and a line break, then `function implements() {}` —- is crossed whole by that scan, braces and head, so that its own `class`, `extends` and `implements` are no heritage of what follows (a head that ends in a name, a call, a `]`, the `>` of type arguments, a `!` or a literal leads back to its `class`, through no braces and no function; a `{` after `extends`, `implements`, a comma or an operator is an object literal's, and the braces of an arrow function or of a function are read back to no `class`);- the one that stays the guess side is a class that has a class expression for its base, `{ a: class extends class {} {}, m() { … } }`, whose head holds braces — that page, like a class whose field is named `new` before a method on the next line, is refused with the guess rather than read, a known residual: parenthesise the class expression, or name the field otherwise), of `if`, `for`, `while`, `switch`, `catch`, `else`, `try`, `finally` and `do`, and the braces that follow a `;` outside parentheses and brackets (`membersMayStandAt`, `blockBraceAt`).+ is crossed whole by that scan, braces and head, so that its own `class`, `extends` and `implements` are no heritage of what follows (a head that ends in a name, a call, a `]`, the `>` of type arguments, a `!`, a literal or the `}` of a class expression leads back to its `class`, through no function and no braces but the bodies of class expressions — `{ a: class extends class {} {}, m() { … } }` has the braces of its base in its head, which are crossed as the head of the element they are, with the base's own head and the decorators before it (`new @d class {}`), no more than four class expressions deep (`HEAD_NESTING`) —; a `{` after `extends`, `implements`, a comma, `new` or an operator is an object literal's, and the braces of an arrow function or of a function are read back to no `class`);+ what stays the guess side is a class whose head holds braces that no class expression owns — a function expression or an object literal for the base or for an element of the list (`{ a: class extends function () {} {}, m() { … } }`, `class extends {} {}`), a class expression with type arguments after it (`class extends class {}<T> {}`: the guess `brace`) and a chain of more than four class expressions, each the base of the one before it — which is refused with the guess rather than read, a known residual: parenthesise the base. A field named `new` that a line break ends — `class C { new` and a line break, then `render() { … } }` — is a field and a method (`newNamesField`), and the call after the `new` is a method's head, not an element of a heritage: the braces around the `new` are the body of a class, read back to its `class`, a member may begin at the `new` (after the start of the body, a separator, a modifier or a decorator) and no keyword or comma of a heritage list is before it, so that `class C extends new` and a line break, then `Base() {`, the same after `implements` and after the comma of `extends A,` have members, as before. What stays the guess side is a `new` that no member of a class begins (the operator that starts a statement in a function, `new X()` and a line break, then a block; a property `x.new` that ends a field's initializer; a private name `#new`) and a field of a class whose head is not read (its base a function expression)), of `if`, `for`, `while`, `switch`, `catch`, `else`, `try`, `finally` and `do`, and the braces that follow a `;` outside parentheses and brackets (`membersMayStandAt`, `blockBraceAt`).Every other brace may hold members and is not taken for a block: a class after its name or its heritage, an object literal, a type literal, the block of an arrow function (`=> {` is a function type's object type as well), the substitution of a template, the braces after a `}` or a `:`, and after a name that a keywordspells (`class C extends a.else {`) or that an escape, a `$` or a letter beyond ASCII cuts. A decorator ends where a name, a literal, a closing bracket, the `>` of type arguments or the decimal point of a number stands whose `@` isat the same level of brackets, with nothing but names, dots, `?.`, `!` and closed brackets between them (`@dec`, `@a.b()`, `@(x)`, `@dec<T>()`, `@dec<T>`, `@1.`, ``@tag`x` ``); a number's digits stand alone after anything but a name or another number, and so after the white space that TypeScript skips between two tokens, a no-break space or a line separator among it, as after a space (`@` U+00A0 `1.`, `a =` U+2028 `1.` and a line break: a character beyond ASCII that the scanner skips, `isTrivia`, is no part of a name); `@dec<T>` is an instantiation expression, which the parser takes for one before a binary operator — a generator's `*`, the name `instanceof`, a field named `in` — or a line break (`@dec<T> *delete<U>() {}`), and the `>` of an arrow or of a comparison ends none; an `@` earlier on the statement says nothing about a token inside its arguments, after an `=` or in a method body that follows it.@@ -3202,7 +3365,7 @@ Residual limits, accepted deliberately:words after a `/`, `>>` or `>>>` (the `/` may end a regex that a member precedes, or divide; the `>` may close type arguments or compare), and a type in the style of JSDoc (`a: A?`), which the parser reads and the checker rejects (TS8020), so that no page that builds has one.(The same words in a *nested* tag, `m(p = x <a in b> '</a>' + '</T>…')` or `m: Array<keyof X>`, are read both ways: `tagMayBeCode`.) `type-parameter-heads.test.js` asks the parser for each list of words and tokens above and for each reading; `ambiguity-sweep.test.js` reads a seededgrammar of heads in members, function types, elements and after line breaks (`helpers/type-head-pages.js`), the element after `void`, `typeof` and `delete` with every kind of line break before the word and after a word that takes an operand, a decorator or a `,` in parentheses, the function types whose- parameter list cannot be read to its end, the type parameters written with an escape, and a method named like an operator in every kind of braces (every heritage of a class or an interface that ends in a `)`, after `extends`, `implements` or a comma, an object literal after the `;` of a `for` head, a type literal after an `=>`), after a decorator that ends in the `>` of type arguments or in a decimal point (after white space of every kind: every character that the parser skips between tokens), and a method or a function named `implements`, `extends` or `new`, and the value before a method after a comma (a letter beyond ASCII, a private name, a word that spells a heritage keyword, a class that is complete).+ parameter list cannot be read to its end, the type parameters written with an escape, and a method named like an operator in every kind of braces (every heritage of a class or an interface that ends in a `)`, after `extends`, `implements` or a comma, an object literal after the `;` of a `for` head, a type literal after an `=>`), after a decorator that ends in the `>` of type arguments or in a decimal point (after white space of every kind: every character that the parser skips between tokens), and a method or a function named `implements`, `extends` or `new`, and the value before a method after a comma (a letter beyond ASCII, a private name, a word that spells a heritage keyword, a class that is complete, one whose base is a class expression), and a field named `new` that a line break ends, before a method.- **A JSX attribute string after trivia is a guess when its text holds a backslash** (`jsx-attribute`): TypeScriptreads a quote that does not follow its `=` at once as a JavaScript string, with escapes, and Babel and esbuildread a JSX string with none, so a page whose string ends at different quotes in the two does different things@@ -3383,6 +3546,24 @@ answer replies with a 502 JSON body itself). It can also refuse chosen requestspattern and, with `nth`, only the nth such request), so a run that fails half way — the second`AddSolutionComponent`, say — can be driven end to end.+`fake-verify-preload.js` is the smallest of them: it replaces the four things `verify-model-app.js` would reach an environment with — the+HTTP client, the SDK factory, the page backend and the verification itself (`FAKE_VERIFY`: what the verification answers, and the folders+the page backend says it could not remove) — so `verify-model-app.test.js` runs a completed verification as a process (the real script, spec+validation, throwaway workspace and printer) and reads the bytes it wrote, which a refused spec alone cannot show.++`queued-stdio-preload.js` changes how a process WRITES rather than what it reaches: it gives the script the stdout and stderr a pipe gets on+Linux and macOS — sockets over descriptors 3 and 4, whose writes are queued when the pipe cannot take them at once — on every platform (Node+makes a pipe on descriptor 1 or 2 synchronous on Windows, so a Windows run with its own stdout never shows what `process.exit` does to a queued+write). Spawn with `stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe']` and read `output[3]` and `output[4]`; `result-whole-before-exit.test.js`+and `printers-whole-before-exit.test.js` use it to read the text a printer that exits right after writing megabytes delivers. That text is not+what proves the fix: how much of it a printer without the blocking call loses depends on the runtime and on how far the reader reads ahead —+`printers-whole-before-exit.test.js` holds its reader back by pausing its streams, which does not stop the runtime reading below them, and on+Windows a megabyte from such a printer arrived whole under Node 20 and cut at 65,536 characters under Node 22. The proof is the ORDER:+`write-order-preload.js` records, inside the process, each `setBlocking(true)` on stdout's or stderr's handle and each write to them, and the+tests require each stream to be made blocking before its first write — which fails on every run for a printer without the call, on every+platform and runtime. The texts are megabytes long without a command line that long: `huge-failure-preload.js` makes the plugin's flag check+answer, or its argument parser throw, with such a message, and `fake-auth-check-preload.js` refuses `check-auth.js`'s WhoAmI with such a diagnostic.+`scripts/tests/helpers/run-with-fakes.js` (`runScript(script, argv, { platform, pac, files, read })`) is the widerform, for a script that reads connections, connector metadata or deployment settings. The child runs over a fakeDataverse, Business Application Platform and Power Apps service (`fake-power-platform.js`, installed by@@ -3402,7 +3583,7 @@ atomic `$batch` change sets, a publish that rotates every token) in `genpage-sdkstatus (`failBatch`, a 429), and a request still in flight when its client gave up on it (`strandBatch`: the client sees a timeout, and the change set commits only when`landStranded()` is called — after the read that looked for it, and perhaps beside its resend); a refused `$batch` may carry headers (`failBatch` answers a status, or `{ status, headers }` for a throttle with its `Retry-After`: the waits of a throttled page write are asserted against them, with the backend's `sleep` and `random` seams recording the waits instead of taking them), and so may a refused PART of a change set (`failOn` answers a status, or `{ status, headers }`: the answer is HTTP 200 with the one part that failed, which is how the service refuses a change set as a whole); with a workspace storage that can be filled or held (`ENOSPC` after the commit,a write stopped half-way) they drive the unknown-outcome races and the disposal-while-working cases against the real bundle. The build's pages phase is run twice over one-workspace against the real backend in `sdk-build-pages-deploy.test.js` (a create whose answer is lost and whose page cannot be read, then the next build; and an unchanged rebuild, a rebuild after a failed publish, a rebuild that changes one page, a page published from another workspace, a page saved as a draft only, a file row added or removed and a record with no versions, each counted in the requests the page service received — change sets, `PublishXml` and the reads of the files' and rows' versions — against the record in `lib/page-publish-records.js`, whose own cases are in `page-publish-records.test.js`, the reader of the files' versions in `genpage-sdk-file-versions.test.js`, the evidence of the proof — the pages' own rows, the compiled output of the draft at the publish and of the published copy, and the failure a result carries — in `genpage-sdk-publish-proof.test.js`, and the read-back of the published copy in `genpage-sdk-published-copy.test.js`; and another writer that publishes over a page before, while and after the build reads its published copy back — its source, or its compiled output alone — or renames it, which leaves the page unrecorded so that the next build publishes it; and a page write the service throttles, which the backend waits out inside the phase, or which the build runs again when the throttle outlasts the backend's waits — with the wait the service asked for carried across that change of layer, and the waiting those two layers add one budget of five minutes, with each layer's waits recorded in one list — and the production HTTP client's own waits for a throttled read, which are not drawn from it: ten minutes of waiting, five of them inside the budget, and a build that succeeds). The build's retry is held in `halt-retry-policy.test.js` (every halt in the sources against a table, raised by the production code with a label that reads as a transient error, and the real retry loop counted: a refusal runs once, a 429 or a 503 four times; the real SDK's answer to a read of a table called like a lock — a 403, a 400 or a 404 that echoes it runs once; and, through the production HTTP client and the real SDK, a certificate failure whose alternative name spells a reset runs once and a reset runs again), `retry-policy.test.js` (the rule, with the SDK's own `ConnectionError`: a status that is not transient is final whatever the answer echoes, a condition is named by its documented error code and not by its words, a transport failure is decided by Node's own code before its words), `throttle-budget.test.js` (the budget) and `sitemap-pages-cause.test.js`. And a test of a CALLER — the upload script, the build's pages phase, verify, download, teardown — takes the backend+workspace against the real backend in `sdk-build-pages-deploy.test.js` (a create whose answer is lost and whose page cannot be read, then the next build; and an unchanged rebuild, a rebuild after a failed publish, a rebuild that changes one page, a page published from another workspace, a page saved as a draft only, a file row added or removed and a record with no versions, each counted in the requests the page service received — change sets, `PublishXml` and the reads of the files' and rows' versions — against the record in `lib/page-publish-records.js`, whose own cases are in `page-publish-records.test.js`, the reader of the files' versions in `genpage-sdk-file-versions.test.js`, the evidence of the proof — the pages' own rows, the compiled output of the draft at the publish and of the published copy, and the failure a result carries — in `genpage-sdk-publish-proof.test.js`, and the read-back of the published copy in `genpage-sdk-published-copy.test.js`; and another writer that publishes over a page before, while and after the build reads its published copy back — its source, or its compiled output alone — or renames it, which leaves the page unrecorded so that the next build publishes it; and a page write the service throttles, which the backend waits out inside the phase, or which the build runs again when the throttle outlasts the backend's waits — with the wait the service asked for carried across that change of layer, and the waiting those two layers do, with the production HTTP client's own waits for a throttled read or publish, one budget of five minutes, with each layer's waits recorded in one list: two reads and two page writes throttled for a minute are waited out inside it, ten minutes of throttling are not (the build stops with the budget's halt), a read the budget has no room to wait for is handed back as the 429 it is and stops the build the same way, through the engine's own backend and client — as does the read before an update, and the read of a page a pending create left behind, which are the throttle's refusal and neither an unreadable page nor a conflict — and a client given no budget waits as it always did). The build's retry is held in `halt-retry-policy.test.js` (every halt in the sources against a table, raised by the production code with a label that reads as a transient error, and the real retry loop counted: a refusal runs once, a 429 or a 503 four times; the real SDK's answer to a read of a table called like a lock — a 403, a 400 or a 404 that echoes it runs once; and, through the production HTTP client and the real SDK, a certificate failure whose alternative name spells a reset runs once and a reset runs again), `retry-policy.test.js` (the rule, with the SDK's own `ConnectionError`: a status that is not transient is final whatever the answer echoes, a condition is named by its documented error code and not by its words, a transport failure is decided by Node's own code before its words), `throttle-budget.test.js` (the budget), `throttle-client-budget.test.js` (the wiring that gives every client of a run the one budget: the page backend's, the build's and the upload script's), `throttle-engine-stop.test.js` (the engine's runner: no step starts after the budget has refused a wait, and the name column length a run owes is still paid — in the settlement of a halted phase and in the pass that completes one, where the budget's refusal of the first of two tables' updates leaves the second's set and its key for the next run — and a step the runner stopped before it began is never taken for a length that was set (`runBestEffort`'s `onFailure`); the column change set that stops the phase instead of falling back is held against the real SDK in `table-columns-in-create.test.js`, as are the two owed lengths, through the build as well) and `sitemap-pages-cause.test.js`. And a test of a CALLER — the upload script, the build's pages phase, verify, download, teardown — takes the backendas a seam and is handed `fakeGenpage(options)` (`helpers/fake-genpage.js`), which answers what the real backend answers (a name read from theenvironment, a page created under a minted id, a read that fails) and records every call. `scripts/genpage.js` is tested at four levels: its command line, what each verb asks of the backend and prints, and what download and types write, against that stand-in (`genpage.test.js`); the backend's page verbs — `describe`, `delete`, `removeFromApp`, `runtimeTypes`, `defaultViews`, `baseLanguage` and the placement that finishes only when the app does not show the page — against `FakeSdk` (`genpage-sdk-verbs.test.js`, with a world of apps for the scan a delete makes) and against the real bundle over `appTransport` (`genpage-verbs-real-bundle.test.js`: the app's saved and published layers move as the operations claim) — and over an app whose navigation opens a table and whose maker took a Main form, a public view and a chart out of it (`helpers/fake-app-components.js` laid over `appTransport`, which answers an AddAppComponents for another app as for an app that does not exist; `genpage-app-edit-real-bundle.test.js` reads the AddAppComponents bodies a placement, a removal, a pin, an upload and the build's pin send: the views they pin and nothing else — `appTransport` alone has generative pages in its navigation only, where the SDK derives no component, which is how a page edit that put the excluded ones back went unseen; `app-component-scope.test.js` holds the limit itself — what it reads by path (percent-decoded) and what it refuses, for a `post` and for a raw POST alike, and the canonical form it decides on and sends in every branch (an object that serializes itself, an address or body that answers differently the second time, the `Content-Length` it declares, an encoded address, a `$batch` — classified the same through `post` and `postRaw`, a JSON one entry by entry), the latter also over the plugin's own transport (`helpers/wire-framing.js` gives the `Content-Length` Node's client would send) — and `genpage-upload-language-real-bundle.test.js` the language an upload titles its entry in, in a German-only environment, and what is said when it cannot be read while a placement is being completed); and the script as a PROCESS (`genpage-process.test.js`: the exit code, one ASCII line on stdout, the words on stderr, the bytes written, and the workspace removed before the process ends) over the real bundle with only the HTTP client replaced (`helpers/fake-genpage-preload.js`, which takes the pages, one app, the org's languages and a refusal from `FAKE_GENPAGE` and writes what the run did to `FAKE_GENPAGE_LOG`). `apps.js create`'s view pins run through `fake-apps-org.js`, which seeds a page fake from its `pages` (`dataSources`, `raw`) and answers a table's default view from `views`. `genpage-no-pac.test.js` scans the productionscripts for a page verb of `pac model genpage` (an allowlist: only the connector verbs `list-connector-operations` and `get-connector-schema`, which read a@@ -3431,6 +3612,35 @@ with the access token taken out (whole and by part: a service that rejects a tokwhat fails), by the same scrubber the Dataverse HttpClient uses; a success is returned as it came. Reach for `httpClient` only when you must share the exact client instance the SDK isusing — and check first that the SDK has not since grown the method, as it did for entity privileges.+**What a script writes is cleaned where it is written — not in the answer, and not in what the SDK raises.** A service that rejects an access token may repeat it, whole or by a part, in a diagnostic — spelled however its+gateway wraps and escapes a long value — and the SDK quotes it: into the message of an error (a change set the service refuses as a whole is answered HTTP 200 with the one part that failed, a success to the HttpClient, and the SDK+quotes that part into the error it raises), into a warning it returns, into the data of an answer. The answer is the caller's: the strict `$batch` readers count its bytes (`completeBatchStatus`, the page backend's refusal proof,+and the retry that follows from it), and rewriting it changed what they prove (a refusal read as unproven became proven; a throttled page write went from two sends to six). An error is not the place either: the text has more+roads out of the SDK than anyone can list (a message, a stack, an object beneath it that may be frozen or hold an accessor that must not be run to look, a warning in a result), and a guard on the errors misses the roads that+are not errors. Every one of those roads ends in the same few places, and there the text is a string: `lib/output-redaction.js` keeps every access token the process OBTAINED (noted where it is read from the Azure CLI and where a+client sends it) out of everything the process writes, and changes nothing else — the SDK's errors, warnings and results, and the service's answers, are exactly what they were. The output paths it covers:++| What the process writes | How the token is kept out |+|---|---|+| stdout and stderr — every `console.*` call, every script's result printer and warning printer, the progress lines, a library's own output, the SDK bundle's | `process.stdout.write` and `process.stderr.write` are wrapped when the first token is noted (a process that has none is untouched); text only, bytes pass. `emitResult` cleans its own text too, so a result is clean where a caller has replaced `write` |+| what Node itself prints when an error ends the process (an uncaught exception, an unhandled rejection) — it never passes through `write` | a handler prints it, cleaned, with the same exit status, when nothing else handles the error (a test runner has its own listener and is left alone) |+| the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, a plan, the settings template | `writeFileSafe` and `appendFileSafe` (`lib/safe-fs.js`) clean the text they write |+| the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records | `writeFileAtomic` (`lib/apply-snapshot-store.js`) cleans the text it writes |+| every file of the SDK's workspace — artifacts, their metadata, the manifest | the SDK writes them through `writeTextAtomic` and through nothing else; `lib/maker-sdk.js`, the one factory, wraps the storage it is given |++`output-token-writers.test.js` lists every other write of file content in the plugin and says why none of them can carry a token (each writes what the plugin made itself or a person gave it, or runs in a process that obtains+no token), so a new writer fails there until it is classified; it also pins that the one raw write to a descriptor is `solution-settings.js`'s own, and that no script pipes a child's output to a stream. A token is looked for as+the text SPELLS it: one character at a time, each the character itself or an escape of it, with a fold between any two (white space, `\r\n` as JSON writes it, a run of backslashes for 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 its letters (`\n` before a part that starts+with `n`) read both ways — in one linear pass over the text, every needle (the token and each of its parts of 24 characters or more) at once, with a bounded set of the second readings beside it (a text that would need more is+refused, and the writer fails closed: a stream writes a notice, a file is not written), the whole span becoming `<token>` so that JSON that was written is JSON still. Not read: other encodings of a token (percent-encoding,+base64, entities), a token another process obtained, bytes (a Buffer a writer is given is written as it is), a token written in two separate calls to `write`, and the end of a part a formatter cut short (`util.inspect`+prints at most 10,000 characters of a string). Observe the boundary at the process's descriptors and files — `output-token-boundary.test.js` runs real processes (`tests/helpers/token-boundary-child.js`), in colours too — and not by replacing `process.stderr.write` in a+process of your own, which replaces the guard itself. `output-redaction.test.js` holds the matcher (against an exact reference that follows every reading over random spellings, JSON validity, cost on a large text and on texts made of nothing but escapes), the registry and the guards,+`output-token-real-bundle.test.js` the real bundle and the production client (the SDK's error is the SDK's own; the answer reaches the SDK byte for byte as the service sent it; a page write whose refusal proof and sends are+those of a client that takes nothing out). `solution-settings.js` keeps its own guard on what it writes (below), which stacks with this one. The pcf plugin carries the copy of the module and notes the tokens it reads; its+`pcf-push.js` writes its receipt through it and `makePcfSdk` guards the SDK's workspace (`plugins/pcf/scripts/tests/pcf-push-token.test.js`), and it has no SDK call that writes through a change set.+When you do go direct, all four of these apply:1. **Comment WHY the SDK cannot serve it** — name the SDK method you would otherwise call and what it@@ -3817,9 +4027,9 @@ real bundle, because a stub stays green through a change in the SDK's own rule.- **An app header write is never unconditional** (`scripts/tests/app-ai-description-real-bundle.test.js`,`scripts/tests/app-header-text-real-bundle.test.js`). TheSDK writes the app's name, description and routing description conditioned on the appmodule ROW token a- fetch read, even when its own read of the header fails (the header PATCH carries `name` and `description` —- always both, whichever one an edit changed — and, when one is supplied, `aiappdescription`; the icon is written at- create only). A header edit made while it+ fetch read, even when its own read of the header fails (the header PATCH carries only the texts that changed:+ `name`, `description` and, when one is supplied, `aiappdescription` — and every text its copy holds when that read+ fails; the icon is written at create only). A header edit made while itholds no token throws `APP_UPDATE_NO_ETAG` before anything is written (it used to send the PATCH plain,which overwrote another writer's header). The plugin edits an existing app's header only on a copy it hasjust fetched, and only its text (`name`, `description`: `applyAppHeaderText`) and the routing description@@ -4207,7 +4417,11 @@ real bundle, because a stub stays green through a change in the SDK's own rule.from a service's answer either: the az-token client takes the access token out of every answer that is not asuccess (its body in whatever mode it is read, its headers) and out of a transport failure's text, whole and byeach part of 24 characters or more (`scrub` and `scrubAnswer`, `lib/sdk-http-client.js`, which the Power Apps- client uses too; a success is the caller's data and is never touched; `sdk-http-client-scrub.test.js`). An HTTP+ client uses too; a success is the caller's data and is never touched; `sdk-http-client-scrub.test.js`). A change set+ the service refuses as a whole is such a success — HTTP 200 with the one part that failed — and the SDK quotes that+ part into the error it raises: the answer is not rewritten (the strict `$batch` readers count its bytes), and+ `lib/output-redaction.js` keeps the tokens the process obtained out of everything it writes (the table in+ "What a script writes is cleaned where it is written" above; `output-token-boundary.test.js`). An HTTP200 can be a failure all the same — StageSolution answers 200 with a status of `Failed`, and the SDK's messagequotes the dependencies and validation results it was given; a job's log is a 200 too — so `solution-settings.js`takes every access token the run sent (`recordingTokens`: every client of the run is given its token through one@@ -4296,44 +4510,83 @@ real bundle, because a stub stays green through a change in the SDK's own rule.deadlock): a request that is named once is sent once, whatever the answer.- **The one exception: an import the platform refused to start** (`sendImport` in `solution-settings.js`; theclient itself stays absolute). While a publish, or another import, holds the environment's customization lock the- platform answers `ImportSolution` with HTTP 429 and a Dataverse error code of the lock family. The codes are the- customization-lock codes of the platform's error reference whose DOCUMENTED text says the operation could not be- started — `0x8004F061`, `0x8004F062`, `0x8004F063`, `0x8004F064` and `0x8004F067`, the `CustomizationLockEx_*` codes- ("Cannot start the requested operation …", and, for `0x8004F063`, "Cannot start another … because there is a previous …- running") — pinned as an exact set. `0x80071151` (`SolutionConcurrencyFailure`) is NOT one of them: its documented text- says the installation or removal FAILED, which does not say that nothing started, and an answer with that code is sent- once and reported as it always was, whatever words come with it. Matched on the code, never on the words. Measured- on a Public-cloud environment, `0x80071151` is what the platform answers an import that meets another import or a- publish — with the "Cannot start the requested operation [Import] because there is another [Publish] running" words- — and the refused import's job exists by then (it reads back with its progress at 37.5%), so neither the code nor- the 404 proof below would let it be sent again: in practice the exception has not been seen to apply, and a resend- for `0x80071151` would need a proof built on the job row's own state. An answer with one of the five codes- is the one that says the- import did not start, and it is the one send that may be repeated — with two conditions, both shown before the- second copy leaves. The status and the code must be the lock's (a service protection 429, `0x80072321`/`22`/`26`,- is another kind and is sent once, like `0x80071154`, an operation that FAILED because of another, which had- started); and `GET importjobs(<id>)` for the id the refused send carried must answer **404** — "the ID of the import- job that will be created to perform the import" does not exist, so nothing started. Any other answer to that read- (the job exists, 401, 403, 5xx, 429, no answer, no token) is not proof, and the run ends as it always did. The wait- comes first (10 s, then 20, 40 and 60 — or the platform's `Retry-After` when that is longer, in either of its forms and- WHOLE: the client's own retries cap it at a minute, this one does not, since a send before the time the platform asked- for is a send it has said it will refuse), so the proof is the latest evidence before the send, and the send carries a- NEW job id (the body is otherwise byte for byte the same, the package included, and the SDK does not stage again: the- retry is below it, in the transport). At most five sends in all, and one budget of **five minutes** of elapsed time- for the whole retry, from the first refusal to the last send (`IMPORT_RETRY_BUDGET_MS`: every wait and every proof- read in between; not the time an import the platform ACCEPTED takes, which is the action's own hour, and a refused- send is answered in moments). Before each wait the run asks whether it fits in what is left; when it does not (a- `Retry-After` of ten minutes) the retry ENDS there — never an early send to make it fit — and so it does when the- proof read leaves nothing of the budget: the platform's refusal is the failure, with the sends so far, and a sentence- of the plugin's own that says why (`ImportSolution was not sent again: the next wait, …`), told by+ platform answers `ImportSolution` with HTTP 429, in one of two forms, each with a proof of its own that nothing+ of the package was applied.+ **A customization-lock code.** The codes are the customization-lock codes of the platform's error reference whose+ DOCUMENTED text says the operation could not be started — `0x8004F061`, `0x8004F062`, `0x8004F063`, `0x8004F064` and+ `0x8004F067`, the `CustomizationLockEx_*` codes ("Cannot start the requested operation …", and, for `0x8004F063`,+ "Cannot start another … because there is a previous … running") — pinned as an exact set. An answer with one of the+ five codes is the one that says the import did not start, with two conditions, both shown before the second copy+ leaves. The status and the code must be the lock's (a service protection 429, `0x80072321`/`22`/`26`, is another kind+ and is sent once, like `0x80071154`, an operation that FAILED because of another, which had started); and+ `GET importjobs(<id>)` for the id the refused send carried must answer **404** — "the ID of the import job that will be+ created to perform the import" does not exist, so nothing started. Any other answer to that read (the job exists,+ 401, 403, 5xx, 429, no answer, no token) is not proof, and the run ends as it always did. The wait comes first (10 s,+ then 20, 40 and 60 — or the platform's `Retry-After` when that is longer, in either of its forms and WHOLE: the+ client's own retries cap it at a minute, this one does not, since a send before the time the platform asked for is a+ send it has said it will refuse), so the proof is the latest evidence before the send.+ **`0x80071151` with "Cannot start" words.** `0x80071151` (`SolutionConcurrencyFailure`) is NOT in that set: its+ documented text says the installation or removal FAILED, which does not say that nothing started. But it is what the+ platform was measured to answer an import that meets another import or a publish — "Cannot start another [Import]+ because there is a previous [Import] running at this moment …", or "Cannot start the requested operation [Import]+ because there is another [Publish] running …" — so an answer with HTTP 429, that code (either case of its hex digits)+ AND a message that begins `Cannot start` (`concurrencyRefusalOf`) is looked into, and any other answer with the code+ is sent once and reported as it always was (the words only select what is looked into; they prove nothing). The+ proof is the refused send's own job, read ONCE and AT ONCE — before the wait: a refused send's job is final when the+ answer is in hand and is not written again, and a job that proves nothing makes the wait pointless — with+ `GET importjobs(<id>)?$select=importjobid,completedon,data` (`readRefusedImportJob`; `progress` is the same for a+ running import and a refused one, and `solutionid` is set for a solution that was never made, so neither is read).+ `lib/import-job-proof.js` holds the rule and the measurements it rests on. The job **does not exist** (404): the+ refusal came at the first lock check, before the platform made a job, and nothing started. Or it **exists** — two+ imports started together, refused at the second check — and is finished (`completedon` set) and its `data`, read as+ ONE XML document by `lib/strict-xml.js` (a log it cannot read is no proof: a pattern over the text misses a+ `processed="true"` after a `>` in an attribute value and finds the attributes in a comment), is an `importexportxml`+ whose root says `succeeded="failure"` and `errorcode="-2147020463"` (0x80071151 as a signed 32-bit integer), every+ `solutionManifest` (at least one) is `processed="false"` and no other element but the package's own checks+ (`upgradeHandler`, `validateHandler`) is marked anything but `"false"`: the import stopped at the lock before it+ applied a solution, a table or a form. Every comparison is exact (`"Failure"`, `-2147020463.0`, `"True"` are no+ proof), a log of more than 8 MiB is not read, and anything else — a job still running, one that failed AFTER it+ began (`errorcode="-2147188685"`, the manifest processed), a log of another shape, a read that answers 401, 403,+ 429, 5xx or nothing — is NOT proven: the import is sent once, and the failure carries a sentence of the plugin's+ own — told by `observe.onImportRetryUnproven` — that says why in fixed words and numbers (never a text the+ platform wrote) and what to do: look up the import job (`importjobs(<id>)`, or the solution history in Maker), and+ run the import again only when it shows nothing was imported and the other operation has finished. All 347 states+ of a job's row that the measurement captured — twenty imports read every 250–500 ms until nothing changed — were+ put through the rule: it accepts exactly the 8 final rows of refused imports and none of the other 339 (running+ imports, imports that applied the package, a refused import's row before its final write, imports that failed+ after they began); `import-job-proof.test.js` holds it to a twin of each kind of state and to every clause.+ **Both kinds**: the send carries a NEW job id (the body is otherwise byte for byte the same, the package included, and+ the SDK does not stage again: the retry is below it, in the transport). At most five sends in all, and one budget of+ **five minutes** of elapsed time for the whole retry, from the first refusal to the last send+ (`IMPORT_RETRY_BUDGET_MS`: every wait and every proof read in between; not the time an import the platform ACCEPTED+ takes, which is the action's own hour, and a refused send is answered in moments). The same sends, waits and budget+ serve both kinds: they are one lock, and the measured holders are short — a publish of six tables 3–12 s, an+ import of a package of six tables 48–127 s — against the 130 s that the four waits add up to; at most four reads of+ a refused send's job are made, one for each refusal that is not the last (the fifth send's refusal is the sends+ running out, and is not looked into). Before each wait the run asks whether it fits in what is left; when it does+ not (a `Retry-After` of ten minutes) the retry ENDS there — never an early send to make it fit — and so it does when+ the proof read leaves nothing of the budget, and when a wait ENDS past it (the budget is asked again after every+ wait, for both kinds: a timer resumes later than it was asked to on a busy machine or a laptop that slept, and the+ check before the wait cannot know that): the platform's refusal is the failure, with the sends so far, and a+ sentence of the plugin's own that says why (`ImportSolution was not sent again: the next wait, …`), told by`observe.onImportRetryStopped`. A send that follows a refusal is judged like a first send, so a gateway'sanswer to it is the failure, "the last send was not sent again", naming ITS job. The output names the job that ran(`importJobId`), how many sends it took (`importAttempts`) and each refused send with the wait after it- (`importRefusals`); when the sends run out the failure is the platform's refusal with that count added. The retry is- opt-in (`observe.onImportRefused`, which only `runImport` gives), so the client of any other caller sends once.- It happens inside the SDK's call, so it can neither become the `pac` fallback nor follow one: a refusal is not a- fallback code, and the fallbacks all come before the first `ImportSolution`. Pinned in `solution-settings.test.js`- (the allowlist, the waits, the budget over a clock that only the waits and the reads move),+ (`importRefusals`; a refusal with `0x80071151` also has `proof`: `job-absent` or `job-refused-before-any-component`,+ and the failure's sentence says which); when the sends run out the failure is the platform's refusal with that count+ added, and a sentence for the KIND of refusal the fifth send met (`observe.onImportRetryExhausted`,+ `exhaustedSentence`): for a lock code the advice it always had (run the import again when the other operation has+ finished); for `0x80071151` — whose job alone could show that nothing was applied, and was not read — never that+ advice outright, but what to look up first: the job must not exist (404), or must be finished with the log of an+ import refused at the lock (the rule above), and the other operation must have finished — anything else means the+ import may be running or may have applied the package. A fifth answer of any other kind (a service protection+ 429, `0x80071154`, `0x80071151` with other words) is not a refusal the retry knows and gets no advice of the+ plugin's, as on a first send. The retry is opt-in (`observe.onImportRefused`, which only `runImport` gives), so+ the client of any other+ caller sends once. It happens inside the SDK's call, so it can neither become the `pac` fallback nor follow one: a+ refusal is not a fallback code, and the fallbacks all come before the first `ImportSolution`. Pinned in+ `solution-settings.test.js` (the allowlist, the waits, the budget over a clock that only the waits and the reads move,+ the order of the read and the wait for each kind), `import-job-proof.test.js` (the rule),`solution-settings-real-bundle.test.js` (the real SDK and client over a fake platform that refuses chosen sends andkeeps a count of what it took) and in a child process (`instantWaits` in the preload).- **`pac`'s time limit** (`lib/pac-fallback.js`): two fixed constants, in the way `PAC_PROBE_TIMEOUT_MS` bounds@@ -4554,16 +4807,18 @@ real bundle, because a stub stays green through a change in the SDK's own rule.uses is refused by the platform (HTTP 400, `0x8004f01f`) and KEPT, which is success — a removal that threwthere would fail the teardown step of every table whose model another component had adopted. What the SDKcannot settle throws `ROW_SUMMARY_REMOVAL_UNCONFIRMED` (the skill-row delete's outcome unknown, naming our- model) or `ROW_SUMMARY_MODEL_NOT_DELETED` (the model left behind, naming it). Teardown's `aiSummary` step- looks for the skill row first, with the SDK's own request, because `removeRowSummary` answers nothing both- when it removes a row summary and when it finds none — a step that only called it printed `(1 deleted)` for- every table without one — and reports a table with none as not found (`teardown-row-summary-lookup.test.js`- holds the lookup to what the bundle asks for). It is still best-effort for failures: a lookup that cannot be- made (`not looked up — …`, kept) or a removal that throws (`kept — 1 not removed: <the SDK's words>`) fails- nothing, and the closing line counts it with the kept steps, not the deleted ones, as its own step line does.- The table delete that follows reports the- dependency if the skill row is still there, and a model left behind blocks only a later row summary for the- same table, by name.+ model) or `ROW_SUMMARY_MODEL_NOT_DELETED` (the model left behind, naming it). It looks the skill row up itself and+ answers `{ removed }`: `true` once the row summary the table had is gone (its skill row deleted, or already gone when+ the delete arrived), `false` — deleting nothing — when the table had none. Teardown's `aiSummary` step makes no lookup+ of its own and says what that answer says: `removed` is `(1 deleted)`, and nothing is `(not found)` — counted with the+ steps that found nothing, never as a deletion — as is an environment with no AI skill table (the SDK's lookup answers+ 404). (The SDK used to answer nothing in both cases, so a step that only called it printed `(1 deleted)` for every+ table without a row summary, and 2.16.0 looked for the skill row first, with a request of its own.) It is still+ best-effort for failures: a lookup or a removal that throws (`kept — 1 not removed: <the SDK's words>`; a first row+ that is no row is one — a failure of the lookup, never "no row summary") fails nothing, and the closing line counts it+ with the kept steps, not the deleted ones, as its own step line does (`teardown-row-summary-removal.test.js` holds all+ of it over the real bundle). The table delete that follows reports the dependency if the skill row is still there, and+ a model left behind blocks only a later row summary for the same table, by name.- **Changes in the same SDK release that no plugin path reaches** — read these again before a plugin changereaches one. (`importSolution`, which now requires `overwriteUnmanagedCustomizations`and `publishWorkflows`, was on this list while no script called it. `solution-settings.js import` does, with@@ -4793,14 +5048,20 @@ node evals/model-apps/app-builder/run-app-builder.js### Skill routing — agent in the loop`evals/model-apps/routing/` grades which skill a real agent CLI (Copilot CLI or-Claude Code, headless, isolated, only this plugin loaded) invokes for each of 20+Claude Code, headless, isolated, only this plugin loaded) invokes for each of 35prompts: `/genpage` vs `/app-builder` from both sides of their boundary, plusnegatives that share vocabulary (Power Pages, canvas, Power Automate, a generic-React dashboard). The offline harnesses above grade what a run *produced* and+React dashboard, a code app — several of them saying outright that the request+is not for Power Platform, Dataverse or a model-driven app) and positives that+carry a "not" about the other skill or the schema. The offline harnesses above grade what a run *produced* andcannot see a mis-route; both skill descriptions point at each other, so awording change to one can start stealing the other's prompts. The agent iskilled at its first plugin-skill call, so a trial costs about one model turn;-cases are graded as a pass rate over N trials. **Run it when you edit a skill+cases are graded as a pass rate over N trials, on the first plugin skill the agent+asks for at any turn. The decision of its **first turn** is reported beside that+grade and never in place of it: a skill it reaches for only after a first turn that+chose none (a stand-in, perhaps, when its read-only menu has no way to do the work)+still fails a negative case, and the case line says the first turn chose none. **Run it when you edit a skill`description:`.** It is not a per-PR gate (cost, non-determinism):`model-apps-agent-evals.yml` runs it on a same-repo PR labelled`run-agent-evals`, weekly, and on demand, using Copilot CLI authenticated by the@@ -4808,6 +5069,13 @@ workflow's own `GITHUB_TOKEN` (`copilot-requests: write`) — no secret toprovision. Its parsing/grading/process code is unit-tested on every PR against afake agent. See [`evals/model-apps/routing/EVAL_GUIDE.md`](../../evals/model-apps/routing/EVAL_GUIDE.md).+A skill `description:` has to stay under 1,024 characters (GitHub Copilot's limit, enforced by+`scripts/validate-skill-descriptions.js`), so say what a request needs and leave process detail to the skill+body. The descriptions of `/genpage`, `/app-builder` and every agent also say what they are **not** for: a+generic or standalone React or web app, the other Power Platform products, and a request that rules out+Power Platform, Dataverse and model-driven apps. `evals/model-apps/routing/tests/descriptions.test.js`+pins those sentences and the trigger phrases the positive cases route on.+```bashnode evals/model-apps/routing/run-routing.js --dry-run # what would launchnode evals/model-apps/routing/run-routing.js --tier smoke --runs 1 # quick local checkdiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 86b83c246..64f0e4659 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,181 @@ 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.17.0]++The bundled SDK is updated to power-platform-ux d603c799. Dashboard tiles the spec does not size now show their charts and lists, a+download keeps File and Image columns and a table's plural, and an alternate key in several languages over a new table's name column+no longer stops the first build. A relationship is reused or verified only when the environment states its whole identity, an import+refused because another import or a publish was running is sent again when its job proves nothing started, and the five minutes a run+allows itself for a throttled service now bound all of its waiting. An access token is kept out of everything a script writes, and a+large result is no longer cut short on Linux and macOS. `--verify` settles a form's captions in another language from one translation+export and puts its warnings in its result JSON, and lint no longer calls an app with no personas administrator-only.++### Added++- **A cross-feature regression matrix.** One App Spec with every feature an offline fake can model faithfully (all column types, a+ Customer column, a global choice, status reasons, an alternate key, 1:N, self and N:N relationships, views, a chart, Main, Quick+ Create and Quick View forms, a dashboard, web resources, commands, a generative page, navigation, app settings, sample data, a+ persona and a role grant) is built, rebuilt unchanged, downloaded, verified and torn down over the bundled SDK and a stateful fake+ Dataverse that refuses every read it does not model and applies every query option it accepts. Every phase's writes and publishes+ are pinned, its reads are under a budget, the download is compared with the authored spec, and every phase is proven to leave the+ content of everything that was already in the environment as it was. Beside it, tests pin that dry runs and the teardown preview+ write nothing, downloads are stable, a rebuild without `--publish`, rebuilding a downloaded spec in place, verify naming what was+ deleted in Maker and a rebuild restoring it, a build or a teardown that fails part way finishing when run again, and a teardown of a+ downloaded spec keeping every table, relationship, global choice and row. The three files take about 7–12 s each.++### Changed++- **The bundled SDK is updated (power-platform-ux d603c799).** What a maker can see of it:+ - an app's header write carries only the texts that changed: an edit of the description does not send the name again (and the+ reverse), and a routing-description edit sends neither text — another writer's unpublished description is no longer sent again;+ - a row-summary lookup that answers something that cannot be read as a list of rows is an error: a first row that is no row, or a+ template row without a GUID id, stops the build (it used to read as "no row summary yet" and publish a model, or as "no+ template"), and teardown says the lookup failed instead of reporting "nothing to remove";+ - the Command Designer change merged since ccf2c1a1 does not reach the plugin: the commands phase writes what it wrote. The SDK's+ PCF control registration, which the plugins never called, is no longer in the bundle.+- **A name or description that is localized (or otherwise not plain text) holds back only its own edit.** The other text and an+ `app.aiDescription` are now applied and written alone, where one such text held the whole header back and a changed plain text+ beside it was reported as not applied. The text is taken off the app copy before it is pushed, so it is never sent — even when the+ SDK's own read of the header fails, which used to stop the build with `APP_HEADER_NOT_PLAIN_TEXT`.+- **An environment without the row-summary AI template skips the row summaries on the SDK's answer alone.** The build no longer reads+ the template list a second time before it skips (one warning, nothing written, as before); an answer the SDK cannot read stops the+ build with the SDK's own error, and a throttled or interrupted read is still run again.+- **Teardown reports a row summary from what the SDK says it did**: `✓ row summary <table> (1 deleted)` when one was removed,+ `⊘ … (not found)` when the table had none (also an environment with no AI skill table), `kept` with the SDK's words when the removal+ or its lookup failed — with no read of the plugin's own.+- **`verify-model-app.js` puts its warnings in the result JSON, and prints the result as pure ASCII.** Every `WARNING:` line it prints on+ stderr is now also in an optional `warnings` array of the result — the same messages, in the order printed, left out when there is+ none — when the verification passes, fails, or the spec is refused; it changes neither `ok` nor the exit status. A refused spec now+ prints the warnings it also has. A character beyond ASCII in the result (an em dash, a Spanish label) is a `\uXXXX` escape that any+ JSON parser reads back as the original text, so Windows PowerShell 5.1 can no longer garble it. stderr is unchanged.+- **A new table that no persona and no `roleGrants[]` entry grants a privilege on is a warning** ("no access declared", in lint and in+ the design document's `warnings`); a covering grant satisfies it, and `--strict` fails on it like on any warning.+- **`write-app-spec-doc.js --env` reads, read-only, the roles the app has associated with it** and lists them beside the privileges the+ spec grants. It finds an app that was saved and never published, matches a role to a persona or a `roleGrants[]` entry by id where+ the spec gives one and otherwise by name as "may be" (role names repeat across business units; every candidate is listed), and says+ "not checked" — never "no roles" — for a refused read or an answer that is no list of roles. It calls an app administrator-only+ only when the environment shows it and no persona gets the app. The command never fails because of the read.+- **A build that is throttled for more than five minutes in all now stops with `throttle-budget-exhausted`** once the five minutes are+ spent and it has something left to write (it used to finish after waiting out the HTTP client's own re-sends on top of the budget);+ running the same command again later continues from there. See Fixed.+- **`/genpage`, `/app-builder` and the six `genpage-*` agents say what they are not for**: a generic or standalone React or web app,+ Power Pages, canvas apps, Power Automate, and a request that rules out Power Platform, Dataverse and model-driven apps.+ `/app-builder`'s description lost process detail no request routes on, to stay under GitHub Copilot's 1,024-character limit; every+ capability and trigger phrase stayed.+- **The routing eval has 35 cases (15 added)** — requests that say outright they are not for Power Platform, a plain web app in the+ stack `/genpage` is written in, a Power Apps code app, and positives that carry a "not" about the other skill — and **reports the+ decision of the agent's first turn beside its grade** (`first turn: … · later: …`; `initial` / `delayed` / `turn` in `--out`). The+ grade is unchanged: the first model-apps skill the agent asks for, at any turn.+- `references/agent-interaction-contract.md` explains that declaring a tool in both naming schemes makes a host recognize it, not+ deliver it, and a test fails an agent that names `TaskCreate`/`TaskUpdate` without saying what to do when there is no task tool.+- A download's warning for a failed label read now says which read failed — the table's own, or its columns' — and only what that read+ carries; the table read's warning also says the table's plural is not written.++### Fixed++- **Dashboard tiles show their charts and lists.** A tile the spec did not size was built one row tall, which the app draws as the+ tile's title bar alone. An unsized tile is now one column by 12 rows, the most common height of the platform's own chart and list+ tiles, so two of them share a row; a tile's `colspan` and `rowspan` still win. A rebuild reuses a dashboard that exists and does not+ resize its tiles: re-create one an earlier version built under a new `name`, or resize its tiles in the dashboard designer. The App+ Spec reference said the default was 1x4; it now states the size and how tiles fill the dashboard's two-column grid.+- **A relationship is no longer taken for the declared one on its name alone.** The build skips the create of an existing relationship+ — and the dry run says `= reuse`, and `verify-model-app.js` passes it — only when the environment's answer states its whole identity:+ schema name, type, both tables and, for a 1:N, the lookup column, for an N:N the intersect table and the column each table has in it.+ An answer that left a part out used to count as "nothing contradicts". Now the build reads the relationship itself and halts, leaving+ it as it is, when that read is incomplete too; the dry run shows `? unknown`; verify fails the check and names what the answer+ lacked. An N:N whose spec names an `intersectEntityName` is refused (`relationship-name-taken`, with the way to reuse it) when the+ relationship under that name sits on another intersect table. Complete answers behave as before.+- **The five minutes a run allows itself for a throttled service now bound all the waiting it does for a throttle.** The HTTP client's+ own re-sends of a throttled read, publish, delete or column create kept a schedule of their own outside the budget; the client now+ draws every wait it takes after an HTTP 429 from the same budget in the build and the page upload. It waits what `Retry-After` asks,+ counts requests throttled together once, and announces a wait of more than five seconds on stderr. A wait that does not fit is not+ taken: the throttled answer comes back as it came, and the build stops with `throttle-budget-exhausted`, which says what the service+ asked, before its next write. A 5xx, a reset connection and the re-send of a deadlock victim are not throttling and keep their own+ schedule; every other script (and the pcf plugin's copy of the client) waits as it always did.+- **A refused throttle wait stops the build before it writes again, not only the request.** No later step that would write starts — a+ refused column change set is no longer followed by one request per column — and the build stops with `throttle-budget-exhausted`+ instead of finishing as a success. A step that only reads to find it has nothing to do still runs, so a rebuild that has nothing left+ to write after a refused best-effort read finishes, with the refusal's warning on stderr. A throttled read before an update, or of a+ page an earlier build started creating, that the budget has no room for is the throttle's refusal, not "could not read page" and not+ a conflict that asks the maker to delete a record. The client's stderr line for such a request no longer says to run the same+ command again; after a page upload's create, the result names the page and the command (`--page-id <id>`) that finishes it.+- **A refused throttle wait no longer leaves a new table's name column at the platform's default length.** The build skipped the+ length update of the next table owed one and forgot it, so a later run could not set it and an alternate key over that column was+ refused for its size on every run. Every owed length is now set whatever the budget has refused; a key waiting for it is made by the+ next run, which the halt asks for.+- **Verify no longer calls a published dashboard "not published" for a user whose own UI language is the organization's second one.**+ When the published read carries more than one language and the saved and published rows answer the same `@odata.etag`, the two reads+ are compared in everything but their captions; any other difference is still a change. A dashboard saved and not published, a row+ that answers no token, and a base-language user's read are decided as before.+- **A generative page whose class has a class expression for its base, and one that has a field named `new` before a method, are read+ instead of refused** (2.15.0 refused them with the guess `generic`). Still refused, naming the guess: a function expression or an+ object literal for the base, type arguments after a class expression, more than four class expressions nested in each other's heads,+ and a `new` that no member of a class begins; parenthesise the base, as before.+- **Lint and the design document no longer call an app administrator-only because `personas[]` is empty** (AB#6770008). A spec that+ authors no role says nothing about who can open an app that already exists — an extension of such an app leaves `personas[]` out on+ purpose — yet lint said the app "opens only for system administrators", steering authors to redefine their existing roles. Both now+ say what the spec authors; a spec that carries what a download writes (`app.uniqueName`, a page or dashboard id) is told the app+ already exists and keeps its roles. The document follows each persona's `appAccess`.+- A rebuild of an app whose name (or description) is held as one text per language writes a changed description (or name) instead of+ reporting it as not applied.+- **`solution-settings.js import` sends an import again that the platform refused because another import or a publish was running.**+ The platform answers such an import with HTTP 429 and `0x80071151` ("Cannot start another [Import] because there is a previous+ [Import] running …"), which the retry did not know, so the maker had to run it again by hand. The code alone does not say that nothing+ started, so the refused send's import job is read once, and the import is sent again — after waits of 10, 20, 40 and 60 seconds (or a+ longer `Retry-After`), at most five sends in five minutes, the budget checked again after each wait — only when the job does not exist+ or is finished and its log says the import failed with that error before it processed the solution or any component. A job that+ proves nothing is not sent again: the failure says why and to look the import job up (`importjobs(<id>)` or the solution history)+ before importing again. A resend's output says how each refusal was proven (`importRefusals[].proof`). When the fifth send is refused+ too, the failure no longer says to run the import again; it says what to check first. The retry for the lock codes is unchanged.+- **`--verify` no longer lists a form's tab and section captions as unverified just because the form read does not return their+ language** (Spanish captions in an English-language organization): they are read from one translation export of the app's solution,+ matched by the id of each tab and section, so a right caption passes and a stale, missing or empty one is reported. The export is one+ request (several seconds, more as the solution grows), made only when such a caption exists, shared by every form of the run and never+ sent twice. When it fails or cannot be read with certainty — its archive must be self-consistent and its labels sheet exactly the+ platform's shape — the captions stay unverified, with the reason, as before.+- **An alternate key labelled in several languages over a new table's name column and another column no longer stops the first+ build** where the platform makes the name column 850 characters long (HTTP 400 `0x80060895`, "Index size exceeded the size limit of+ 1700 bytes"). For such a key only, the build reads the column's length once (a typed `MaxLength` read, no labels); where the key cannot+ fit beside it but can at the length the spec asks, it is made after the length step, with both labels, instead of in the run after.+ The key's size is counted from its columns as the build creates them (an `AutoNumber` column, like one with no `type`, is created 100+ characters long whatever `maxLength` it carries). Every other key keeps its place. The warnings and the stop+ (`alt-key-name-length-not-set`) now name the platform's measured limit of 1,700 bytes (they said 900) and no longer promise that+ running the build again creates a key: a key proven too large at the asked length is said to be so, with its size and what to change;+ otherwise they say a run again may create it, that this is not certain, and what to compare if it is refused again. They no longer+ suggest labelling the key in one language. The stop's code, retry behaviour and exit status are unchanged.+- **An access token the process obtained no longer reaches anything a script writes, whatever text carries it.** A service that rejects a+ token may repeat it — whole or by a part, folded onto several lines, with a JSON escape or a backslash left in it — in a diagnostic,+ and a change set refused as a whole is answered HTTP 200, so the token could reach an error message, a warning, the journal or a file.+ Every token the process obtains is now kept out of stdout and stderr (colour output included), what Node prints when an error ends a+ script, the build's journal and status file, the baseline and snapshot, downloads and generated files, and every file of the SDK's+ workspace; the token reads `<token>` and the text around it is unchanged. Answers themselves are never rewritten, so the strict+ `$batch` readers decide a page write's resend on the same bytes as before. A text that could not be checked is not written.+- **pcf: the push receipt no longer carries the access token** a refused confirmation read quoted, and every file the SDK writes into a+ push's workspace goes through the same guard.+- **A download keeps File and Image columns.** Both report the Dataverse type "Virtual", so every download left them out without a word+ and a rebuild elsewhere lost them. They now come back typed, with `maxSizeKb` when it is not the build's default (10240 KB) and+ `isPrimaryImage` for a table's primary image. The table's own image and the platform's companion columns are not written, a column of+ another type the App Spec cannot express is named in a warning, and a size read that fails or answers short is reported — per read, and+ per column for a short answer. Only a table with such a column costs a read more (one per type).+- **A download keeps a table's plural when a rebuild would not derive it**: "Tag Catalog" for "Tag" was left out, so a rebuild into+ another environment named the table "Tags". A plural that is the display name plus "s" is still left out, so the download of an+ ordinary table is unchanged.+- **A large result or message is no longer cut short on Linux and macOS when a script prints it and exits at once.** Node writes to a+ pipe asynchronously there and `process.exit` did not wait, so an agent could receive a multi-megabyte answer, listing, auth check,+ validation report or error as a text that ended mid-string. Every printer that ends the process — `emitResult`, the printer of an+ uncaught error, each script's own result printer (`check-auth.js`, `dataverse-request.js`, `genpage-plan-provenance.js`,+ `promote-intent-pages.js`, `check-page-files.js`, …), usage errors, last-resort error handlers, the hooks' messages and the warnings+ a script prints right before its result — now makes its writes blocking first. What is printed and every exit status are unchanged,+ and Windows was never affected; as on Windows, a reader that stops reading now holds the script at its last write instead of+ receiving a truncated text.+- The page-builder worker, the planners and the entity builder no longer tell the agent to call `TaskCreate` with no alternative: a+ host can hand a subagent no task tool, so the agent tracks its task with `TaskCreate`/`TaskUpdate` or `todo` when it has one, and+ otherwise says so and tracks it in plain words; `/genpage` does not treat a worker without a task tool as a failed worker.+- The routing eval no longer ends a trial before the agent it killed has exited (an `EBUSY` on Windows), and two tests no longer+ assert a time limit that failed on a busy machine (the shared telemetry spawn test, and the test that ending a verify pass's page+ reads does not wait for a read in flight).+## [2.16.0]The bundled SDK is updated to power-platform-ux ccf2c1a1, and a new table's primary (name) column is now created required when thediff --git a/plugins/model-apps/agents/genpage-connector-builder.md b/plugins/model-apps/agents/genpage-connector-builder.mdindex e1f869410..9f6bf1c68 100644--- a/plugins/model-apps/agents/genpage-connector-builder.md+++ b/plugins/model-apps/agents/genpage-connector-builder.md@@ -6,6 +6,9 @@ description: >-connection references when needed, and produces the ## Connector Bindingscontract. Invoked only by the top-level genpage orchestrator from BOTH thecreate and edit flows; never invoked by planners or directly by users.+ Works only on generative pages in a Power Apps model-driven app. Never use it for+ a generic React or web app, or when the user rules out Power Platform, Dataverse,+ or model-driven apps (for example "no Power Platform").color: green# Two naming schemes on purpose: Claude Code names first, then the portable# Copilot aliases for the same capabilities. Every host ignores tool names itdiff --git a/plugins/model-apps/agents/genpage-customapi-builder.md b/plugins/model-apps/agents/genpage-customapi-builder.mdindex b5374dea4..362681374 100644--- a/plugins/model-apps/agents/genpage-customapi-builder.md+++ b/plugins/model-apps/agents/genpage-customapi-builder.md@@ -6,6 +6,9 @@ description: >-entity-bound Actions/Functions) plus their declared request-parameter kinds, and producesthe ## Custom API Bindings contract. Invoked only by the top-level genpage orchestrator fromBOTH the create and edit flows; never invoked by planners or directly by users.+ Works only on generative pages in a Power Apps model-driven app. Never use it for+ a generic React or web app, or when the user rules out Power Platform, Dataverse,+ or model-driven apps (for example "no Power Platform").color: green# Two naming schemes on purpose: Claude Code names first, then the portable# Copilot aliases for the same capabilities. Every host ignores tool names itdiff --git a/plugins/model-apps/agents/genpage-edit-planner.md b/plugins/model-apps/agents/genpage-edit-planner.mdindex a77d256b7..cbbe81480 100644--- a/plugins/model-apps/agents/genpage-edit-planner.md+++ b/plugins/model-apps/agents/genpage-edit-planner.md@@ -6,7 +6,10 @@ description: >-the user's edit intent, and returns a proposed edit plan for the orchestrator topresent for approval. Writes genpage-edit-plan.md, for the orchestrator toexecute, once it is re-invoked with the approval outcome. Called by the genpage- skill — not invoked directly by users.+ skill — not invoked directly by users. Works only on generative pages in a Power+ Apps model-driven app. Never use it for a generic React or web app, or when the+ user rules out Power Platform, Dataverse, or model-driven apps (for example "no+ Power Platform").color: cyan# Two naming schemes on purpose: Claude Code names first, then the portable# Copilot aliases for the same capabilities. Every host ignores tool names it@@ -134,7 +137,8 @@ you want to confirm the file layout before reading.## Step 2 — Gather Change Requirements-Create tasks via `TaskCreate`:+If you have a task tool (`TaskCreate`, or `todo`), create tasks; if you have none, skip this+and never say you created a task:1. "Analyze existing page and gather edit requirements"2. "Design edit plan"3. "Write edit plan document (genpage-edit-plan.md)"diff --git a/plugins/model-apps/agents/genpage-entity-builder.md b/plugins/model-apps/agents/genpage-entity-builder.mdindex f7e77caa4..16799b2a6 100644--- a/plugins/model-apps/agents/genpage-entity-builder.md+++ b/plugins/model-apps/agents/genpage-entity-builder.md@@ -5,6 +5,9 @@ description: >-in genpage-plan.md using the plugin's Node.js Web API scripts. Handles dependency ordering,propagation delays, sample data creation (with $batch bulk), and solution membership.Called by the genpage skill when new entities need creating — not invoked directly by users.+ Works only on generative pages in a Power Apps model-driven app. Never use it for a+ generic React or web app, or when the user rules out Power Platform, Dataverse, or+ model-driven apps (for example "no Power Platform").color: yellow# Two naming schemes on purpose: Claude Code names first, then the portable# Copilot aliases for the same capabilities. Every host ignores tool names it@@ -174,7 +177,8 @@ You will populate each section as you provision entities in Step 5.## Step 4 — Build Provisioning Input JSON-Create a `TaskCreate` task: "Build entity provisioning input".+If you have a task tool (`TaskCreate`, or `todo`), create a task: "Build entity provisioning+input". If you have none, skip this and never say you created a task.From the parsed `## Entity Creation Required` + `## Environment` data (Step 1),construct a single JSON file at `<working-dir>/provision-input.json` with the@@ -306,11 +310,12 @@ For Choice columns, each option's value is `100000000 + index` (0-based).Write the completed JSON to `<working-dir>/provision-input.json`.-Mark the task complete.+Mark the task complete (if you created one).## Step 5 — Provision Entities via SDK-Create a `TaskCreate` task: "Provision entities to Dataverse".+If you have a task tool (`TaskCreate`, or `todo`), create a task: "Provision entities to+Dataverse". If you have none, skip this and never say you created a task.Run the single provisioning command:@@ -417,7 +422,7 @@ node "${PLUGIN_ROOT}/scripts/provision-entities.js" --env "$ENV_URL" --input @<wIf sample data is created (Step 7), append `--sample-data` to the command.-Mark the task complete.+Mark the task complete (if you created one).## Step 6 — Ask About Sample Datadiff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.mdindex c665f6f31..bc82a996f 100644--- a/plugins/model-apps/agents/genpage-page-builder.md+++ b/plugins/model-apps/agents/genpage-page-builder.md@@ -5,6 +5,9 @@ description: >-Reads genpage-plan.md for page specification, RuntimeTypes.ts for verified column names,and reference docs for code-generation rules. Writes one .tsx file per invocation.Called by the genpage skill in parallel — not invoked directly by users.+ Works only on generative pages in a Power Apps model-driven app. Never use it for a+ generic React or web app, or when the user rules out Power Platform, Dataverse, or+ model-driven apps (for example "no Power Platform").color: green# Two naming schemes on purpose: Claude Code names first, then the portable# Copilot aliases for the same capabilities. Every host ignores tool names it@@ -12,6 +15,9 @@ color: green# search and todo tools even on a host that does not implement the compatible-# alias table. `TaskCreate`/`TaskUpdate` are NOT aliases anywhere — `todo` is# the portable name. No `execute`/`Bash`: this agent only authors page source.+# Declaring a tool makes a host recognize it, not hand it to a subagent: a+# Copilot CLI session gave this agent no task tool at all, so Steps 4 and 7 say+# what to do without one.# See references/agent-interaction-contract.md.tools:- Read@@ -250,11 +256,18 @@ mount, the data-fetching reference is authoritative for the in-flight de-dupe +`window` cache + readiness-dep pattern that survives the host double-mount.**Never put `dataApi` in a dependency array** (see rules.md Rule 15).-## Step 4 — Create a Task+## Step 4 — Track the Page-Call `TaskCreate` for: "Generate [Page Name] page"+Your progress on this page is one task: "Generate [Page Name] page". A host can hand a+subagent no task tool (a Copilot CLI session gives this agent only its file and search+tools), so check the tools you were actually given, once:-Mark it as in_progress immediately.+- **If you have a task tool** (`TaskCreate`/`TaskUpdate` on Claude Code, `todo` where+ Copilot provides it): create the task and mark it `in_progress`.+- **If you have none**: do not search for one, do not call a tool you were not given, and+ never say you created a task. Open your first message with+ `Task: Generate [Page Name] page — in progress` instead; Step 7 closes it. The page is+ judged by the orchestrator's completeness gate, so nothing else about the work changes.## Step 5 — Generate the Complete .tsx File@@ -550,12 +563,15 @@ Write the complete `.tsx` file to the working directory at the target file path.## Step 7 — Return Result-Mark the task as complete. Return a concise result to the orchestrating skill:+Close the task from Step 4 (mark it complete if you have a task tool). Return a concise+result to the orchestrating skill:```Page: [Page Name]File: [working directory]/[filename].tsxStatus: Written+Task: Generate [Page Name] page — complete+Task tool: [TaskCreate/TaskUpdate | todo | none on this host]```## Critical Constraintsdiff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.mdindex aef04f3db..635a07ffd 100644--- a/plugins/model-apps/agents/genpage-planner.md+++ b/plugins/model-apps/agents/genpage-planner.md@@ -7,6 +7,9 @@ description: >-present for approval. Writes genpage-plan.md, for downstream agents to consume,once the orchestrator re-invokes it with the approval outcome.Called by the genpage skill — not invoked directly by users.+ Works only on generative pages in a Power Apps model-driven app. Never use it for a+ generic React or web app, or when the user rules out Power Platform, Dataverse, or+ model-driven apps (for example "no Power Platform").color: cyan# Two naming schemes on purpose: Claude Code names first, then the portable# Copilot aliases for the same capabilities. Every host ignores tool names it@@ -517,7 +520,8 @@ the user before continuing:## Step 5 — Hand the Plan Back for Approval-Create tasks via `TaskCreate`:+If you have a task tool (`TaskCreate`, or `todo`), create tasks; if you have none, skip this+and never say you created a task:1. "Design page plan and data strategy"2. "Write plan document (genpage-plan.md)"diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.mdindex b0c9ca0ca..e7c195ba9 100644--- a/plugins/model-apps/docs/app-builder-capabilities.md+++ b/plugins/model-apps/docs/app-builder-capabilities.md@@ -22,7 +22,7 @@ apart deliberately.- Deterministic, **idempotent** build engine — discovers via the SDK (`findTables`/`findColumns`/`fetchEntityMetadata`) and creates only what's missing; new / existing / mixed envs all work.- **All Dataverse access via the vendored headless SDK**; metadata cached under `<app-folder>/.maker-workspace/` for reuse.- Phase selection (`--only`/`--skip`/`--from`/`--to`), `[n/total]` narration, `BuildHalt` gate, dry-run by default, `--sample-data` / `--publish` opt-in.-- Bounded-concurrency for independent ops; one publish round-trip per entity + the app. 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 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; the HTTP client's own re-sends of a throttled read or publish keep their own schedule and are not drawn from it; 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.+- 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>`).### Data model (Tier 1) — ✅ verified live@@ -279,7 +279,7 @@ apart deliberately.test here and by a `@jest-environment node` regression upstream.### Edit flow (download → edit → rebuild) — ✅ verified live-- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages (code, prompt, data sources and model; a page's connector and Custom API bindings stay on the deployed page but are not carried in the spec, so they survive a same-environment rebuild only), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.+- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages (code, prompt, data sources and model; a page's connector and Custom API bindings stay on the deployed page but are not carried in the spec, so they survive a same-environment rebuild only), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **File and Image columns** come back typed too — by their `AttributeTypeName` (FileType / ImageType), as both report `AttributeType` "Virtual", which an earlier release left out of every download without a word — with the `maxSizeKb` each was made with (left out when it is 10240 KB, the size a build gives a column that sets none) and, for an Image column the environment reports as the table's primary image, `isPrimaryImage: true` (a read of that detail that fails, or answers without a column, leaves the column typed without it, and the download says which read or column it was; the platform makes a table's first Image column its primary image whatever its create asks, so a rebuild into a fresh environment makes the spec's first Image column the primary image, whichever column carries the flag); the table's own image (`entityimage`) and the platform's companions of each column are not written, and a column of any other type the App Spec cannot express is left out *and named*. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.- Live regression on the edit path found + fixed **4 bugs**, then re-verified clean.- `verify-model-app.js` — read-only reconcile of spec vs deployed (exits non-zero on anything missing). Sitemap checks are **element-scoped**: an area/subarea icon is matched on its own `<Area>`/`<SubArea>` element, and a **dashboard subarea** is verified by resolving the dashboard id (systemform type 0 — by a downloaded spec's pinned `dashboardId` first, else by name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass — and that entry must carry the dashboard launcher `Url`, without which the app shows a placeholder icon for it. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).diff --git a/plugins/model-apps/hooks/run-skill-posttool-validation.js b/plugins/model-apps/hooks/run-skill-posttool-validation.jsindex 9dcd4487a..9572b9a5c 100644--- a/plugins/model-apps/hooks/run-skill-posttool-validation.js+++ b/plugins/model-apps/hooks/run-skill-posttool-validation.js@@ -23,6 +23,7 @@ const {getValidatorScript,readUtf8Stream,} = require('../scripts/lib/modelapps-hook-utils');+const { makeWritesBlocking } = require('../scripts/lib/output-redaction.js');const DEBUG = process.env.DEBUG === '1' || process.env.DEBUG === 'true';@@ -75,10 +76,12 @@ readUtf8Stream(process.stdin).then((inputData) => {process.exitCode = result.status ?? 0;} catch (err) {// Never block on a hook-side bug — the skill already ran.+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`[model-apps hook] Unexpected error: ${err.message}\n`);process.exit(0);}}).catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`[model-apps hook] Unexpected error: ${err.message}\n`);process.exit(0);});diff --git a/plugins/model-apps/hooks/validate-icon-imports.js b/plugins/model-apps/hooks/validate-icon-imports.jsindex 85062ab7b..8a94b3c10 100644--- a/plugins/model-apps/hooks/validate-icon-imports.js+++ b/plugins/model-apps/hooks/validate-icon-imports.js@@ -44,6 +44,7 @@ if (process.env.MODEL_APPS_DISABLE_HOOKS === '1' || process.env.MODEL_APPS_DISAB}const { readUtf8Stream } = require('../scripts/lib/utf8-stream.js');+const { makeWritesBlocking } = require('../scripts/lib/output-redaction.js');function isWriteTool(toolName) {return toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit';@@ -316,6 +317,7 @@ readUtf8Stream(process.stdin).then((inputData) => {const relPath = path.relative(cwd, absPath) || absPath;const unsupported = extractUnsupportedIconImports(content);if (unsupported.length > 0) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(buildUnsupportedImportMessage(relPath, unsupported) + '\n');process.exit(2);}@@ -336,6 +338,7 @@ readUtf8Stream(process.stdin).then((inputData) => {}if (invalid.length === 0) process.exit(0);+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(buildBlockMessage(relPath, invalid) + '\n');process.exit(2);}).catch(() => {diff --git a/plugins/model-apps/hooks/validate-write-safety.js b/plugins/model-apps/hooks/validate-write-safety.jsindex 5fe937578..64b4676d9 100644--- a/plugins/model-apps/hooks/validate-write-safety.js+++ b/plugins/model-apps/hooks/validate-write-safety.js@@ -47,6 +47,7 @@ if (process.env.MODEL_APPS_DISABLE_HOOKS === '1' || process.env.MODEL_APPS_DISAB}const { readUtf8Stream } = require('../scripts/lib/utf8-stream.js');+const { makeWritesBlocking } = require('../scripts/lib/output-redaction.js');function debug(msg) {if (DEBUG) process.stderr.write(`[write-safety] ${msg}\n`);@@ -55,6 +56,7 @@ function debug(msg) {// Non-blocking warning. Exit 1 (not 2) so Claude Code shows this on stderr to the// USER and still lets the write through — the guard flags, it does not block.function warn(userMsg) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`[model-apps] ${userMsg}\n`);process.exit(1);}@@ -144,6 +146,7 @@ readUtf8Stream(process.stdin).then((inputData) => {try {input = JSON.parse(inputData);} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);debug(`stdin parse failed: ${err.message}`);process.exit(0); // never block on hook-side bugs}@@ -174,9 +177,11 @@ readUtf8Stream(process.stdin).then((inputData) => {}}+ makeWritesBlocking(process.stdout, process.stderr);debug(`OK ${toolName} ${extractWritePaths(toolName, toolInput).join(',')}`);process.exit(0);}).catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);debug(`stdin read failed: ${err.message}`);process.exit(0);});diff --git a/plugins/model-apps/references/agent-interaction-contract.md b/plugins/model-apps/references/agent-interaction-contract.mdindex bcf9143e2..cf519ff9f 100644--- a/plugins/model-apps/references/agent-interaction-contract.md+++ b/plugins/model-apps/references/agent-interaction-contract.md@@ -92,9 +92,27 @@ tools:`scripts/validate-agent-interactivity.js` fails the build on a one-sideddeclaration, in either direction.+## A declared tool is not always a delivered one++Declaring a capability in both schemes makes a host *recognize* it. It does not make+the host *hand it to a subagent*. Task tracking is the live example. The `todo` alias+is documented as supported in VS Code and not in the cloud agent; a Copilot CLI+session gave `genpage-page-builder` only `view`, `create`, `edit` and `grep` although+its frontmatter declares `TaskCreate`, `TaskUpdate` and `todo`; and Claude Code+provides `TaskCreate`, `TaskUpdate` and `TaskList` by default only on some models.+Nothing an agent declares can change that.++So an agent never *depends* on a task tool. A step that uses one says to check the+toolset first, and says what to do with none: skip the tool, do not search for one,+do not call a tool that was not given, never say a task was created, and keep the+progress in its own words. `agents/genpage-page-builder.md` Step 4 and Step 7 are the+reference wording; `scripts/tests/agent-task-tracking.test.js` fails an agent that+tells its reader to use `TaskCreate` without it.+References:[Copilot tool aliases](https://docs.github.com/en/copilot/reference/custom-agents-configuration#tool-aliases)· [Claude Code ignores unknown tool names](https://github.com/anthropics/claude-code/issues/93171)+· [Claude Code tools reference](https://code.claude.com/docs/en/tools-reference)## Logging is unchangeddiff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex e5aa33234..ea20539d4 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -256,12 +256,21 @@ works through.{ "name": "Operations", "description": "Daily queue health for the support lead.", "tiles": [{ "type": "chart", "chart": "Orders by Status", "view": "Active Orders" }, // chart needs both{ "type": "list", "view": "Active Orders", "name": "Recent" }, // list needs a view- { "type": "iframe", "url": "https://…", "name": "Map" },+ { "type": "iframe", "url": "https://…", "name": "Map", "colspan": 2, "rowspan": 8 }, // optional size{ "type": "webresource", "webResource": "new_widget.html", "name": "Widget" } ] }```- A **chart** tile needs both a declared `chart` (the visualization) **and** a declared `view` (itsdata); a **list** tile needs a declared `view`. The target entity is derived from the view. `name`- defaults to the chart/view name; `colspan`/`rowspan` optional (default 1×4).+ defaults to the chart/view name.+- **Size (`colspan`/`rowspan`, optional): 1 column by 12 rows unless set.** A tile's height is its+ `rowspan`, and the app draws a one-row tile as its title bar alone — no chart, no list — so give a+ tile `rowspan: 1` only when it should be that thin. The grid is two columns wide and fills in tile+ order, left to right: two `colspan: 1` tiles share a row, `colspan: 2` takes the full width (a list+ with several columns), a tile too wide for what is left of a row starts the next one, and a+ `colspan` above 2 is narrowed to 2. The platform's own dashboards give charts and lists 9 to 24+ rows, most often 12, which is why 12 is the default. A rebuild reuses a dashboard that exists and+ never resizes its tiles, so one an earlier version built keeps its one-row tiles until it is+ created again under a new `name` or its tiles are resized in the dashboard designer.- **View and chart names are unique only per table.** When the tile's view name is declared on morethan one table, set the tile's `entity` to say which; the chart must be declared on that **same**table. Both are rejected at the spec gate otherwise — a same-named chart on another table would@@ -314,7 +323,11 @@ works through.Adds privileges for a table to a security role that **already exists** — typically the roles anexisting solution ships. Use it when you add a table to an app whose access model somebody else owns:without it the table, its forms and its navigation deploy while every non-admin persona still cannot-open the table, and nothing reports it.+open the table, and nothing reports it. (Lint now does: a new table that no persona job and no+`roleGrants[]` entry grants a privilege on is a "no access declared" warning, and a grant that covers it+satisfies the check.) A grant is about **tables**: it does not associate the role with the app, and a+spec with no `personas[]` leaves the roles an existing app has as they are — `write-app-spec-doc.js+--env` lists them.```jsonc"roleGrants": [diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex b897bf16c..2b6c70519 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -84,13 +84,12 @@ sample data (incl. multi-parent junction links + status reasons), and publish.is put back to the spec's. Two cases leave the text as it is, and **warn that it was not applied** while the rest ofthe build goes ahead: an app that was **never published** (Dataverse takes no write to its name or description untilit is — publish it in Power Apps and re-run), and a name or description that is **localized** (held as one text per- language), which a rebuild never replaces with one text: change it in Power Apps. The SDK writes the name and the- description in one request, so while either is localized (or is any other value that is not plain text) the app's- header is **not edited at all**: a changed plain text beside it, and an `app.aiDescription`, are reported as not- applied too, with the reason — a warning, never a halt; the navigation is written as ever. (The SDK has no partial- header write, so the one plain field that changed cannot be sent alone; that would need a new SDK operation.) And if the- SDK's own read of the header fails while a text is not plain, the build stops with `APP_HEADER_NOT_PLAIN_TEXT` before- anything is sent or written — the SDK writes the header it holds when that read fails — and a re-run normally succeeds.+ language, or any other value that is not plain text), which a rebuild never replaces with one text: change it in+ Power Apps. Only that one text is held back: the SDK writes just the texts that changed, so the other text, and an+ `app.aiDescription`, are applied as usual — a localized name beside a changed plain description writes the+ description alone and leaves every translation of the name as it is. A text that is not plain is never sent, even+ when the SDK's own read of the header fails (the build takes it off the copy it pushes); the HTTP client still+ refuses a write of one, with `APP_HEADER_NOT_PLAIN_TEXT`, for a push the build did not make itself.- **`app.newLook`** *(optional, default off)* — opt into the **modern ("new look") shell** for this app.Writes the per-app `NewLookAlwaysOn` setting, which Dataverse describes as enabling the new look and**hiding the user switch** — so the result is deterministic rather than a per-user preference. It is@@ -199,9 +198,8 @@ sample data (incl. multi-parent junction links + status reasons), and publish.those texts saved in Maker and not yet published is kept: the build's push is saved with it. If the appchanges while the build runs, the push is refused as a concurrent edit (`version-conflict`): downloadthe app again and rebuild, which never overwrites the other edit.- While the app's name or description is **localized** (or otherwise not plain text) this is **not applied**- and the build warns — it is written in the same request as those two texts, which a rebuild never sends- in that state; it does not halt.+ While the app's name or description is **localized** (or otherwise not plain text) that text is left as it is, and+ this is still **applied**: the SDK writes only what changed, so the routing description is written alone.**Rules:** a non-empty string of at most 1,048,576 characters, the column's maximum.- **`languageCode`** *(optional)* — the [LCID](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/)stamped on the Dataverse labels the build creates: data-model labels (table, column, choice, status@@ -216,14 +214,15 @@ sample data (incl. multi-parent junction links + status reasons), and publish.flag, and a build run with it needs it there**: the build writes a form's tab and section captions in thatlanguage, and `--verify` holds them to the language it is told (the flag, else this field, else theorganization's base language) — so without the flag, or this field pinned in the spec, such a form is held to- the organization's language and its captions cannot be confirmed: they are reported missing, or listed as- unverified when the form's read carries no label in that language (below). (The build's own `--verify` is told+ the organization's language and its captions cannot be confirmed: they are reported missing, or, when the form's+ read carries no label in that language, looked up in a translation export (below). (The build's own `--verify` is toldthe language the build used.)When no language can be established at all — the organization cannot be read — those captions are listed- as **unverified**, neither passed nor failed. So are the captions compared in a language the environment's form- read does not carry: the platform decides which languages' labels the FormXML it returns carries (a form built- with Spanish captions in an English-language organization reads back with its labels in English only), and a- language no label of the form is in cannot be read back, whatever the form stores.+ as **unverified**, neither passed nor failed. A caption compared in a language the environment's form+ read does not carry is read from a **translation export** of the app's solution instead: the platform decides which+ languages' labels the FormXML it returns carries (a form built with Spanish captions in an English-language organization+ reads back with its labels in English only), and the export is the one read that carries them all. It is one request,+ made only when such a caption is there to check; the captions it cannot settle stay **unverified**.If the organization has **not** provisioned the LCID you pin, the build stops at the start of thedata-model phase and lists the ones it does have — Dataverse would otherwise accept the table andChoice labels (silently storing them under the org's base language) and then reject the first@@ -313,7 +312,9 @@ languages resolves to the same artifact. One option, one value, several names.**Round-trip.** `download-model-app` reconstructs localized labels from Dataverse: a table, plural,column or option labelled in several languages comes back as a map, and one labelled in a singlelanguage comes back as a plain string (so no existing spec changes shape). The download emits-`pluralName` alongside a localized `displayName`, so its own output re-validates.+`pluralName` alongside a localized `displayName`, so its own output re-validates, and beside a plain one+whenever it is not the `"<displayName>s"` a rebuild would derive — `"Tag Catalog"` for `"Tag"` comes back,+`"Tags"` does not (it is the default).A navigation `label` or `title` is always a plain string (the spec has no map form for one), read in thelanguage a rebuild writes it in: `--language-code`, else the `languageCode` the spec already on disk pins,else the environment's base language. When none of the three gives one — the base language could not be@@ -556,23 +557,40 @@ spec with its last snapshot, not with the deployed row, so it does not notice).length the spec asks for (or cannot be read). A build that stops because the table was created but cannotbe read back yet (`TABLE_METADATA_NOT_VISIBLE`) warns that the length may not have been applied, since are-run leaves an existing table's name column alone.-- **A key over the name column — give the column a `maxLength`.** A key may hold at most 900 bytes (2 for- each character of text), and some environments make a new name column 850 characters long whatever length- the table's create asks for, so Dataverse refuses a key over it. When the spec gives the name column a- `maxLength` and a table's `alternateKeys[]` entry holds that column, the build makes the key after it has+- **A key over the name column — give the column a `maxLength`.** A key may hold only so many bytes (2 for+ each character of text) and Dataverse refuses one that is too large: Microsoft Learn documents 900 bytes, and the+ platform's own answer on the environment this was measured on named 1,700. Some environments make a new name+ column 850 characters long whatever length the table's create asks for — 1,700 bytes by itself, so a key over that+ column alone is accepted there, and a key that holds any other column beside it is refused. When the spec gives the+ name column a `maxLength` and a table's `alternateKeys[]` entry holds that column, the build makes the key after it hasset the length — so the first build succeeds — and does not send it when the length could not be set: it stops- with a message that says why and what to do instead of the platform's refusal. Keep the key within 900 bytes- (at most 450 characters when the name column is its only column). Without a `maxLength` the build leaves the+ with a message that says why and what to do instead of the platform's refusal. Keep the key within 900 bytes to be+ safe on every environment (at most 450 characters when the name column is its only column). Without a `maxLength` the build leaves thecolumn as the environment made it and makes the key with its table, so on such an environment the key isrefused: give one. This holds for a key whose `displayName` goes out in one language: a string, or a languagemap that names exactly one language, whichever it is — the SDK sends either as one label, the same request, andwhere the key is made does not depend on the language the build writes in. A key labelled in several languages(`{ "1033": "…", "3082": "…" }`) is made **before** the length is set,because the update that sets the length reads the column with its labels, and Dataverse keeps only the base- language of a create that comes straight after such a read. So where the platform refuses such a key for the- length of its column, the first build stops there; the build then **warns**, naming the key and what to do: run it- again (the length is set as the build stops, so the key is made then), or label the key in one language so that it- is made after the length. Nothing is said where the environment keeps the length asked and the key is made.+ language of a create that comes straight after such a read. The exception is a key that holds the name column **and+ another column** where the environment made the name column too long for it (the key then cannot fit beside the+ column, and shortening the column is what lets it): the build reads the column's length once, before it asks for such+ a key, and makes the key after the length is set — with both labels, so the first build succeeds. A key labelled in several+ languages over the name column alone is made before the length is set whatever the column's length. Where the platform refuses a key made before+ the length is set for its size all the same, the first build stops there, and the build **warns**, naming the key. What the+ warning says depends on what the build can tell of the key's size. It counts the key's columns as it creates them, 2 bytes+ for each character of text — a `Text` column at its `maxLength` (100 without one), an `AutoNumber` column at 100 (the build+ gives it no other length) — and any other column at one byte, so the count is a minimum. When even that minimum is over+ 1,700 bytes at the length you give the name column, the key is **proven** too large: the warning says so, with its size, and+ that running the build again does not create it — take a column out of the key, or make its text columns shorter. Otherwise+ the count is **inconclusive** (a column that is not text can take more than one byte, and an environment may allow less than+ 1,700), so the warning promises nothing: running the build again may create the key, since the length is set as the build+ stops, if the name column at the length you give leaves room for it; if that run is refused the same way, compare Dataverse's+ error with the sizes of the key's columns. Labelling the key in one language changes where it is made, not its size. The+ stop for a key that waited for a length the build could not set says the same of the key: proven too large, no run creates+ it as the spec has it; otherwise, once the name column has the length you give (set it in Maker, or clear what stopped the+ build), running the build again may create the key, which the build does not promise. Nothing+ is said where the environment keeps the length asked and the key is made.### `visualization` — custom grid rendering (optional, PREVIEW)@@ -721,6 +739,10 @@ run the lint, so an unlinted spec hits the failure at build time instead).```- A **plain N:N** (no extra fields on the link) — use `ManyToMany`. A form sub-grid can sit on*either* side (the builder resolves the N:N relationship name automatically).+- `intersectEntityName` (optional) names the table that holds the links. Leave it out and the build names it+ after the relationship (its schema name, lower-cased). A build and `verify-model-app.js` hold the relationship+ to the name you give it: an N:N that already uses the schema name on another intersect table is refused by the+ build and fails verify. With no `intersectEntityName` the relationship is reused whichever intersect table it has.- **N:N that needs attributes on the link** (e.g. a role/date per assignment) — model a**junction entity** with two `OneToMany` relationships into it, and put the payload columns onthe junction. Sample rows then bind **both** parents via `$parents` (see sampleData). This is the@@ -1294,12 +1316,16 @@ The same goes for a language the environment's form read does not carry: the plainto the FormXML it returns, and it can return fewer than the form stores (measured: a form built and published with Spanish(`3082`) captions in an English-language (`1033`) organization keeps both languages, yet its published FormXML carries every label in`1033` alone). When no label of the form — on any element — is in the language a label is compared in, while the read carries labels-in other languages, the labels compared in it-are reported **unverified** (what the read does carry, and what to do: check them in Power Apps with that language), a label map-`{ "1033": …, "3082": … }` is compared at the languages the read carries and the others are listed the same way, and `ok` and the exit-status are those of everything that could be compared. A language the read does carry is compared strictly: a stale caption in it-fails. A form whose read carries no label at all names no language that could be missing from the read: the captions the spec-declares for it are missing, and fail. Translations are not read another way (a translation export, `RetrieveLocLabels`).+in other languages, the labels compared in it are read from **one translation export of the app's solution** — the one read that+carries every provisioned language — by the `id` the tab or section has in the FormXML: the caption the spec declares passes, another+text or an empty cell is a mismatch and fails, and a label map `{ "1033": …, "3082": … }` is compared language by language. What the+export cannot settle (it fails or cannot be read, the form gives the element no id, the export has no row for it or no column for the+language) is reported **unverified** with the reason (what to do: check those captions in Power Apps with that language), and `ok`+and the exit status are those of everything that could be compared. **Cost:** one request per verify, made only when there is such+a caption to check — measured at 7.5–11.2 s for a solution of one table, more as the solution grows (it exports every label of it) —+and it shows the published layer: a caption saved and not published is not in it. A language the read does carry is compared+strictly, from the read: a stale caption in it fails. A form whose read carries no label at all names no language that could be+missing from the read: the captions the spec declares for it are missing, and fail.A label the spec does not write is not compared. Auto forms also require readableFormXML for the identity check. Repeated bindings of one field with distinct IDs are allowed.It does **not** check field order or `after` adjacency.@@ -1876,8 +1902,17 @@ auto-selects tables that are good row-summary candidates and skips those that ar## personas[] (optional — security roles)Authors one **security role per persona**, sized to the entity access that persona's-**jobs-to-be-done** need. Without at least one role the generated app runs only for system-administrators; `personas[]` produces a working access model so the app opens for real users.+**jobs-to-be-done** need, and associates the app with it. A **new** app is associated with the System+Administrator role only, so without a persona role users who have no maker-level role cannot open it;+`personas[]` produces a working access model so the app opens for real users.++An app that **already exists** keeps the roles associated with it: a spec with no `personas[]` leaves+them as they are, which is how an extension of such an app is written (a download carries none). Do+not list an existing role as a persona to silence the lint — a persona's role is converged to exactly+the privileges declared, and a role the build did not author is refused. Give an existing role access+to a table the spec adds with `roleGrants[]` (below). Opening the app and using a table are two+questions: lint and `write-app-spec-doc.js` keep them apart, and flag a new table that no persona job+and no `roleGrants[]` entry grants a privilege on ("no access declared").`personas[]` is captured **first** during authoring (Level (a0), before the data model): the jobsare what the app exists to do, so they drive which tables and surfaces exist. `privileges[]` isdiff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.mdindex b1574b511..f1a9751e9 100644--- a/plugins/model-apps/references/authoring-flow.md+++ b/plugins/model-apps/references/authoring-flow.md@@ -701,6 +701,14 @@ The builder authors **one role per persona**, unioning every job's declared acceper entity+access), and grants the app to that role so it **opens for that persona, not just forsystem administrators** (`appAccess: false` opts a role out).+**Extending an app that already has roles** (a downloaded spec): leave `personas[]` out. The roles+associated with an existing app are not changed by a spec that authors none, and a persona's role is+converged to exactly the privileges declared (so naming an existing role there is the opposite of+leaving it alone). Give an existing role access to a new table with a `roleGrants[]` entry instead —+it adds privileges and removes none (see [`app-spec-schema-advanced.md`](./app-spec-schema-advanced.md)+→ `roleGrants[]`). The lint's "no access declared" warning names each new table that no persona job+and no grant covers.+**Render the proposed roles and their per-entity access as a table in your chat reply**, thenconfirm with `AskUserQuestion` — the user cannot approve an access model they cannot see, andtool output is collapsed and invisible to them.diff --git a/plugins/model-apps/scripts/_vendor-build/build-typescript.js b/plugins/model-apps/scripts/_vendor-build/build-typescript.jsindex 141eb95aa..948dd26c1 100644--- a/plugins/model-apps/scripts/_vendor-build/build-typescript.js+++ b/plugins/model-apps/scripts/_vendor-build/build-typescript.js@@ -25,6 +25,7 @@ const fs = require('node:fs');const zlib = require('node:zlib');const vm = require('node:vm');const crypto = require('node:crypto');+const { makeWritesBlocking } = require('../lib/output-redaction.js');// [email protected], as the npm registry publishes it (`npm view [email protected] dist`): the tarball's sha1 and sha512,// and the SHA-256 of the one file vendored from it. Bump all three together, deliberately.@@ -74,6 +75,7 @@ function readTar(buffer) {const tgz = fs.readFileSync(tarball);const integrity = `sha512-${sha('sha512', tgz, 'base64')}`;if (integrity !== PINNED.tarballIntegrity || sha('sha1', tgz) !== PINNED.tarballSha1) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`Refusing ${tarball}: it is not the pinned typescript@${PINNED.version} tarball (integrity ${integrity}).`);process.exit(1);}diff --git a/plugins/model-apps/scripts/_vendor-build/build.js b/plugins/model-apps/scripts/_vendor-build/build.jsindex 6911ca267..3bab9c58f 100644--- a/plugins/model-apps/scripts/_vendor-build/build.js+++ b/plugins/model-apps/scripts/_vendor-build/build.js@@ -19,6 +19,7 @@* {sdk-surface-contract,hardening2-real-bundle,vendor-sdk-smoke}.test.js) against the new bundle. */const path = require('node:path');const fs = require('node:fs');+const { makeWritesBlocking } = require('../lib/output-redaction.js');const argSdk = (() => {const i = process.argv.indexOf('--sdk');@@ -46,10 +47,12 @@ const PROVENANCE = path.resolve(__dirname, '../vendor/PROVENANCE.json');const esbuild = require('esbuild');if (!fs.existsSync(SDK_ENTRY)) {+ makeWritesBlocking(process.stdout, process.stderr);console.error('SDK entry not found:', SDK_ENTRY);process.exit(2);}if (!fs.existsSync(SDK_NODE_ENTRY)) {+ makeWritesBlocking(process.stdout, process.stderr);console.error('SDK /node adapter entry not found:', SDK_NODE_ENTRY);console.error('The SDK requires an injected workspaceStorage; the plugin builds one from this.');process.exit(2);@@ -129,6 +132,7 @@ function sdkProvenance(root) {const prov = sdkProvenance(argSdk);if (prov.libIsStale) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`REFUSING: ${SDK_ENTRY} is OLDER than the newest .ts under packages/cds-maker-sdk/src`);console.error(` lib built : ${prov.libBuiltAt}`);console.error(` newest src : ${prov.newestSrcAt}`);diff --git a/plugins/model-apps/scripts/add-page-to-solution.js b/plugins/model-apps/scripts/add-page-to-solution.jsindex 55133e7e1..41536ad9e 100644--- a/plugins/model-apps/scripts/add-page-to-solution.js+++ b/plugins/model-apps/scripts/add-page-to-solution.js@@ -30,6 +30,7 @@ const {} = require('./lib/dataverse-auth');const { odataLit } = require('./lib/odata');const { FORM_GUID_RE } = require('./lib/app-spec');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const APPMODULE_COMPONENT_TYPE = 80;const UXAGENTPROJECT_LOGICAL_NAME = 'uxagentproject';const CONNECTION_REFERENCE_LOGICAL_NAME = 'connectionreference';@@ -90,6 +91,7 @@ async function main() {needValue: ['page-ids', 'connection-refs'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/ai-preflight.js b/plugins/model-apps/scripts/ai-preflight.jsindex 7af31af87..0d106d1ea 100644--- a/plugins/model-apps/scripts/ai-preflight.js+++ b/plugins/model-apps/scripts/ai-preflight.js@@ -12,6 +12,7 @@ const { createAzHttpClient } = require('./lib/sdk-http-client.js');const { AI_APP_SETTING, AI_SETTING_CODEC, resolveAppModuleId, effectiveSettingValue, settingIsOn } = require('./lib/ai-app-settings.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');const fs = require('node:fs');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// Human-readable label + admin-action hint for each feature key returned by getAiReadiness.const FEATURE_META = {@@ -141,6 +142,7 @@ async function main() {const USAGE = 'Usage: node scripts/ai-preflight.js --env <orgUrl> [--app <uniqueName>]';const flagError = validateFlags(argv, { known: ['env', 'app'], needValue: ['env', 'app'] });if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -189,6 +191,8 @@ async function main() {const res = await effectiveSettingValue(read, appModuleId, setting);effective[key] = res.error ? { error: res.error } : { value: res.value, scope: res.scope, on: settingIsOn(res.value, key) };}+ // The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);if (appLookup.error) {process.stderr.write(`\nWarning: could not resolve app '${app}' (${appLookup.error}); reporting readiness gates only.\n`);}@@ -222,6 +226,7 @@ module.exports = { runPreflight, featureLine };if (require.main === module) {main().catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Error: ${err.message}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/apps.js b/plugins/model-apps/scripts/apps.jsindex b684e82dd..ce25ec97b 100644--- a/plugins/model-apps/scripts/apps.js+++ b/plugins/model-apps/scripts/apps.js@@ -152,6 +152,7 @@const { randomBytes, randomUUID } = require('node:crypto');const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');const { pushFailed } = require('./lib/entity-provision.js');const { collectionRows, currentLayerRow, savedPageRows } = require('./lib/app-components.js');@@ -672,6 +673,7 @@ async function writeApp(sdk, args, plan, sitemapId) {// --- the command line ------------------------------------------------------------------------------------------------------function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${message}\n${USAGE}\n`);process.exit(1);}@@ -732,6 +734,8 @@ async function main() {result = failure(err, command === 'create' ? { written: false } : {});}// The SDK's notes on the push, for a run that finished and for one that failed after it: the failed run is the one that most needs them.+ // The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);for (const warning of result.warnings || []) process.stderr.write(`⚠ ${warning}\n`);emitResult(result.ok, result, { ascii: true });}@@ -742,6 +746,7 @@ module.exports = { listApps, createApp, deriveUniqueName, pageIdArguments, COMMAif (require.main === module) {main().catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Error: ${err.message}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 79bbb92a8..cb8dbac6f 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -44,10 +44,12 @@ const { envTruthy } = require('./lib/interaction-mode.js');// `verify-model-app.js` pass. Reuses the read-only reconcile core + the SDK reader (DRY — same code the// standalone verifier runs). The sibling CLI is safe to require (it has a `require.main` guard).const { verifySpec } = require('./lib/verify-spec.js');+const { isTranslationExport } = require('./lib/translation-labels.js');const { readerFor, isolatedReaderFor } = require('./verify-model-app.js');const { makeGenpageSdk } = require('./lib/genpage-sdk.js');const { leftOnDiskWarning } = require('./lib/left-on-disk.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// The folder an app's workspace lives in, checked before anything is built on it. An APPLY makes the folder if it is// missing and re-checks it (mkdir on an existing junction succeeds, so the re-check is what refuses one). A DRY RUN@@ -76,13 +78,16 @@ function assertWorkspaceDir(workspaceDir, { create }) {// which environment it belongs to, and the answer comes back as `folderNote` so the// preview can warn that an --apply would stop. Construction is offline (no token// until first call).-async function makeSdk(env, spec, workspaceDir, languageCode, { persistent = true } = {}) {+async function makeSdk(env, spec, workspaceDir, languageCode, { persistent = true, throttle } = {}) {// A link at the workspace root would make the provision SDK's storage follow it. Refuse// before either constructor: the first SDK does not use this directory, but once the// directory has been refused the factory must not run at all.assertWorkspaceDir(workspaceDir, { create: persistent });const { createMakerSdk, createNodeWorkspaceStorage } = require('./lib/maker-sdk.js');- const httpClient = createAzHttpClient(env);+ // The one client of both SDK instances and of verify's isolated reader draws its waits for a throttled answer from the run's budget (`throttle`, made by main()).+ // The build's own `--verify` reads a form's captions in a language the form read does not carry from a translation export (verify-model-app.js readerFor), through this client:+ // that request is sent once whatever answers it (isTranslationExport), as in the standalone verify — a long action, which a re-send would run a second time.+ const httpClient = createAzHttpClient(env, { throttle, sendOnce: isTranslationExport });const sdkTempDir = makeTempWorkspace('model-app-');const cleanup = () => {fs.rmSync(sdkTempDir, { recursive: true, force: true });@@ -417,10 +422,11 @@ async function buildModelApp(spec, opts, deps) {const baseEmit = deps.emit || cliEmit(log, { apply: opts.apply, counts });const emit = journal ? (e) => { baseEmit(e); journal.record(e); } : baseEmit;const sleep = deps.sleep || ((ms) => new Promise((res) => setTimeout(res, ms)));- // One budget for the waiting the BUILD'S OWN retry layers add when a service throttles — the page backend's waits between the sends of a page write (a `$batch` the HTTP client never re-sends) and this loop's own waits before it runs- // a phase again — so the run can neither wait twenty silent minutes for one page nor forget, where one layer hands over to the other, what the service asked (lib/throttle-budget.js). It is NOT a bound on all the waiting a run does:- // the production HTTP client re-sends a throttled read, publish, delete or column create on a schedule of its own (at most five re-sends, honouring a `Retry-After` of up to a minute), exactly as it did before there was a budget, and- // that is not charged to it — a throttled build that succeeds today would otherwise halt. `now` is the clock the page backend stamps the moment before which nothing may be sent on (`retryNotBefore`): a test seam, with `sleep`.+ // One budget for all the waiting a run does when a service throttles — the HTTP client's waits before it sends a throttled read, publish, delete or column create again, the page backend's waits between the sends of a page write (a `$batch` the+ // client never re-sends) and this loop's own waits before it runs a phase again — so the run can neither wait twenty silent minutes for one page nor forget, where one layer hands over to the other, what the service asked (lib/throttle-budget.js).+ // main() makes it before the SDK and hands it to the client the SDK is made over, to the page backend (through the engine's `throttle`) and here (`deps.throttle`); a caller that gives none gets one of its own, which only the layers it is handed to+ // draw from. The waits that are not for a throttle — a 5xx, a reset connection, a deadlock victim — keep the clients' own schedules and are not drawn. `now` is the clock the page backend stamps the moment before which nothing may be sent on+ // (`retryNotBefore`): a test seam, with `sleep`.const throttle = deps.throttle || makeThrottleBudget({ warn: deps.warn });const now = deps.now || Date.now;let authorizedFormRemovals;@@ -648,8 +654,11 @@ async function buildModelApp(spec, opts, deps) {// no list (one thrown before the engine, or by a stand-in for it) leaves it as it was.let owedLengths = [];let r;+ // How many waits the HTTP client has been refused by the budget (lib/throttle-budget.js, `declined`): the count at the start of a run of the phases says whether one happened in it.+ const declinedCount = () => (typeof throttle.declined === 'function' ? throttle.declined().count : 0);for (let attempt = 1; ; attempt++) {counts.ok = counts.skip = counts.error = 0; // summary reflects the final (successful) attempt+ const declinedBefore = declinedCount();try {r = await runBuild(spec, {sdk: deps.sdk,@@ -690,18 +699,27 @@ async function buildModelApp(spec, opts, deps) {collectOwedPublishes(owedAcrossAttempts, err && err.owedPublishes);if (err && Array.isArray(err.owedLengths)) owedLengths = err.owedLengths;let halted = err;- if (attempt <= maxRetries && isTransientHalt(err, { spec })) {+ const transient = isTransientHalt(err, { spec });+ const ask = transient ? throttleAskOf(err) : null;+ // The words of the halt for a wait that does not fit: stop, and say what the service asked. The build is idempotent, so a later run goes on from here.+ const budgetHalt = (askedMs, waitMs) => new BuildHalt(`${err && err.phase ? `${err.phase} stopped` : 'the build stopped'}: ${waitDoesNotFit(throttle, { askedMs, waitMs })}`, {+ phase: err && err.phase, code: 'throttle-budget-exhausted', recoverable: true, cause: err, retry: retryPolicyFor(err), statusCode: 429,+ });+ // A throttle that stopped a request in THIS run of the phases: the HTTP client draws its waits from the budget too, and a wait that does not fit is not taken — the answer comes back as the 429 it is, which carries nothing of what the service+ // asked (the SDK's error holds no headers), and the client tells the budget instead (`declined`, lib/throttle-budget.js). The service said it was not ready for longer than the run may wait, so running the phases again would meet the+ // same answer: stop here, as for a wait of the build's own that does not fit — and so on the last run as on the first.+ const refused = transient && ask.throttled && declinedCount() > declinedBefore ? throttle.declined() : null;+ if (refused) {+ halted = budgetHalt(Math.max(ask.askedMs, refused.askedMs), refused.waitMs);+ } else if (attempt <= maxRetries && transient) {const backoff = opts.retryDelayMs != null ? opts.retryDelayMs : backoffMs(attempt);// What the service asked of the next send, carried across the layers (retry-policy.js, throttleAskOf): when the page backend's sends ran out it handed over the moment before which nothing may be// sent. The wait is what is LEFT of it — the layers between did work — in whole seconds, the unit `Retry-After` counts in, and never less than the build's own backoff.- const ask = throttleAskOf(err);const asked = ask.notBefore > 0 ? Math.ceil(Math.min(ask.askedMs || Infinity, Math.max(0, ask.notBefore - now())) / 1000) * 1000 : 0;const delay = Math.max(backoff, asked);if (ask.throttled && !throttle.fits(delay)) {- // The wait does not fit what is left of the run's budget: stop, and say what the service asked. The build is idempotent, so a later run goes on from here.- halted = new BuildHalt(`${err && err.phase ? `${err.phase} stopped` : 'the build stopped'}: ${waitDoesNotFit(throttle, { askedMs: ask.askedMs || asked, waitMs: delay })}`, {- phase: err && err.phase, code: 'throttle-budget-exhausted', recoverable: true, cause: err, retry: retryPolicyFor(err), statusCode: 429,- });+ // The wait does not fit what is left of the run's budget.+ halted = budgetHalt(ask.askedMs || asked, delay);} else {if (ask.throttled) throttle.spend(delay);if (journal) journal.record({ phase: err && err.phase, status: 'retry', label: `transient error (attempt ${attempt}/${maxRetries}) — retrying in ${delay}ms`, detail: String((err && err.message) || err) });@@ -1029,6 +1047,7 @@ async function main() {needValue: ['env', 'spec', 'stage', 'only', 'skip', 'from', 'to', 'language-code', 'languageCode', 'workspace'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -1151,7 +1170,10 @@ async function main() {// (offline), and apply needs it. A spec validation error short-circuits before any write.// Only an apply opens (and so binds) the app folder's workspace; a dry run works in a throwaway one and// hands back a note when the folder would stop an --apply.- const { sdk, provisionSdk, cleanup, isolatedReader, folderNote } = await makeSdk(env, spec, workspaceDir, authoringLanguageCode, { persistent: opts.apply });+ // The run's budget for waiting out a throttled service (lib/throttle-budget.js), made before anything that sends so that every layer draws from the one: the HTTP client the SDK is made over, the page backend (through the engine's+ // `throttle`) and the build's own retry loop (`deps.throttle`). A wait of more than a few seconds is announced on stderr — stdout carries the JSON result.+ const throttle = makeThrottleBudget({ warn: (m) => process.stderr.write(`⚠ ${m}\n`) });+ const { sdk, provisionSdk, cleanup, isolatedReader, folderNote } = await makeSdk(env, spec, workspaceDir, authoringLanguageCode, { persistent: opts.apply, throttle });if (folderNote) process.stderr.write(`⚠ ${folderNote}\n`);// Durable build journal (apply runs only): a per-run record of steps + where a run halted,// written to <workspace>/build-log.jsonl. Resume = re-run the same command (idempotent).@@ -1206,7 +1228,7 @@ async function main() {const deps = {log: (m) => process.stderr.write(m + '\n'),warn: (m) => process.stderr.write(`⚠ ${m}\n`),- sdk, provisionSdk, journal,+ sdk, provisionSdk, journal, throttle,// The role-privileges check must actually RUN here. verify-spec skips it unless BOTH// `rolePrivileges` and `entityPrivileges` readers are present, and `entityPrivileges` used to// need the raw client plus the org URL — omitting them degraded silently, so `--apply --verify`@@ -1216,7 +1238,7 @@ async function main() {verify: async (s, verifyOpts) => {// The page reads go through a backend of their own, in a throwaway workspace — not the app folder's `.maker-workspace`, which// would be left holding a copy of every page read — removed as soon as this verify ends.- const genpage = makeGenpageSdk(env);+ const genpage = makeGenpageSdk(env, { throttle });try {return await verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpage, workspaceDir, isolatedReader }), verifyOpts);} finally {diff --git a/plugins/model-apps/scripts/capture-fixture.js b/plugins/model-apps/scripts/capture-fixture.jsindex 9c39c678f..c13c66f94 100644--- a/plugins/model-apps/scripts/capture-fixture.js+++ b/plugins/model-apps/scripts/capture-fixture.js@@ -31,6 +31,7 @@const fs = require('node:fs');const path = require('node:path');const { spawnSync } = require('node:child_process');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');const FIXTURES_DIR = path.join(@@ -253,17 +254,20 @@ function main() {try {args = parseArgs(process.argv.slice(2));} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: ${err.message}`);process.exit(1);}const workingDir = path.resolve(args.workingDir);if (!fs.existsSync(workingDir) || !fs.statSync(workingDir).isDirectory()) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: working directory does not exist or is not a directory: ${workingDir}`);process.exit(2);}if (!evalExists(args.eval)) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: no eval with id ${args.eval} in evals.json`);process.exit(1);}@@ -273,6 +277,7 @@ function main() {if (fs.existsSync(fixtureDir)) {if (!args.force) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: fixture already exists: ${fixtureDir}\n` +` pass --force to overwrite, or pick a different --slug`,@@ -285,6 +290,7 @@ function main() {const { copied, skipped } = copyAllowedFiles(workingDir, fixtureDir);if (copied.length === 0) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: no allowlisted files found in ${workingDir}\n` +` expected at least one of: *.tsx, *.md, RuntimeTypes.ts`,diff --git a/plugins/model-apps/scripts/check-auth.js b/plugins/model-apps/scripts/check-auth.jsindex 385a18a47..47675bbcb 100644--- a/plugins/model-apps/scripts/check-auth.js+++ b/plugins/model-apps/scripts/check-auth.js@@ -42,6 +42,7 @@const { execFileAsync } = require('./lib/process-runner.js');const { dataverseRequest, getAuthTokenAsync, parseArgs, validateFlags, tokenFailureKind, tokenFailureMessage } = require('./lib/dataverse-auth');const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./lib/cli-failure.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// `pac org who` cold-starts the PAC CLI's .NET runtime (~7 s measured on Windows), and longer on a busy// machine; a probe that runs out of time is reported as that, never as "not logged in".@@ -107,7 +108,11 @@ function runQuietAsync(cmd, args, timeoutMs) {};}+// The result is a fixed shape whose strings are not bounded: a refused WhoAmI's whole diagnostic is its `message`, and a+// mistyped flag is quoted in a usage blocker. The process exits right after this one write, so the write is made blocking+// first (lib/output-redaction.js makeWritesBlocking): on Linux and macOS a pipe would otherwise take only what fits at once.function emit(payload) {+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify(payload) + '\n');process.exit(0);}diff --git a/plugins/model-apps/scripts/check-page-files.js b/plugins/model-apps/scripts/check-page-files.jsindex d84249c43..d70b4c00a 100644--- a/plugins/model-apps/scripts/check-page-files.js+++ b/plugins/model-apps/scripts/check-page-files.js@@ -19,6 +19,7 @@const fs = require('node:fs');const path = require('node:path');const { pageFileProblems, pagesTables } = require('./lib/page-file-targets.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');function checkPageFiles({ planPath, workingDir }) {if (!planPath) return { exit: 1, result: { ok: false, error: '--plan is required' } };@@ -57,6 +58,9 @@ function parseArgv(argv) {if (require.main === module) {const { exit, result } = checkPageFiles(parseArgv(process.argv.slice(2)));+ // The result lists every file and problem of the plan, and the process exits right after it: the write is+ // made blocking first, or a pipe on Linux and macOS takes only what fits at once (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify(result) + '\n');process.exit(exit);}diff --git a/plugins/model-apps/scripts/connector.js b/plugins/model-apps/scripts/connector.jsindex ce12a9929..0447f599d 100644--- a/plugins/model-apps/scripts/connector.js+++ b/plugins/model-apps/scripts/connector.js@@ -45,6 +45,7 @@const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');const { sdkFirst, connectivity } = require('./lib/sdk-first.js');const { runPac, pacPayload } = require('./lib/pac-fallback.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = ['Usage:',@@ -197,6 +198,7 @@ function describeFailure(error) {async function main() {const { request, error } = readRequest(process.argv.slice(2));if (error) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${error}\n${USAGE}\n`);process.exit(1);}@@ -226,6 +228,7 @@ module.exports = { readRequest, pacArgs, answer, answerLine, describeFailure, coif (require.main === module) {main().catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Error: ${err.message}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/create-connection-reference.js b/plugins/model-apps/scripts/create-connection-reference.jsindex 3688bf700..70e4b18ae 100644--- a/plugins/model-apps/scripts/create-connection-reference.js+++ b/plugins/model-apps/scripts/create-connection-reference.js@@ -24,6 +24,7 @@ const {validateFlags,emitResult,} = require('./lib/dataverse-auth');+const { makeWritesBlocking } = require('./lib/output-redaction.js');async function main() {const argv = process.argv.slice(2);@@ -34,6 +35,7 @@ async function main() {needValue: ['connection-id', 'display-name'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/dataverse-request.js b/plugins/model-apps/scripts/dataverse-request.jsindex 6b9018b9e..2c5990a78 100644--- a/plugins/model-apps/scripts/dataverse-request.js+++ b/plugins/model-apps/scripts/dataverse-request.js@@ -28,6 +28,7 @@// 1 - Fatal error (no token, invalid args, network failure after retries)const { dataverseRequest, parseArgs, validateFlags, readJsonArg } = require('./lib/dataverse-auth');+const { makeWritesBlocking } = require('./lib/output-redaction.js');async function main() {const argv = process.argv.slice(2);@@ -40,6 +41,7 @@ async function main() {hints: { timeout: 'a positive millisecond value (for example, --timeout 60000)' },});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -57,6 +59,7 @@ async function main() {if (flags.timeout !== undefined) {const parsed = Number(flags.timeout);if (!Number.isFinite(parsed) || parsed <= 0) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`--timeout must be a positive number (got "${flags.timeout}")\n`);process.exit(1);}@@ -65,9 +68,13 @@ async function main() {try {const res = await dataverseRequest(envUrl, method, apiPath, body, { includeHeaders, timeout });+ // An answer can be megabytes, and the process exits right after printing it: blocking writes put the whole text in the pipe+ // first (on Linux and macOS a pipe's writes are queued, and process.exit does not wait for them — lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify(res) + '\n');process.exit(0);} catch (e) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(e.message + '\n');process.exit(1);}diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 6ef0d04bf..af634b463 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -34,15 +34,16 @@ const { parseManifestBase64, manifestResourceName, reconcilePageIds, KEY_GRAMMARconst { reverseResolveNavIdsReport } = require('./lib/pageref-resolver.js');const { fetchSitemap, sitemapGenPages, appNavigationMatchesSitemap } = require('./lib/sitemap-pages.js');const { isRestrictedSolution } = require('./lib/system-solutions.js');-const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey, PAGE_MODEL_RE, sitemapEntityTables, lookupLabelFor, isOldLookupColumnLabel } = require('./lib/app-spec.js');+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, derivedPluralName, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey, PAGE_MODEL_RE, sitemapEntityTables, lookupLabelFor, isOldLookupColumnLabel } = require('./lib/app-spec.js');const { labelsByLcid, sameLabel } = require('./lib/lookup-labels.js');const { odataGuid } = require('./lib/ai-app-settings.js');const { APP_COMPONENT_ENTITY_SOURCES, appComponentEntities, appComponentRows, currentAppLayer, readAppComponentInventory, downloadAppMainForms, setAppMembershipFloor } = require('./lib/app-components.js');-const { mapLimit } = require('./lib/entity-provision.js');+const { mapLimit, DEFAULT_MAX_SIZE_KB } = require('./lib/entity-provision.js');const { compareText } = require('./lib/compare-text.js');const { hostsCustomControl } = require('./lib/dashboard-tiles.js');const { appUniqueName } = require('./lib/sdk-build.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// webresourcetype (int) -> app-spec web-resource type.const WR_TYPE = { 1: 'html', 2: 'css', 3: 'js', 4: 'xml', 5: 'png', 6: 'jpg', 7: 'gif', 8: 'xap', 9: 'xsl', 10: 'ico', 11: 'svg', 12: 'resx' };@@ -1270,6 +1271,102 @@ function choiceTypeFromTypeName(a) {return name ? SPEC_TYPE_FROM_ATTRIBUTE_TYPE_NAME[name] : undefined;}+// File and Image columns. Like a MultiSelectPicklist, both report `AttributeType: "Virtual"` — the vendored SDK creates them as+// { "@odata.type": "Microsoft.Dynamics.CRM.FileAttributeMetadata", "AttributeType": "Virtual", "AttributeTypeName": { "Value": "FileType" }, "MaxSizeInKB": 1024 }+// { "@odata.type": "Microsoft.Dynamics.CRM.ImageAttributeMetadata", "AttributeType": "Virtual", "AttributeTypeName": { "Value": "ImageType" }, "IsPrimaryImage": false, "MaxSizeInKB": 10240 }+// — so the `File` / `Image` keys of SPEC_TYPE_FROM_ATTRIBUTE_TYPE were never hit, and every download left both out without a+// word: a downloaded-then-rebuilt app lost them. The type NAME is what identifies them (Microsoft Learn finds image columns the same+// way: AttributeTypeName equals ImageType), and it is what tells them from the platform's virtual companions of other columns,+// which are `VirtualType` and name the column they belong to:+// { "LogicalName": "contoso_priorityname", "AttributeType": "Virtual", "AttributeTypeName": { "Value": "VirtualType" }, "AttributeOf": "contoso_priority" }+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-attributes#retrieve-image-column-definitions+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/file-attributes+const SPEC_TYPE_FROM_MEDIA_TYPE_NAME = { FileType: 'File', ImageType: 'Image' };++// An attribute's type NAME, from either place a download has it: the attribute read readEntityWithDescriptions merges in+// (`AttributeTypeName: { "Value": "FileType" }`), else the SDK's own projection of the table (`attributeTypeName: "FileType"`, ''+// when the platform sent none). The second keeps a File or Image column identifiable when the first read failed, which would+// otherwise drop both again.+function attributeTypeNameOf(a) {+ const merged = a && a.AttributeTypeName && a.AttributeTypeName.Value;+ if (typeof merged === 'string' && merged) return merged;+ return a && typeof a.attributeTypeName === 'string' && a.attributeTypeName ? a.attributeTypeName : undefined;+}++// 'File' or 'Image' for a column of one of the two types, else undefined. `Object.hasOwn`, because the name is the platform's+// text and must never resolve to something the map inherits.+function mediaTypeFromTypeName(a) {+ const name = attributeTypeNameOf(a);+ return name && Object.hasOwn(SPEC_TYPE_FROM_MEDIA_TYPE_NAME, name) ? SPEC_TYPE_FROM_MEDIA_TYPE_NAME[name] : undefined;+}++// What a maker did not author and a build never creates, left out by NAME as a system column is:+// - the table's own primary image, `entityimage` — the platform's, made with the table's image option, not an Image column a+// maker added — with its companions (the `*id`, `*_timestamp` and `*_url` the platform makes beside every image column);+// - the companions of each File or Image column the download keeps: `<file>_name` beside a File column, and `<image>id`,+// `<image>_timestamp` and `<image>_url` beside an Image column. The platform makes them WITH the column (none appears in the+// designer). LIVE-MEASURED, `<file>_name` is `AttributeOf` the File column and `_timestamp` / `_url` are `AttributeOf`+// `<image>id`, which the shadow rule in entityFromMetadata reads; but `<image>id` itself is a custom Uniqueidentifier that is+// `AttributeOf` nothing and not logical (the Image column is `AttributeOf` IT), so no shadow rule sees it. Naming them here keeps+// `<image>id` out (its type would as well: see the AttributeOf rule in entityFromMetadata), and every one of them when that read+// failed. Kept in, a rebuild into a fresh environment would create them as Text and BigInt columns of their own, under the very+// names the platform makes for the File or Image column itself.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-column-data#primary-images+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/file-column-data+const TABLE_IMAGE_COLUMNS = new Set(['entityimage', 'entityimage_url', 'entityimage_timestamp', 'entityimageid']);+const MEDIA_COMPANION_SUFFIXES = { File: ['_name'], Image: ['id', '_timestamp', '_url'] };++function attributeLogicalName(a) {+ return String((a && (a.logicalName || a.LogicalName || a.schemaName || a.SchemaName)) || '').toLowerCase();+}++// The lower-cased names of the companions of every File and Image column among `attrs` (see above).+function mediaCompanionNames(attrs) {+ const out = new Set();+ for (const a of attrs || []) {+ const type = mediaTypeFromTypeName(a);+ const name = attributeLogicalName(a);+ if (!type || !name) continue;+ for (const suffix of MEDIA_COMPANION_SUFFIXES[type]) out.add(`${name}${suffix}`);+ }+ return out;+}++// The size a File or Image column comes back with, when one is worth writing: the size the column was made with, unless it is the+// one a rebuild of a spec WITHOUT `maxSizeKb` gives it (DEFAULT_MAX_SIZE_KB, the build's own) — so a column authored without a size+// downloads as it was authored, and one made in Maker (32768 KB for a File column there) or with another size keeps it. Plus, for+// an image, `isPrimaryImage: true` when the platform reports the column as the table's primary image. The platform makes a table's+// FIRST Image column its primary image whatever the create sent (LIVE-MEASURED: a build sending `false` read back `true`; Microsoft+// Learn, image-attributes: "If there's only one image column for a table, this value is set by default"), so a spec whose one Image+// column sets no flag downloads with it: written all the same, as it is what the environment holds, and a rebuild sends nothing for+// a column that exists. `false` is what a build sends for a spec without the flag, so it is never written.+function mediaColumnFields(a, type) {+ const out = {};+ const size = a && a.MaxSizeInKB;+ if (usableMediaSize(size) && size !== DEFAULT_MAX_SIZE_KB) out.maxSizeKb = size;+ if (type === 'Image' && a && a.IsPrimaryImage === true) out.isPrimaryImage = true;+ return out;+}++// `MaxSizeInKB` is an Int32 the platform always fills for a File or Image column, so anything but a positive whole number is not a+// size this download can write — it is reported as missing (missingMediaDetail) rather than guessed.+function usableMediaSize(size) {+ return Number.isInteger(size) && size > 0;+}++// What an ANSWERED read of a File or Image column's cast did not give it: 'size', and for an image 'primary' — its row was not in the+// answer, or held a value that cannot be used (a size that is not a positive whole number, a flag that is not true or false). Checked+// against the columns a download writes, so an answer read while the table changes — a column added after the attribute read, say —+// is said rather than taken for a column at the build's default. [] when the read did not answer: a failed read is reported as+// such (mediaReadFailures), and no read is made for a column typed without a type name.+function missingMediaDetail(meta, a, type) {+ if (!(meta && meta.mediaReadsAnswered && meta.mediaReadsAnswered[type] === true)) return [];+ const missing = [];+ if (!usableMediaSize(a && a.MaxSizeInKB)) missing.push('size');+ if (type === 'Image' && typeof (a && a.IsPrimaryImage) !== 'boolean') missing.push('primary');+ return missing;+}+// One downloaded option set, or null when it carries nothing this spec can declare. Shape:// { name: 'new_ticket_new_status', isGlobal: false, options: [<Dataverse Label>, ...] }//@@ -1577,10 +1674,15 @@ function untypedColumnNames(entities) {return out;}-function entityFromMetadata(meta, logical) {+// `unexpressible`, when given, is an array this fills with the attributes left out because the App Spec has no type for them although+// nothing shows they were not authored (`{ table, column, typeName }`), so the caller can name them (see the end of the filter).+// `incomplete`, when given, is filled with the File and Image columns written without detail an answered read should have carried+// (`{ table, column, type, missing }`, missingMediaDetail), so the caller can name those too.+function entityFromMetadata(meta, logical, { unexpressible, incomplete } = {}) {const primary = meta && (meta.primaryNameAttribute || meta.primaryNameLogicalName);const attrs = Array.isArray(meta && meta.attributes) ? meta.attributes : (Array.isArray(meta && meta.Attributes) ? meta.Attributes : []);const primaryLower = String(primary || '').toLowerCase();+ const companions = mediaCompanionNames(attrs);const columns = attrs.filter((a) => {if (!a) return false;const name = String(a.schemaName || a.SchemaName || a.logicalName || a.LogicalName || '').toLowerCase();@@ -1597,6 +1699,9 @@ function entityFromMetadata(meta, logical) {// sdk-build.js `defaultViewColumns`: the set only ever contains DECLARED spec columns.const isCustom = a.isCustomAttribute !== undefined ? a.isCustomAttribute : a.IsCustomAttribute;if (isCustom === false) return false;+ // The table's own primary image, and the platform's companions of a File or Image column — never authored, never created by a+ // build (TABLE_IMAGE_COLUMNS). A column the type name itself proves to be a File or Image column is never a companion.+ if (TABLE_IMAGE_COLUMNS.has(name) || (companions.has(name) && mediaTypeFromTypeName(a) === undefined)) return false;// SYNTHETIC SHADOW attributes. Creating a lookup also creates a formatted-name attribute// (`<lookup>name`) which LIVE-MEASURED reports `AttributeType: "String"` AND// `IsCustomAttribute: true` — so neither the type map nor the custom-only filter above excludes@@ -1625,8 +1730,12 @@ function entityFromMetadata(meta, logical) {// EVERY attribute when the read fails, so dropping on absent would empty the table's `columns[]`// entirely. The residual cost is that a failed read re-enables the shadow leak, which is why the// label-read warning now names that consequence explicitly.+ //+ // A File or Image column is exempt for the same reason a choice is: its type name is positive evidence of an authored column.+ // And the exemption is load-bearing, not defensive: LIVE-MEASURED, the platform reports an Image column `IsLogical: true` (it is+ // `AttributeOf` the `<image>id` beside it — see the AttributeOf rule below), and a File column `IsLogical: false`.const isLogical = a.IsLogical !== undefined ? a.IsLogical : a.isLogical;- if (isLogical === true && a.optionSet === undefined && choiceTypeFromTypeName(a) === undefined) return false;+ if (isLogical === true && a.optionSet === undefined && choiceTypeFromTypeName(a) === undefined && mediaTypeFromTypeName(a) === undefined) return false;// SHADOW-OF, the precise form of the same rule. `AttributeOf` names the attribute this one is a// projection of, so a non-empty value is positive proof the column was never authored — no type// inference and no relationship context needed.@@ -1643,7 +1752,22 @@ function entityFromMetadata(meta, logical) {//// Absent KEEPS the attribute, matching every other rule here: when the label read fails no// attribute carries `AttributeOf`, and "we could not look" must not become a column deletion.- if (a.AttributeOf) return false;+ //+ // A File or Image column is exempt, because for an Image column "a projection, so never authored" is false. LIVE-MEASURED (the+ // names here are placeholders), the same for the columns a build made and the ones made in Maker:+ // contoso_contract AttributeOf=null IsLogical=FALSE AttributeType=Virtual AttributeTypeName=FileType+ // contoso_contract_name AttributeOf=contoso_contract IsLogical=TRUE AttributeType=String+ // contoso_photo AttributeOf=contoso_photoid IsLogical=TRUE AttributeType=Virtual AttributeTypeName=ImageType+ // contoso_photoid AttributeOf=null IsLogical=FALSE AttributeType=Uniqueidentifier IsCustomAttribute=true+ // contoso_photo_timestamp AttributeOf=contoso_photoid IsLogical=TRUE AttributeType=BigInt+ // contoso_photo_url AttributeOf=contoso_photoid IsLogical=TRUE AttributeType=String+ // The authored Image column is itself `AttributeOf` the `<image>id` that holds the image's id, so this rule dropped every Image+ // column a maker or a build made, without a word. Its type name is positive evidence of an authored column, as for the IsLogical+ // rule above: no companion is FileType or ImageType, so the exemption admits none — `_timestamp`, `_url` and `<file>_name` are+ // still dropped here. `<image>id` is `AttributeOf` nothing and not logical, so no shadow rule sees it: its NAME keeps it out (the+ // companion rule above), and its type would too — a Uniqueidentifier is no App Spec column type, and not being Virtual it is left+ // out without being named (the type rule below). The table's own image, `entityimage`, which is ImageType, is out by name first.+ if (a.AttributeOf && mediaTypeFromTypeName(a) === undefined) return false;// BASE-CURRENCY TWIN. Dataverse generates a `<money>_base` column beside every Money column. It// carries no `AttributeOf`, is not logical, and reports `IsCustomAttribute: true`, so every rule// above is blind to it — and emitting it meant a rebuild tried to CREATE a column the platform@@ -1664,9 +1788,21 @@ function entityFromMetadata(meta, logical) {// Keep only attribute types the App Spec can declare (see the map above), PLUS any attribute the// option-set read matched, PLUS any attribute `AttributeTypeName` proves is a choice. That last// clause is what keeps a MultiChoice when the cast read failed or came back empty: its- // `AttributeType` is `Virtual`, so nothing else would admit it.+ // `AttributeType` is `Virtual`, so nothing else would admit it. A File or Image column is+ // `Virtual` too, and its type name admits it the same way (SPEC_TYPE_FROM_MEDIA_TYPE_NAME).const at = a.attributeType || a.AttributeType;- return at === undefined || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at] !== undefined || a.optionSet !== undefined || choiceTypeFromTypeName(a) !== undefined;+ if (at === undefined || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at] !== undefined || a.optionSet !== undefined || choiceTypeFromTypeName(a) !== undefined || mediaTypeFromTypeName(a) !== undefined) return true;+ // Any OTHER `Virtual` column that got this far — custom, not logical, the companion of nothing — has a type the App Spec cannot+ // express, and leaving it out costs a rebuild into a fresh environment that column. So it is NAMED (by the caller, from+ // `unexpressible`), never dropped without a word. Only when the attribute read gave its type name: without it the platform's+ // virtual companions cannot be told from such a column (that read also carries `AttributeOf`), and the read's own failure is+ // what is reported then. Every other type left out here is one a spec never declares as a column — a Lookup comes from+ // relationships[], an Owner, State, Status or Uniqueidentifier is the platform's — and stays out silently, as before.+ const typeName = a.AttributeTypeName && a.AttributeTypeName.Value;+ if (at === 'Virtual' && typeof typeName === 'string' && typeName && Array.isArray(unexpressible)) {+ unexpressible.push({ table: logical, column: a.schemaName || a.SchemaName || a.logicalName || a.LogicalName, typeName });+ }+ return false;}).map((a) => {const schemaName = (a && (a.schemaName || a.SchemaName || a.logicalName || a.LogicalName)) || '';// The SDK projects `attributeType`, NOT `type`. Reading `a.type` yielded `undefined` on every@@ -1685,7 +1821,8 @@ function entityFromMetadata(meta, logical) {// untyped regardless. A mutation removing it from this expression was not detectable by any// test, which is the signal that it was decoration rather than logic.const os = (a && a.optionSet) || null;- const mapped = (a && a.type) || (os && os.type) || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at];+ // A File or Image column's type comes from its type NAME, before the AttributeType map (which sees only `Virtual` for both).+ const mapped = (a && a.type) || (os && os.type) || mediaTypeFromTypeName(a) || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at];// Companion data for a Choice/MultiChoice (see TYPES_NEEDING_COMPANION_DATA). Present -> the// column carries its REAL type plus the `options[]`/`globalChoice` its declaration requires.// Absent -> it stays untyped and is named in the untyped-column warning, because emitting@@ -1721,6 +1858,10 @@ function entityFromMetadata(meta, logical) {: (usableOptionSet.isGlobal && usableOptionSet.name? { globalChoice: usableOptionSet.name }: { options: inlineOptions });+ if ((specType === 'File' || specType === 'Image') && schemaName && Array.isArray(incomplete)) {+ const missing = missingMediaDetail(meta, a, specType);+ if (missing.length) incomplete.push({ table: logical, column: schemaName, type: specType, missing });+ }return withDescription({schemaName,// A column labelled in several languages round-trips as an LCID map; one language stays a@@ -1740,6 +1881,8 @@ function entityFromMetadata(meta, logical) {...(columnDisplayName(a) !== undefined ? { displayName: columnDisplayName(a) } : {}),...(specType ? { type: specType } : {}),...choice,+ // The size (and, for an image, the primary-image flag) the column was made with, where a rebuild needs it (mediaColumnFields).+ ...(specType === 'File' || specType === 'Image' ? mediaColumnFields(a, specType) : {}),}, a && (a.description !== undefined ? a.description : a.Description));}).filter((c) => c.schemaName);// Table label + plural. When the table carries more than one language, BOTH must round-trip and@@ -1754,17 +1897,26 @@ function entityFromMetadata(meta, logical) {// translations. `'Name'` remains the fallback for a metadata read that carried no label at all.const primaryAttr = primaryLower ? attrs.find((a) => String((a && (a.logicalName || a.LogicalName || a.schemaName || a.SchemaName)) || '').toLowerCase() === primaryLower) : null;const primaryLabel = columnDisplayName(primaryAttr);+ const tableSchemaName = (meta && (meta.schemaName || meta.logicalName)) || logical;+ const tableLabel = displayName !== undefined ? displayName : ((meta && meta.displayName) || logical);return {- schemaName: (meta && (meta.schemaName || meta.logicalName)) || logical,- displayName: displayName !== undefined ? displayName : ((meta && meta.displayName) || logical),+ schemaName: tableSchemaName,+ displayName: tableLabel,// Emitted when EITHER label is localized, not only when the singular is. `validateAppSpec`// requires `pluralName` beside a localized `displayName`, which is why the singular's shape is// checked — but a table can carry a single-language `DisplayName` and a multi-language// `DisplayCollectionName` (the two are independent in Dataverse, and an unprovisioned language is// dropped per-label on read). Keying only off the singular silently discarded those plural- // translations and a rebuild then derived an English plural. Two PLAIN labels still omit it: a- // plain plural is derivable and emitting it would add noise to every download.- ...((isLocalizedLabelMap(displayName) || isLocalizedLabelMap(pluralName)) && pluralName !== undefined ? { pluralName } : {}),+ // translations and a rebuild then derived an English plural.+ //+ // Two PLAIN labels omit it only when the plural is the one a rebuild of a spec without it would+ // write — derivedPluralName, the build's own rule, applied to what this spec says — so every+ // download of an ordinary table ("Order" / "Orders") stays byte-identical. Any other plural is+ // kept, because leaving it out was a silent rename: "Tag Catalog" is not derivable from "Tag", and+ // a rebuild into another environment named the table "Tags". The comparison is exact (case and+ // spacing included), because that is how the build writes the derivation.+ ...(pluralName !== undefined && (isLocalizedLabelMap(displayName) || isLocalizedLabelMap(pluralName)+ || pluralName !== derivedPluralName({ schemaName: tableSchemaName, displayName: tableLabel })) ? { pluralName } : {}),...(descriptionFromDataverse(meta && (meta.description !== undefined ? meta.description : meta.Description)) ? { description: descriptionFromDataverse(meta && (meta.description !== undefined ? meta.description : meta.Description)) } : {}),// Never synthesized: a fabricated attribute name yields a spec that references a column Dataverse// does not have, which is exactly the bug this fixes.@@ -1882,6 +2034,10 @@ async function readEntityWithDescriptions(sdk, logical, { concurrency } = {}) {// A non-2xx is NOT "this table has no extra languages" — it is "we could not look". Recorded so// the caller can say so; see the catch below for why silence here is the wrong default.meta.labelReadFailed = entityLabels.failed;+ // WHICH read failed is recorded too, because the two carry different things — this one the table's own labels (and with them+ // its plural, which no other read carries), the one below the columns' labels with the flags and type names the column filters+ // read — and a warning must say only what the read that failed carries (runDownload).+ meta.tableLabelReadFailed = entityLabels.failed;}if (attributeLabels.rows) {// Merge onto the SDK's attribute list rather than replacing it: `fetchEntityMetadata` supplies@@ -1905,11 +2061,12 @@ async function readEntityWithDescriptions(sdk, logical, { concurrency } = {}) {const row = byLogical.get(key);return row ? { ...a, Description: row.Description, DisplayName: row.DisplayName, IsLogical: row.IsLogical, AttributeOf: row.AttributeOf, AttributeTypeName: row.AttributeTypeName } : a;});- } else if (attributeLabels.failed && !meta.labelReadFailed) {+ } else if (attributeLabels.failed) {// Recorded, not swallowed — and it does NOT overwrite a table-level failure already recorded// above, because the first reason is the more useful one to show and both describe the same// outcome for the operator: this table came back single-language.- meta.labelReadFailed = attributeLabels.failed;+ if (!meta.labelReadFailed) meta.labelReadFailed = attributeLabels.failed;+ meta.attributeReadFailed = attributeLabels.failed;}// Base-currency twins. `IsBaseCurrency` lives on MoneyAttributeMetadata, not on the base// attribute type, so it needs its own CAST read — the same shape the option-set reads below use.@@ -1943,9 +2100,77 @@ async function readEntityWithDescriptions(sdk, logical, { concurrency } = {}) {});// A cast that failed is recorded WITHOUT discarding what the other one returned.if (optionSets.failed) meta.optionSetReadFailed = optionSets.failed;+ // File and Image columns: the size each was made with, and whether an image is the table's primary one (readMediaColumns). Read+ // AFTER the reads above, because only their type names say whether the table has such a column at all — a table without one+ // sends no more requests than it did before. A row of the File answer is taken only for a File column, and one of the Image answer+ // only for an Image column.+ const media = await readMediaColumns(sdk, logical, meta.attributes, concurrency);+ if (media.rows.File.size || media.rows.Image.size) {+ meta.attributes = (meta.attributes || []).map((a) => {+ const type = mediaTypeFromTypeName(a);+ const row = type ? media.rows[type].get(attributeLogicalName(a)) : undefined;+ if (!row) return a;+ return {+ ...a,+ ...(row.MaxSizeInKB !== undefined ? { MaxSizeInKB: row.MaxSizeInKB } : {}),+ ...(type === 'Image' && row.IsPrimaryImage !== undefined ? { IsPrimaryImage: row.IsPrimaryImage } : {}),+ };+ });+ }+ // By type, because each read carries only its own columns' detail, and what the caller says must name only what the read that+ // failed carries (mediaReadFailures). The columns are kept, typed, either way. A read that answered is what entityFromMetadata+ // checks each of its columns against, so an answer that lacks one is said too (missingMediaDetail).+ if (Object.keys(media.answered).length) meta.mediaReadsAnswered = media.answered;+ if (Object.keys(media.failed).length) meta.mediaReadFailures = media.failed;return meta;}+// What a File or an Image column was made with. `MaxSizeInKB` and `IsPrimaryImage` belong to the derived metadata types, not to+// AttributeMetadata, so they are read through a cast segment, as the option sets and the Money flags are. Shapes (abridged):+// GET EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.FileAttributeMetadata?$select=LogicalName,MaxSizeInKB+// -> { "value": [ { "LogicalName": "contoso_contract", "MaxSizeInKB": 1024, "MetadataId": "<guid>" } ] }+// GET EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.ImageAttributeMetadata?$select=LogicalName,MaxSizeInKB,IsPrimaryImage+// -> { "value": [ { "LogicalName": "contoso_logo", "MaxSizeInKB": 10240, "IsPrimaryImage": false, "MetadataId": "<guid>" } ] }+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/fileattributemetadata+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/imageattributemetadata+const MEDIA_CASTS = [+ { type: 'File', cast: 'Microsoft.Dynamics.CRM.FileAttributeMetadata', select: 'LogicalName,MaxSizeInKB' },+ { type: 'Image', cast: 'Microsoft.Dynamics.CRM.ImageAttributeMetadata', select: 'LogicalName,MaxSizeInKB,IsPrimaryImage' },+];++// Reads the casts of the types `attributes` holds a column of (by type name; the table's own `entityimage` does not count, as it is+// never written to a spec), and returns, by type: `rows` (Map<lower-cased name, row>, empty for a type not read or not answered),+// `answered` (true for a read that answered with a value[]) and `failed` (the reason for one that did not). A failed read is recorded,+// not thrown: the columns are kept either way, and the caller says what was lost (their sizes, an image's primary flag).+async function readMediaColumns(sdk, logical, attributes, concurrency) {+ const present = new Set((attributes || [])+ .filter((a) => !TABLE_IMAGE_COLUMNS.has(attributeLogicalName(a)))+ .map(mediaTypeFromTypeName)+ .filter(Boolean));+ const reads = MEDIA_CASTS.filter((m) => present.has(m.type));+ const results = await mapLimit(reads, concurrency, async ({ type, cast, select }) => {+ try {+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/Attributes/${cast}?$select=${select}`);+ // `dataverse.get` RESOLVES on a non-2xx rather than throwing, so the status is checked here, as for every read above.+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);+ if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');+ return { type, rows: res.body.value };+ } catch (err) {+ return { type, failed: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };+ }+ }, { firstInOrder: true });+ const out = { rows: { File: new Map(), Image: new Map() }, answered: {}, failed: {} };+ for (const r of results) {+ if (r.failed) { out.failed[r.type] = r.failed; continue; }+ out.answered[r.type] = true;+ for (const row of r.rows) {+ const key = String((row && row.LogicalName) || '').toLowerCase();+ if (key) out.rows[r.type].set(key, row);+ }+ }+ return out;+}+// Reconstruct an App Spec label from a Dataverse Label, preserving EVERY language. AB#6686428.//// Shape (see the Label reference linked in hydrate-spec.js):@@ -2498,20 +2723,31 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossyconst noPrimaryName = []; // sitemap tables — a hard failure (the user asked for these)const droppedComponents = []; // component-only tables — dropped with a warning (best-effort input)const metadataErrors = new Map(); // logical -> error message (the read itself failed)- // Tables whose LABEL read failed. Distinct from `metadataErrors`: the table itself was recovered- // and the spec is usable, but only the SDK's flattened single-language `displayName` survived, so- // a multi-language table silently downloads as English-only. Reported rather than swallowed.- const labelReadFailures = new Map(); // logical -> reason- // Tables whose OPTION-SET read failed (#564). Kept apart from `labelReadFailures` for the same- // reason that one is kept apart from `metadataErrors`: the table is recovered and the spec is+ // Tables whose LABEL reads failed. Distinct from `metadataErrors`: the table itself was recovered+ // and the spec is usable, but only the SDK's flattened single-language labels survived, so+ // a multi-language table silently downloads as English-only. Reported rather than swallowed —+ // by READ, because the table's own read and the columns' read carry different things, and each+ // warning must say only what the read that failed carries.+ const tableLabelReadFailures = new Map(); // logical -> reason+ const attributeReadFailures = new Map(); // logical -> reason+ // Tables whose OPTION-SET read failed (#564). Kept apart from the label reads for the same+ // reason that those are kept apart from `metadataErrors`: the table is recovered and the spec is// usable, but every Choice/MultiChoice column on it comes back untyped, so a cross-environment// rebuild would create them as Text. Naming the reason is what makes that actionable.const optionSetReadFailures = new Map(); // logical -> reason+ // Tables whose File or Image read failed, by type: those columns are kept and typed, but without what that read carries.+ const mediaReadFailures = { File: new Map(), Image: new Map() }; // type -> logical -> reason+ // File and Image columns an answered read came back without detail for (entityFromMetadata's `incomplete`), of the tables kept.+ const incompleteMediaColumns = [];+ // Columns left out because the App Spec has no type for them (entityFromMetadata's `unexpressible`), of the tables the spec keeps.+ const unexpressibleColumns = [];// Shared option sets bound by a downloaded column, keyed by lower-cased name so a set used by// several tables is declared once.const globalChoiceDecls = new Map();for (const logical of allLogicals) {let e;+ const leftOut = [];+ const shortOf = [];// A metadata READ failure is not the same as metadata that reports no primary name, and it must// not be swallowed: a 429/503 on a sitemap table used to drop it silently, leaving its subarea// behind so validation later complained about a "sitemap subArea references unknown entity" —@@ -2519,10 +2755,12 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy// exactly like the no-primary-name case, so the user is told the table AND the reason.try {const meta = await readEntityWithDescriptions(sdk, logical, { concurrency });- if (meta && meta.labelReadFailed) labelReadFailures.set(logical, meta.labelReadFailed);+ if (meta && meta.tableLabelReadFailed) tableLabelReadFailures.set(logical, meta.tableLabelReadFailed);+ if (meta && meta.attributeReadFailed) attributeReadFailures.set(logical, meta.attributeReadFailed);if (meta && meta.optionSetReadFailed) optionSetReadFailures.set(logical, meta.optionSetReadFailed);+ for (const [type, reason] of Object.entries((meta && meta.mediaReadFailures) || {})) if (mediaReadFailures[type]) mediaReadFailures[type].set(logical, reason);collectGlobalChoices(meta, globalChoiceDecls);- e = entityFromMetadata(meta, logical);+ e = entityFromMetadata(meta, logical, { unexpressible: leftOut, incomplete: shortOf });} catch (err) {metadataErrors.set(logical, (err && err.message) || String(err));(sitemapSet.has(logical) ? noPrimaryName : droppedComponents).push(logical);@@ -2543,6 +2781,8 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossycontinue;}entities.push(e);+ for (const c of leftOut) unexpressibleColumns.push(`${e.schemaName}.${c.column} (${c.typeName})`);+ for (const c of shortOf) incompleteMediaColumns.push({ name: `${e.schemaName}.${c.column}`, missing: c.missing });}const withReason = (list) => list.map((l) => (metadataErrors.has(l) ? `${l} (metadata read failed: ${metadataErrors.get(l)})` : l)).join(', ');if (noPrimaryName.length) {@@ -2557,14 +2797,22 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossyif (droppedComponents.length) {process.stderr.write(`WARNING: ${droppedComponents.length} app component table(s) were omitted from the spec because Dataverse reported no primary-name column (${withReason(droppedComponents)}) — they are NOT in the app's navigation, and the deployed app still references them; declare them by hand if a rebuild needs them.\n`);}- // AB#6686428: the label read is the ONLY source of multi-language labels. When it fails the table- // is still recovered, so the download succeeds and the spec looks complete — but it carries the- // SDK's flattened single-language `displayName` and every other language is gone. Silently- // degrading there is the same shape as the bug this feature fixes, so say so. Not a gate: an- // English-only spec is still a usable spec, and failing a read-only command over it would be worse.- if (labelReadFailures.size) {- const detail = [...labelReadFailures.entries()].sort(([a], [b]) => compareText(a, b)).map(([l, r]) => `${l} (${r})`).join(', ');- process.stderr.write(`WARNING: a label read failed for ${labelReadFailures.size} table(s) (${detail}). The table AND COLUMN labels for those tables fall back to ONE language, so anything labelled in several languages downloads as single-language and a rebuild would recreate it that way. That read also carries the flags that identify a lookup's synthetic '<lookup>name' column, so those tables may additionally have captured one as a real Text column — delete any you see before a cross-environment rebuild. Re-run the download to recover both.\n`);+ // AB#6686428: the two label reads are the ONLY source of multi-language labels — the table's own (its display name, plural and+ // description) and the columns' (which also carries the flags and type names the column filters read). When one fails the table+ // is still recovered, so the download succeeds and the spec looks complete — but it carries the SDK's flattened single-language+ // labels and every other language is gone. Silently degrading there is the same shape as the bug this feature fixes, so say so —+ // once per READ, naming only what that read carries: the table's read failing says nothing about the columns, and the columns'+ // read failing says nothing about the table. Not a gate: an English-only spec is still a usable spec, and failing a read-only+ // command over it would be worse.+ const failureDetail = (failures) => [...failures.entries()].sort(([a], [b]) => compareText(a, b)).map(([l, r]) => `${l} (${r})`).join(', ');+ if (tableLabelReadFailures.size) {+ // The table's plural is carried by this read alone (download keeps one a rebuild would not derive), so it goes with it.+ process.stderr.write(`WARNING: the table label read failed for ${tableLabelReadFailures.size} table(s) (${failureDetail(tableLabelReadFailures)}). Their display names and descriptions fall back to ONE language and their plurals are not written, so rebuilding into a FRESH environment would recreate each of those tables labelled in one language, with the plural '<display name>s'. Re-run the download to recover them before a cross-environment rebuild.\n`);+ }+ if (attributeReadFailures.size) {+ // Without this read no Virtual column has the type name entityFromMetadata names an unexpressible one by, so none is named: the+ // platform's own virtual columns could not be told from it. That is what the last clause says, and it is said only here.+ process.stderr.write(`WARNING: the column read failed for ${attributeReadFailures.size} table(s) (${failureDetail(attributeReadFailures)}). Their COLUMN labels and descriptions fall back to ONE language, so a column labelled in several languages downloads as single-language and rebuilding into a FRESH environment would recreate it that way. That read also carries the flags that identify a lookup's synthetic '<lookup>name' column, so those tables may additionally have captured one as a real Text column — delete any you see before a cross-environment rebuild — and the type names that tell a column of a type the App Spec cannot express from the platform's own, so any such column on those tables was left out without being named. Re-run the download to recover them.\n`);}// #564: the option-set read is the ONLY source of a Choice/MultiChoice column's type. When it// fails the table is still recovered and the spec still looks complete, but every choice column on@@ -2584,6 +2832,34 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossyif (untyped.length) {process.stderr.write(`WARNING: ${untyped.length} column(s) were captured WITHOUT a type (${untyped.join(', ')}) — most likely Choice/MultiChoice columns whose option set could not be read. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Add the type and options[] (or a globalChoice reference) by hand before a cross-environment rebuild.\n`);}+ // A File or Image column whose read failed is still in the spec, typed, but without what that read carries — so a rebuild into a+ // FRESH environment makes it at the build's default size (and an image not asked to be the table's primary one) instead of as it is+ // here. Said per READ, with the reason, as the option-set failure is: the read is what is re-runnable, and the File read failing+ // says nothing about the Image columns, nor the other way round.+ if (mediaReadFailures.File.size) {+ process.stderr.write(`WARNING: the File column read failed for ${mediaReadFailures.File.size} table(s) (${failureDetail(mediaReadFailures.File)}). Their File columns are captured WITHOUT the maximum size each was made with, so rebuilding into a FRESH environment would create them at the default size of ${DEFAULT_MAX_SIZE_KB} KB. Re-run the download to recover them before a cross-environment rebuild.\n`);+ }+ if (mediaReadFailures.Image.size) {+ process.stderr.write(`WARNING: the Image column read failed for ${mediaReadFailures.Image.size} table(s) (${failureDetail(mediaReadFailures.Image)}). Their Image columns are captured WITHOUT the maximum size each was made with or whether one is the table's primary image, so rebuilding into a FRESH environment would create them at the default size of ${DEFAULT_MAX_SIZE_KB} KB, none of them asked to be the table's primary image. Re-run the download to recover them before a cross-environment rebuild.\n`);+ }+ // A read that answered, but without a column's row or with a value that cannot be used (missingMediaDetail) — what an answer read+ // while the table changes can carry. The column is kept with whatever valid detail came back; what did not is named per column,+ // and the consequence is said only for the kinds of detail that are missing.+ if (incompleteMediaColumns.length) {+ const WHAT = { size: 'its maximum size', primary: "whether it is the table's primary image" };+ const named = incompleteMediaColumns.slice().sort((a, b) => compareText(a.name, b.name)).map((c) => `${c.name} (${c.missing.map((m) => WHAT[m]).join(' and ')})`);+ const consequences = [+ ...(incompleteMediaColumns.some((c) => c.missing.includes('size')) ? [`create a column without its maximum size at the default size of ${DEFAULT_MAX_SIZE_KB} KB`] : []),+ ...(incompleteMediaColumns.some((c) => c.missing.includes('primary')) ? ["not ask an Image column without its primary-image flag to be the table's primary image"] : []),+ ];+ process.stderr.write(`WARNING: the File/Image column read came back incomplete for ${named.length} column(s): ${named.join(', ')}. Each is captured without what did not come back, so rebuilding into a FRESH environment would ${consequences.join(' and would ')}. Re-run the download to recover them before a cross-environment rebuild.\n`);+ }+ // A column whose type the App Spec cannot express is left out of columns[] (entityFromMetadata's `unexpressible`). A rebuild into+ // an environment that has the table leaves it as it is — a build never deletes a column a spec does not list — but one into a+ // FRESH environment would not make it at all, so each is named rather than dropped without a word.+ if (unexpressibleColumns.length) {+ process.stderr.write(`WARNING: ${unexpressibleColumns.length} column(s) have a type the App Spec cannot express and were left out of the spec (${unexpressibleColumns.join(', ')}). Rebuilding this spec into an environment that already has the table leaves them as they are, but rebuilding into a FRESH environment would not create them: add them there in Maker after the rebuild.\n`);+ }// App identity comes from the app's REAL, immutable uniquename (`appUnique`, captured from Dataverse as// `appmodule.uniquename`; guaranteed present here because runDownload bails at the sitemap gate above).@@ -2807,6 +3083,7 @@ async function main(deps = {}) {needValue: ['env', 'app', 'out', 'output', 'language-code', 'languageCode'],});if (flagError) {+ makeWritesBlocking(io.stderr);io.stderr.write(`✗ ${flagError}\n${USAGE}\n`);io.exit(1);return;@@ -2828,6 +3105,7 @@ async function main(deps = {}) {try {languageFlag = readLanguageCodeFlag(flags);} catch (e) {+ makeWritesBlocking(io.stderr);io.stderr.write(`✗ ${e.message}\n${USAGE}\n`);io.exit(1);return;@@ -2898,6 +3176,8 @@ async function main(deps = {}) {const genpage = io.makeGenpageSdk(env, { sdk });const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys });+ // The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, io.stderr);if (!result.ok) { finish(false, result); return; }const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, solutionCandidates, navIdsLeft } = result;diff --git a/plugins/model-apps/scripts/generate-page-manifest.js b/plugins/model-apps/scripts/generate-page-manifest.jsindex 93116f15b..81c6e9e00 100644--- a/plugins/model-apps/scripts/generate-page-manifest.js+++ b/plugins/model-apps/scripts/generate-page-manifest.js@@ -46,6 +46,7 @@ const {buildDevDependencyMap,FEATURE_RUNTIME_KEYS,} = require('./lib/supported-dependencies.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const VALID_FEATURES = new Set(Object.keys(FEATURE_RUNTIME_KEYS));@@ -440,6 +441,7 @@ function main() {try {args = parseArgs(process.argv.slice(2));} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: ${err.message}`);process.exit(1);}@@ -457,24 +459,29 @@ function main() {let approvedRoot;try {if (!fs.existsSync(workingDir)) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: working directory does not exist: ${workingDir}`);process.exit(2);}if (fs.lstatSync(workingDir).isSymbolicLink()) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: refusing to use ${workingDir} as the working directory: it is a symbolic link or junction. Pass the directory it points to if that is intended.`);process.exit(2);}if (!fs.statSync(workingDir).isDirectory()) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: not a directory: ${workingDir}`);process.exit(2);}approvedRoot = fs.realpathSync(workingDir);} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: failed to stat working directory: ${err.message}`);process.exit(2);}if (!/^[a-z][a-z0-9-]*$/.test(slug)) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: page-slug must be kebab-case (got: ${slug})`);process.exit(1);}@@ -491,6 +498,7 @@ function main() {const dtsPath = path.join(workingDir, 'genpage.d.ts');dtsResult = writeIfAllowed(dtsPath, buildAmbientDeclarations(), args.force, approvedRoot);} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);console.error(`error: ${err.message}`);process.exit(2);}diff --git a/plugins/model-apps/scripts/genpage-base.js b/plugins/model-apps/scripts/genpage-base.jsindex 93fc23780..3ec48de43 100644--- a/plugins/model-apps/scripts/genpage-base.js+++ b/plugins/model-apps/scripts/genpage-base.js@@ -36,6 +36,7 @@ const {readPlainText,markerPath,} = require('./lib/genpage-base.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = 'Usage: node scripts/genpage-base.js record --page-id <id> --file <page.tsx> [--app-id <id>] [--deployed-sha256 <hash>]\n'+ ' node scripts/genpage-base.js check --env <url> --app-id <id> --page-id <id> --file <local.tsx>';@@ -181,6 +182,7 @@ async function main(argv = process.argv.slice(2), deps = {}) {if (require.main === module) {main().catch((e) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${e && e.message ? e.message : e}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/genpage-plan-provenance.js b/plugins/model-apps/scripts/genpage-plan-provenance.jsindex 48d476a2c..0878d723f 100644--- a/plugins/model-apps/scripts/genpage-plan-provenance.js+++ b/plugins/model-apps/scripts/genpage-plan-provenance.js@@ -25,6 +25,7 @@ const fs = require('node:fs');const path = require('node:path');const { pagesTables } = require('./lib/page-file-targets.js');const { sha256 } = require('./lib/hash.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// What a plan document targets.// create: the Pages table's File column — `## Pages` in the written plan, `### Pages (N total)`@@ -360,6 +361,9 @@ function main() {result = { ok: false, error: 'Usage: node genpage-plan-provenance.js prepare --plan <path> OR verify --plan <path> --approved @<approved-plan-file>' };}+ // A mismatch carries both change lists whole, and the process exits right after the write: it is made blocking+ // first, or a pipe on Linux and macOS takes only what fits at once (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify(result) + '\n');process.exit(result.ok ? 0 : (args.command === 'prepare' || args.command === 'verify' ? 3 : 1));}diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.jsindex bcc123c24..9d36b87e6 100644--- a/plugins/model-apps/scripts/genpage-upload.js+++ b/plugins/model-apps/scripts/genpage-upload.js@@ -48,11 +48,13 @@ const fs = require('node:fs');const path = require('node:path');const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');const { makeGenpageSdk, suppliedButBlank, sourceText, dataSourcesOf } = require('./lib/genpage-sdk.js');+const { makeThrottleBudget } = require('./lib/throttle-budget.js');const { leftOnDiskWarning } = require('./lib/left-on-disk.js');const { griffelStyleProblems, griffelProblemsNotIn, describeGriffelRefusal, describeGriffelWarning } = require('./lib/griffel-styles.js');const { commandArgOrPlaceholder } = require('./lib/cli-failure.js');const genpageBase = require('./lib/genpage-base.js');const { writeFileSafe } = require('./lib/safe-fs.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const KNOWN = ['env', 'app-id', 'code-file', 'compiled-code-file', 'page-id', 'name', 'name-file','data-sources', 'clear-data-sources', 'prompt', 'prompt-file', 'agent-message', 'agent-message-file',@@ -393,9 +395,10 @@ async function main(argv = process.argv.slice(2), deps = {}) {});if (styleProblems.length && !flags['page-id']) return emit(false, stylesRefusal(styleProblems));- // A throttled page write is waited out for up to five minutes (lib/throttle-budget.js). A wait of more than a few seconds is announced on stderr — stdout carries the JSON result — so that- // a command that is silent for minutes is not mistaken for a hung one.- const genpage = makeBackend(flags.env, { warn: (message) => process.stderr.write(`WARNING: ${message}\n`) });+ // The waiting a run does for a throttled service is bounded at five minutes (lib/throttle-budget.js): this one budget is the page write's and the backend's HTTP client's alike — its reads and its publish wait out a throttle too. A wait of more+ // than a few seconds is announced on stderr — stdout carries the JSON result — so that a command that is silent for minutes is not mistaken for a hung one.+ const warn = (message) => process.stderr.write(`WARNING: ${message}\n`);+ const genpage = makeBackend(flags.env, { warn, throttle: makeThrottleBudget({ warn }) });// The backend's workspace is removed BEFORE anything is reported: emitResult calls process.exit, so a cleanup placed after an emit never// runs, and that workspace holds the page's source. dispose() answers when the storage calls the backend had under way have settled and the// folder is gone — or says, in `{ left }`, which folder is not (a handle a scanner holds), and that is reported with the result: a success that left@@ -707,6 +710,7 @@ async function deploy(context) {if (require.main === module) {main().catch((e) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${e && e.message ? e.message : e}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/genpage-worker-output.js b/plugins/model-apps/scripts/genpage-worker-output.jsindex f10a1b81e..07dd22a19 100644--- a/plugins/model-apps/scripts/genpage-worker-output.js+++ b/plugins/model-apps/scripts/genpage-worker-output.js@@ -23,6 +23,7 @@ const { pageStructureProblems: structuralProblems } = require('./lib/page-structconst STAMP_SUFFIX = '.dispatch-stamp.json';const stampPathFor = (abs) => path.join(path.dirname(abs), `.${path.basename(abs)}${STAMP_SUFFIX}`);const { sha256 } = require('./lib/hash.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');function stampPageTarget({ filePath }) {if (!filePath) return { ok: false, action: 'stamp', problems: ['--file is required'] };@@ -135,6 +136,9 @@ function parseArgv(argv) {function main() {const args = parseArgv(process.argv.slice(2));const result = args.stamp ? stampPageTarget(args) : validatePageOutput(args);+ // The result quotes the path it was given and the page's problems, and the process exits right after it:+ // the write is made blocking first, or a pipe on Linux and macOS takes only what fits at once (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify(result) + '\n');process.exit(result.ok ? 0 : 3);}diff --git a/plugins/model-apps/scripts/genpage.js b/plugins/model-apps/scripts/genpage.jsindex 15b3ad02c..41359b948 100644--- a/plugins/model-apps/scripts/genpage.js+++ b/plugins/model-apps/scripts/genpage.js@@ -118,6 +118,7 @@ const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = requireconst { makeGenpageSdk, pageFolderFiles, dataSourcesOf, GUID_RE, unescapePacName } = require('./lib/genpage-sdk.js');const { leftOnDiskWarning } = require('./lib/left-on-disk.js');const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe, removeFileSafe } = require('./lib/safe-fs.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// How long the backend's cleanup is waited for before the process ends: a storage call that never settles must not keep the script alive.const DISPOSE_WAIT_MS = 10000;@@ -188,6 +189,7 @@ class UsageError extends Error {const scriptError = (code, message, extra = {}) => Object.assign(new Error(message), { code }, extra);function exitWithUsage(message, verb) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${message}\n${usageFor(verb)}\n`);process.exit(1);}@@ -482,6 +484,7 @@ module.exports = { main, parseCommand, UsageError, VERBS };if (require.main === module) {main().catch((error) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Error: ${error && error.message ? error.message : error}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/launch-playwright-mcp.js b/plugins/model-apps/scripts/launch-playwright-mcp.jsindex 36d71490b..1b1a901f8 100644--- a/plugins/model-apps/scripts/launch-playwright-mcp.js+++ b/plugins/model-apps/scripts/launch-playwright-mcp.js@@ -10,6 +10,7 @@ const path = require('path');const { detectBrowser } = require('./lib/detect-browser');// npx is a batch shim on Windows; the runner starts it without a shell (see lib/process-runner.js).const { spawnProcess } = require('./lib/process-runner');+const { makeWritesBlocking } = require('./lib/output-redaction.js');function buildMcpArgs(browser, {configPath = path.join(__dirname, 'playwright-mcp-fullscreen.config.json'),@@ -48,6 +49,7 @@ function launch({// (ENOENT, EACCES, ...). Without a handler Node throws the error as an// uncaught exception; surface it and exit non-zero so the MCP host sees the// server failed to start.+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Failed to launch Playwright MCP server: ${err && err.message ? err.message : err}\n`);process.exit(1);},diff --git a/plugins/model-apps/scripts/lib/app-access.js b/plugins/model-apps/scripts/lib/app-access.jsnew file mode 100644index 000000000..b8af8514b--- /dev/null+++ b/plugins/model-apps/scripts/lib/app-access.js@@ -0,0 +1,266 @@+'use strict';+// What an App Spec says about two different questions the plugin used to answer as one ("no personas[] → the app opens only for administrators", AB#6770008):+//+// 1. Who can open the APP? The security roles ASSOCIATED WITH THE APP (the `appmoduleroles` relationship) decide which users see it in the app list.+// The build writes that association in exactly two places: the SDK gives a NEW app the System Administrator role when it creates it, and the security+// phase associates each persona's role (unless `appAccess: false`). It never changes the roles of an app that already exists, other than for the+// personas it authors. So a spec with no personas[] says nothing about who can open an app that already exists — and the spec alone cannot say whether+// the app exists (existingAppMarkers).+// 2. Who can use a TABLE? Privileges, from personas[] (roles the spec owns: the build converges them to exactly the declared set, and refuses a role it did+// not author) and roleGrants[] (privileges ADDED to roles it does not own — which does not associate the role with the app). A table the spec creates is+// held by no role it does not grant it to.+//+// A user needs both: a role associated with the app to open it, and privileges on a table in a role to work with that table's records in it, as+// https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/share-model-driven-app says. Users with a maker-level role (System Administrator,+// System Customizer, Environment Maker) can open every app without an association: https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/app-visibility-privileges+//+// PURE: no I/O. The lint (spec-lint.js), the design document (app-spec-doc.js) and its warnings (write-app-spec-doc.js) all read the spec through here,+// so they cannot disagree about which tables nothing grants, or which marks say an app already exists. The environment's side — the roles an app+// has — is read by lib/app-roles.js and arrives here as `appAccess`.+const { canonicalPersonaName } = require('./app-spec.js');++// Every collection read here is shape-guarded: the lint and the document run on specs still being typed, and a crash kills the authoring flow.+const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);+const arr = (v) => (Array.isArray(v) ? v : []);+const lc = (s) => String(s || '').toLowerCase();+const filled = (v) => typeof v === 'string' && v.trim() !== '';++// "a", "a and b", "a, b and c".+function list(items) {+ return items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`;+}++/**+ * What the spec carries that a download writes, and a spec for a new app does not: the app's own unique name (`app.uniqueName` — "download-emitted" in+ * references/app-spec-schema.md; an authored create-fresh spec omits it), and the ids of its pages and dashboards (`pages[].pageId`, `dashboards[].dashboardId`:+ * an edit-snapshot's). Each is named once, in this order. They say the spec was DOWNLOADED from an app, which is why callers say "most likely": a copy of+ * a downloaded spec can be built into an environment that does not have the app. An EMPTY list does not mean the app is new either — a hand-written spec for an+ * app that exists carries none of them — so a caller words what it says without them as a condition.+ * @returns {string[]}+ */+function existingAppMarkers(spec) {+ const s = isObject(spec) ? spec : {};+ const marks = [];+ if (isObject(s.app) && filled(s.app.uniqueName)) marks.push('app.uniqueName');+ if (arr(s.pages).some((p) => isObject(p) && filled(p.pageId))) marks.push('pages[].pageId');+ if (arr(s.dashboards).some((d) => isObject(d) && filled(d.dashboardId))) marks.push('dashboards[].dashboardId');+ return marks;+}++/** The tables the spec creates: entities[] not marked `existing: true` (a download marks every table it recovers), by the schemaName they were written with. */+function introducedTables(spec) {+ return arr(isObject(spec) ? spec.entities : []).filter((e) => isObject(e) && filled(e.schemaName) && e.existing !== true).map((e) => e.schemaName);+}++/**+ * Every privilege the spec declares on a table, by the table's logical name (lower case):+ * Map { 'contoso_baseline' → [ { via: 'persona' | 'roleGrant', role, access, scope } ] }+ * from personas[].jobs[].privileges, personas[].additionalPrivileges and roleGrants[].privileges, personas first. `role` is the persona's name, or the+ * grant's role name (its id when it names the role by id). A privilege that grants nothing — no table, no access — is not a source. `scope` defaults to+ * `user`, as it does in the spec.+ * @returns {Map<string, { via: string, role: string, access: string[], scope: string }[]>}+ */+function tablePrivileges(spec) {+ const s = isObject(spec) ? spec : {};+ const sources = new Map();+ const add = (privilege, via, role) => {+ if (!isObject(privilege) || !filled(privilege.entity)) return;+ const access = arr(privilege.access).filter((a) => typeof a === 'string' && a);+ if (!access.length) return;+ const key = lc(privilege.entity.trim());+ if (!sources.has(key)) sources.set(key, []);+ sources.get(key).push({ via, role, access, scope: filled(privilege.scope) ? privilege.scope : 'user' });+ };+ for (const persona of arr(s.personas)) {+ if (!isObject(persona)) continue;+ const name = canonicalPersonaName(persona);+ const role = typeof name === 'string' ? name : '';+ for (const job of arr(persona.jobs)) {+ if (isObject(job)) for (const privilege of arr(job.privileges)) add(privilege, 'persona', role);+ }+ for (const privilege of arr(persona.additionalPrivileges)) add(privilege, 'persona', role);+ }+ for (const grant of arr(s.roleGrants)) {+ if (!isObject(grant)) continue;+ const role = filled(grant.role) ? grant.role.trim() : (filled(grant.roleId) ? grant.roleId.trim() : '');+ for (const privilege of arr(grant.privileges)) add(privilege, 'roleGrant', role);+ }+ return sources;+}++/** The introduced tables no persona and no roleGrants[] entry grants a privilege on, once each, in the order the spec lists them. */+function uncoveredTables(spec) {+ const covered = tablePrivileges(spec);+ const seen = new Set();+ return introducedTables(spec).filter((name) => {+ const key = lc(name.trim());+ if (seen.has(key)) return false;+ seen.add(key);+ return !covered.has(key);+ });+}++// --- the personas' share of who can open the app ----------------------------------------------------------------------------------------------++/**+ * Which personas get the app and which opt out, by the names their roles are made with (the canonical, trimmed ones: once each, in any letter case, in spec+ * order). The build associates a persona's role with the app unless `appAccess` is `false`, and REMOVES the association of a role whose persona opts out — sdk-build.js,+ * the security phase: `persona.appAccess !== false`, else the dissociate. So "this spec authors roles" is not "this spec gives the app to roles": every sentence about+ * what a build associates follows this, not whether there are personas.+ * @returns {{ gets: string[], optedOut: string[] }}+ */+function personaAppAccess(spec) {+ const out = { gets: [], optedOut: [] };+ const seen = new Set();+ for (const p of arr(isObject(spec) ? spec.personas : [])) {+ if (!isObject(p)) continue;+ const name = canonicalPersonaName(p);+ if (!filled(name) || seen.has(lc(name))) continue;+ seen.add(lc(name));+ (p.appAccess === false ? out.optedOut : out.gets).push(name);+ }+ return out;+}++// "the role of persona `A`", "the roles of personas `A` and `B`".+function rolesOfPersonas(names) {+ const many = names.length > 1;+ return `the role${many ? 's' : ''} of persona${many ? 's' : ''} ${list(names.map((n) => `\`${n}\``))}`;+}++// --- what the lint and the document say ---------------------------------------------------------------------------------------------------++/**+ * Who can open the app, as far as the SPEC can say: first what a build does for the personas (their roles get the app, or lose it), then what it leaves to the+ * environment — the sentence the lint (a spec with no personas) and the document (an answer from the environment that is missing or unreadable) share. With a mark+ * of an existing app it says the spec most likely edits one, whose other roles a build leaves alone; without one it is a condition — nothing in a spec proves the app+ * is new.+ */+function appAccessCondition(spec) {+ const { gets, optedOut } = personaAppAccess(spec);+ const marks = existingAppMarkers(spec);+ const hasPersonas = gets.length > 0 || optedOut.length > 0;+ let personas = '';+ if (gets.length && optedOut.length) personas = `A build associates the app with ${rolesOfPersonas(gets)}, and removes it from ${rolesOfPersonas(optedOut)} (\`appAccess: false\`) if it has it.`;+ else if (gets.length) personas = `A build associates the app with ${rolesOfPersonas(gets)}.`;+ else if (optedOut.length) personas = `No persona gets the app: a build removes the app from ${rolesOfPersonas(optedOut)} (\`appAccess: false\`) if it has it.`;+ let rest;+ if (marks.length) {+ const download = `It carries ${list(marks)}, which a download writes, so it most likely edits an app that already exists — and a build`;+ rest = hasPersonas+ ? `${download} changes the roles associated with an existing app only for its personas: who else can open the app is decided by the environment, not by this spec.`+ : `${download} leaves the roles associated with an existing app as they are: who can open the app is decided by the environment, not by this spec.`;+ } else {+ rest = hasPersonas+ ? 'Beyond that, a new app is associated with the System Administrator role only, and an existing app keeps the roles it has.'+ : 'If the app is new, it is associated with the System Administrator role only, so users without a maker-level role cannot open it until a role is associated with it (personas[] does that); if it already exists, it keeps the roles it has.';+ }+ return personas ? `${personas} ${rest}` : rest;+}++/** The lint's warning for a spec with no personas[]: the jobs are not recorded, no role is authored, and what that does and does not say about access. */+function noPersonasWarning(spec) {+ const advice = existingAppMarkers(spec).length+ ? 'Add personas[] only for roles this spec should own (a persona\'s role is converged to exactly the privileges declared, and the build refuses a role it did not author); to give an existing role access to a new table, add a roleGrants[] entry.'+ : 'Capture who uses this app and what each of them needs to get done; to give an existing role access to a new table without redefining the role, add a roleGrants[] entry instead of a persona.';+ return `no personas[] — no jobs-to-be-done are recorded and this spec authors no security role. ${appAccessCondition(spec)} ${advice}`;+}++// The table names a sentence shows: up to five, then a count.+function tableNames(names, quote) {+ const shown = names.slice(0, 5).map((n) => `${quote}${n}${quote}`);+ return list(names.length > 5 ? [...shown, `${names.length - 5} more`] : shown);+}++/** The warning (lint and design gaps) for new tables nothing grants a privilege on. `names` is uncoveredTables(spec), not empty. */+function uncoveredTablesWarning(names) {+ const one = names.length === 1;+ const it = one ? 'it' : 'them';+ const subject = one ? `new table ${tableNames(names, "'")} has` : `${names.length} new tables (${tableNames(names, "'")}) have`;+ return `${subject} no access declared: no persona job or additionalPrivileges entry and no roleGrants[] entry grants a privilege on ${it}, so a user of a role that already exists cannot use ${it} until a grant is made. Add a roleGrants[] entry for each existing role that needs ${it} (it only adds privileges), or declare the access on a persona's job.`;+}++/** The design document's callout for the same tables (the heading it sits under says "no access declared"). */+function uncoveredTablesCallout(names) {+ const one = names.length === 1;+ const it = one ? 'it' : 'them';+ const subject = one ? `${tableNames(names, '`')} is` : `${tableNames(names, '`')} are`;+ return `${subject} introduced by this spec, but no persona and no \`roleGrants[]\` entry grants a privilege on ${it}, so a user of a role that already exists cannot use ${it} until a grant is made. Add a \`roleGrants[]\` entry for each existing role that needs ${it} (it only adds privileges), or declare the access on a persona's job.`;+}++// --- what the environment says ----------------------------------------------------------------------------------------------------------------++/**+ * What a read of the environment (lib/app-roles.js `appRolesOf`) means for this spec — ONE model, from which the document and its warnings take every sentence, so+ * that what they say of who gets the app, of which role is which and of whether the app is administrator-only cannot differ.+ * { state: 'unread', personas } the environment was not asked (no --env), or the answer is not one this knows+ * { state: 'absent', appUnique, personas } neither layer has the app: a build creates it+ * { state: 'unreadable', appUnique, reason, personas } nothing is known of its roles — a refusal, an answer that holds no list, a row that names no role+ * { state: 'read', appUnique, personas, roles, grants } what the app has+ * `personas` is personaAppAccess(spec): the personas that get the app and those that opt out.+ * `roles`: { roleId, name, managed, sources }, one per associated role, in the order of the answer. `sources` says what in the spec may be that role:+ * { kind: 'roleGrant', label, by: 'id', certain: true } a roleGrants[] entry that names this role's id: the one case it IS the role the grant extends+ * { kind: 'roleGrant', label, by: 'name', certain: false } an entry that names only a name — a role is one of (name, business unit), the answer carries no business+ * unit, and the build resolves the grant's role by name AND business unit, so any role of that name may be it+ * { kind: 'persona', label, getsApp, certain: false } a persona of that name: its role is made in the persona's business unit, so it too is matched by name only+ * `getsApp` is what the persona asks of the app; the build keeps the association of one that gets it and removes that of one that opts out.+ * `grants`: one per roleGrants[] entry that names a role, { label, by: 'id' | 'name', status, candidates: [{ roleId, name }] }. `status`:+ * 'associated' named by id, and that role is associated with the app — certain+ * 'maybe' named by name, and every candidate has that name: which of them (if any) is the grant's role the answer cannot say+ * 'not-associated' no associated role has that id (or that name) — certain: such a grant gives its role the table, not the app+ * A role is never claimed as a grant's or a persona's by a match of names alone. A match by id is exact, and a grant that gives an id is matched by it alone.+ */+function appAccessModel(spec, appAccess) {+ const personas = personaAppAccess(spec);+ if (!isObject(appAccess)) return { state: 'unread', personas };+ const appUnique = typeof appAccess.appUnique === 'string' ? appAccess.appUnique : '';+ if (appAccess.state === 'absent') return { state: 'absent', appUnique, personas };+ if (appAccess.state === 'unreadable') return { state: 'unreadable', appUnique, reason: filled(appAccess.reason) ? appAccess.reason : 'unknown', personas };+ if (appAccess.state !== 'read') return { state: 'unread', personas };+ // An answer is a list of roles, every one of them a role: a list that is none, or has a row that names no role, is not read as a list with nothing in it.+ if (!Array.isArray(appAccess.roles)) return { state: 'unreadable', appUnique, reason: 'the answer held no list of roles', personas };+ if (appAccess.roles.some((r) => !isObject(r) || !filled(r.roleId))) return { state: 'unreadable', appUnique, reason: 'an association row names no role', personas };++ const s = isObject(spec) ? spec : {};+ const named = arr(s.personas).filter(isObject)+ .map((p) => ({ name: canonicalPersonaName(p), getsApp: p.appAccess !== false }))+ .filter((p) => filled(p.name));+ const wanted = arr(s.roleGrants).filter(isObject).map((g) => {+ if (filled(g.roleId)) return { by: 'id', key: lc(g.roleId.trim()), label: g.roleId.trim() };+ if (filled(g.role)) return { by: 'name', key: lc(g.role.trim()), label: g.role.trim() };+ return null;+ }).filter(Boolean);+ const isTarget = (grant, role) => (grant.by === 'id' ? grant.key === lc(role.roleId) : grant.key === lc(role.name));++ const roles = appAccess.roles.map((r) => {+ const role = { roleId: r.roleId, name: typeof r.name === 'string' ? r.name : '' };+ const sources = [];+ for (const grant of wanted) {+ if (isTarget(grant, role)) sources.push({ kind: 'roleGrant', label: grant.label, by: grant.by, certain: grant.by === 'id' });+ }+ for (const persona of named) {+ if (role.name && lc(persona.name) === lc(role.name)) sources.push({ kind: 'persona', label: persona.name, getsApp: persona.getsApp, certain: false });+ }+ return { ...role, managed: r.managed === true, sources };+ });+ const grants = wanted.map((grant) => {+ const candidates = roles.filter((role) => isTarget(grant, role)).map((role) => ({ roleId: role.roleId, name: role.name }));+ const status = !candidates.length ? 'not-associated' : (grant.by === 'id' ? 'associated' : 'maybe');+ return { label: grant.label, by: grant.by, status, candidates };+ });+ return { state: 'read', appUnique, personas, roles, grants };+}++module.exports = {+ existingAppMarkers,+ introducedTables,+ tablePrivileges,+ uncoveredTables,+ personaAppAccess,+ rolesOfPersonas,+ appAccessCondition,+ noPersonasWarning,+ uncoveredTablesWarning,+ uncoveredTablesCallout,+ appAccessModel,+};diff --git a/plugins/model-apps/scripts/lib/app-header-text.js b/plugins/model-apps/scripts/lib/app-header-text.jsindex 6f1efaa7f..51715e36c 100644--- a/plugins/model-apps/scripts/lib/app-header-text.js+++ b/plugins/model-apps/scripts/lib/app-header-text.js@@ -3,22 +3,23 @@//// Both are String columns of the app module table// (https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule). The build edits them on the workspace copy of-// an existing app (sdk-build.js `applyAppHeaderText`) and never edits a text that is not plain — a text per language held as an LCID map, a list, a-// number — because the SDK writes the header from the whole copy and cannot be told to leave one field out. That hold is on the COPY, though, and the-// SDK decides for itself whether the header is written. Its push of an app makes two requests about the header (the vendored bundle, `pushArtifact('app')`):+// an existing app (sdk-build.js `applyAppHeaderText`), never edits a text that is not plain — a text per language held as an LCID map, a list, a+// number — and takes such a text off the copy right before it pushes it (`pushAppHeader`, `removeElement`), which the SDK reads as "neither compared nor+// written" (cds-maker-sdk 9a0c9f03). That is a hold on the COPY, though, and the SDK decides for itself what it writes. Its push of an app makes two requests+// about the header (the vendored bundle, `pushArtifact('app')`)://// GET …/api/data/v9.0/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1// (the commas and the spaces are percent-encoded on the wire)// PATCH …/api/data/v9.0/appmodules(<id>)?$select=appmoduleid If-Match: W/"<the row's token>"-// { "name": "Help Desk", "description": "Track tickets" } (plus "aiappdescription" when the copy carries one)+// { "description": "Track tickets" } (only the texts that differ from the row's: `name`, `description`, `aiappdescription`)//-// The PATCH is made when that comparison read finds the copy's header different from the row's — and also when the read CANNOT be made: the SDK's "write-// needed" flag starts true and only a 2xx answer sets it, so a read that answers 503 or 403, or that throws, leaves it true; a 200 with no row is compared-// with an empty header, which differs, so it comes out true as well. The header is then written from the copy as it is, a text that is not plain included.-// "The build made no header edit" has therefore never meant "no header PATCH". The one place that sees-// every request is the client, so the last line of defence is there: a PATCH of an app module row whose body carries a `name` or a `description` that is not-// a string is not sent. It fails before any byte leaves, with APP_HEADER_NOT_PLAIN_TEXT. (Pinned against the real bundle, for each way the comparison read-// can fail, in tests/app-header-text-real-bundle.test.js.)+// The PATCH carries each text of the copy that differs from the row the comparison read answered — and, when that read CANNOT be made, EVERY text the copy+// holds: the SDK's "write needed" flag starts true and only a 2xx answer sets it, so a read that answers 503 or 403, or that throws, leaves it true, and a 200+// with no row is compared with an empty header, which differs. A text that is not on the copy is neither compared nor written, so a build that took the text+// that is not plain off the copy never offers it. But a push the build did not clean — the page backend's push of the app copy it fetched, say — can carry+// one, and "the build edited no text" has never meant "no header PATCH". The one place that sees every request is the client, so the last line of defence is+// there: a PATCH of an app module row whose body carries a `name` or a `description` that is not a string is not sent. It fails before any byte leaves, with+// APP_HEADER_NOT_PLAIN_TEXT. (Pinned against the real bundle, for each way the comparison read can fail, in tests/app-header-text-real-bundle.test.js.)//// THE OTHER DOORS. The SDK's own `patch` is not the only way that PATCH can leave the process. `sdk.dataverse` is a public surface, and three more of its methods reach the client with a body this module// does not see as an object:diff --git a/plugins/model-apps/scripts/lib/app-roles.js b/plugins/model-apps/scripts/lib/app-roles.jsnew file mode 100644index 000000000..d8fc56f02--- /dev/null+++ b/plugins/model-apps/scripts/lib/app-roles.js@@ -0,0 +1,98 @@+'use strict';+// What the environment says about who can OPEN a model-driven app: the security roles associated with it — the N:N `appmoduleroles` relationship, the+// rows the app launcher reads to decide which apps a user without a maker-level role sees. READ-ONLY: nothing here writes, and every failure is an+// answer ({ ok: false, reason } / { state: 'unreadable' }), never a throw, because both callers report what they could not read instead of failing on it.+//+// verify-model-app.js appIdFor / appRoleIdsFor — the ids of the roles a deployed app has, to prove the app is associated with the roles its personas author.+// They read as they always did: the published layer, and an answer that carries no list is read as no ids (verify then FAILS the persona's+// check, the safe side).+// write-app-spec-doc.js appRolesOf — the roles (by name) an app has, for the design document: an extension of an app that already has roles+// says nothing about them in its spec, and the document is where a reviewer is told what they are. It states what it read, so it is+// strict where verify is lenient: see below.+//+// What the document reads must be an ANSWER, never a guess.+// * The app is looked up in the SAVED layer — `resolveArtifact('app', { uniqueName })`, the SDK's own lookup, which the teardown deletes an app by and which finds+// a draft (lib/sitemap-pages.js neverPublishedNavigation) — and not by the published-layer probe the build and verify make (`findArtifact`, `queryRecords`): an+// app that was saved and never published has no published row, and "does not exist yet" is a statement about the environment that probe cannot make. An app is+// absent only when the saved layer, which holds the published apps too, has none.+// * The roles are read through collectionRows (lib/app-components.js), the plugin's one reader of a paged collection: a refusal, an answer that is no list, a link+// that is no link and a page that repeats are each an error, never a shorter list, and the continuation is followed to its end. Every row must then name a role.+// Only a list with nothing in it says the app has no role; a draft whose roles the platform will not read (HTTP 404 by id for an app with no published row), a+// refused read and a malformed answer are each "unreadable" — which the document words as "not checked".+//+// The relationship is read directly (`GET /appmodules(<id>)/appmoduleroles_association`): the SDK has associate and disassociate helpers for it+// and no modeled read.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule+// https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/share-model-driven-app+const { odataLit } = require('./odata.js');+const { compareText } = require('./compare-text.js');+const { collectionRows } = require('./app-components.js');++// A failure as the one line a caller shows: the message, cut at 200 characters (an error text can carry a whole response body).+const reasonOf = (err) => ((err && err.message) ? String(err.message).slice(0, 200) : 'read failed');++// The association rows of an app, with the role columns in `select` (the navigation property answers role rows).+const associationPath = (appId, select) => `/appmodules(${appId})/appmoduleroles_association?$select=${select.join(',')}`;++// Resolve the app module id from its unique name, in the published layer. Undefined when there is no such app there.+async function appIdFor(sdk, appUnique) {+ const rows = await sdk.queryRecords('appmodule', { select: ['appmoduleid'], filter: `uniquename eq '${odataLit(appUnique)}'`, top: 1 });+ return rows && rows[0] && rows[0].appmoduleid;+}++// verify's view: the ids of the roles the deployed app has, lower-cased, so verify proves the app<->role rows the launcher uses rather than inferring+// access from a role's existence or from the build's result. { ok: true, roleIds } | { ok: false, reason }. Unchanged from before the design document read the+// same relationship — including what it makes of an answer that carries no list — and kept apart from appRolesOf's strictness on purpose.+async function appRoleIdsFor(sdk, appUnique) {+ try {+ const appId = await appIdFor(sdk, appUnique);+ if (!appId) return { ok: false, reason: `app '${appUnique}' could not be resolved` };+ if (!sdk.dataverse || typeof sdk.dataverse.get !== 'function') return { ok: false, reason: 'SDK dataverse reader is unavailable' };+ const res = await sdk.dataverse.get(associationPath(appId, ['roleid']));+ if (!res || res.status < 200 || res.status >= 300) return { ok: false, reason: `HTTP ${res && res.status}` };+ return {+ ok: true,+ roleIds: ((res.body && res.body.value) || [])+ .map((r) => r && r.roleid)+ .filter(Boolean)+ .map((id) => String(id).toLowerCase()),+ };+ } catch (err) {+ return { ok: false, reason: reasonOf(err) };+ }+}++/**+ * The roles associated with the app `appUnique`, as the environment holds them now.+ * { state: 'read', appUnique, appId, roles: [{ roleId, name, managed }] } `roles` by name (lib/compare-text.js), then id: the same order on every run+ * { state: 'absent', appUnique } neither layer has an app of that unique name, so a build creates it+ * { state: 'unreadable', appUnique, reason } the app or its roles could not be read: nothing is known about them+ * `reason` is `HTTP <status>` for a refusal and the error's own words otherwise. A role with no name is listed with the empty one; a row with no role id is not a+ * role, and an answer that holds one is unreadable.+ * @param {object} sdk the bundled SDK (lib/maker-sdk.js)+ * @param {string} appUnique the app's unique name+ */+async function appRolesOf(sdk, appUnique) {+ const unreadable = (reason) => ({ state: 'unreadable', appUnique, reason });+ try {+ if (typeof sdk.resolveArtifact !== 'function') return unreadable('the SDK has no app lookup');+ const found = await sdk.resolveArtifact('app', { uniqueName: appUnique });+ if (!Array.isArray(found)) return unreadable('the app lookup answered no list');+ if (!found.length) return { state: 'absent', appUnique };+ const appId = found[0] && typeof found[0].id === 'string' ? found[0].id.trim() : '';+ if (!appId) return unreadable('the app lookup answered a row with no id');+ if (!sdk.dataverse || typeof sdk.dataverse.get !== 'function') return unreadable('SDK dataverse reader is unavailable');+ const rows = await collectionRows(sdk.dataverse, associationPath(appId, ['roleid', 'name', 'ismanaged']), 'the association rows');+ const roles = [];+ for (const row of rows) {+ if (!row || typeof row !== 'object' || typeof row.roleid !== 'string' || !row.roleid) return unreadable('an association row names no role');+ roles.push({ roleId: row.roleid.toLowerCase(), name: typeof row.name === 'string' ? row.name : '', managed: row.ismanaged === true });+ }+ roles.sort((a, b) => compareText(a.name, b.name) || compareText(a.roleId, b.roleId));+ return { state: 'read', appUnique, appId, roles };+ } catch (err) {+ return unreadable(err && err.statusCode ? `HTTP ${err.statusCode}` : reasonOf(err));+ }+}++module.exports = { appIdFor, appRoleIdsFor, appRolesOf };diff --git a/plugins/model-apps/scripts/lib/app-spec-doc.js b/plugins/model-apps/scripts/lib/app-spec-doc.jsindex 190b24f74..6bc0d4a9f 100644--- a/plugins/model-apps/scripts/lib/app-spec-doc.js+++ b/plugins/model-apps/scripts/lib/app-spec-doc.js@@ -17,6 +17,7 @@const lc = (s) => String(s || '').toLowerCase();const { labelText, lookupLabelFor } = require('./app-spec.js');+const { appAccessCondition, appAccessModel, rolesOfPersonas, uncoveredTables, uncoveredTablesCallout } = require('./app-access.js');// Every collection read below goes through these. The renderer runs against WORK-IN-PROGRESS specs// during authoring — a half-typed `jobs: "x"`, a null entry left by an edit, a `dataSources` written@@ -89,10 +90,12 @@ function jobsSection(spec) {const personas = objs(spec.personas);const out = ['## Jobs to be done', ''];if (!personas.length) {+ // All the spec can say here is what it does NOT author: who can open the app is decided by the roles associated with it, and a spec with no+ // personas[] leaves those as they are (the Security section says what that means, and what the environment holds when it was read).out.push(- '> ⚠ No `personas[]` were captured, so this app has no recorded jobs-to-be-done and no security',- '> roles — it will open only for system administrators. Capture who uses the app and what each',- "> of them needs to get done, then regenerate this document.",+ '> ⚠ No `personas[]` were captured, so this app has no recorded jobs-to-be-done and this spec authors no security role.',+ '> That does not say who can open the app — see **Security**. Capture who uses the app and what each of them needs',+ '> to get done, then regenerate this document.','');return out;@@ -324,51 +327,151 @@ const scopeRank = (s) => {return r === undefined ? 0 : r;};-function security(spec) {+// The privileges a list declares, per table and per ACCESS: table -> access -> most permissive declared scope.+function unionPrivileges(privileges) {+ const byEntity = new Map();+ for (const pr of privileges) {+ if (!pr || typeof pr !== 'object') continue;+ const entity = lc(pr.entity);+ if (!entity) continue;+ let byAccess = byEntity.get(entity);+ if (!byAccess) { byAccess = new Map(); byEntity.set(entity, byAccess); }+ const scope = String(pr.scope || 'user');+ for (const a of Array.isArray(pr.access) ? pr.access : []) {+ const prev = byAccess.get(a);+ if (prev === undefined || scopeRank(scope) > scopeRank(prev)) byAccess.set(a, scope);+ }+ }+ return byEntity;+}++// The rows of a privilege table, one per (table, scope). The accesses that share a scope are grouped so the common case stays one row, while a genuine+// split (read@organization + write@user) renders as two — visibly different access levels.+function privilegeRows(byEntity) {+ const rows = [];+ for (const [entity, byAccess] of byEntity) {+ const byScope = new Map();+ for (const [access, scope] of byAccess) {+ if (!byScope.has(scope)) byScope.set(scope, []);+ byScope.get(scope).push(access);+ }+ const scopes = [...byScope.keys()].sort((a, b) => scopeRank(b) - scopeRank(a));+ for (const scope of scopes) rows.push({ entity, access: byScope.get(scope).join(', '), scope });+ }+ return rows;+}++// What in the spec may be an associated role, for the table of the roles the app has. A role is one of (name, business unit) and the read carries no business unit,+// so a grant that names only a name, and a persona (whose role is made in its own business unit), match a role by name alone: "may be", never "is". Only a grant that+// names the role's id says what the role is — and what a build does for a persona is said of the persona's role ("if it is"), not of the role a name happens to match.+function roleSources(role) {+ if (!role.sources.length) return 'not touched by this spec';+ return role.sources.map((s) => {+ if (s.kind === 'roleGrant') return s.certain ? 'extended by `roleGrants[]`' : 'may be the role `roleGrants[]` extends (matched by name only)';+ return s.getsApp+ ? `may be the role of persona \`${s.label}\` (matched by name); if it is, a build keeps this association`+ : `may be the role of persona \`${s.label}\` (matched by name, \`appAccess: false\`); if it is, a build removes this association`;+ }).join('; ');+}++// WHO CAN OPEN THE APP, kept apart from who can use a table. The roles associated with the app decide which users see it. A build associates the roles of the+// personas that get the app (`appAccess` is not false), removes the association of those that opt out, and leaves every other role's as it is; the SPEC alone says+// nothing more, and — when the environment was read (--env) — the ENVIRONMENT says what the app has. Every sentence here follows the model (lib/app-access.js+// appAccessModel): which personas get the app, which role is which, whether the app is known to be administrator-only. That claim is made only on the evidence of a+// read — an app the environment has with no role associated with it, or one neither layer has yet — and only while no persona gets the app.+function appAccessSection(spec, model, opts) {+ const { gets, optedOut } = model.personas;+ const out = ['### Access to the app', ''];+ const where = opts.envUrl ? text(opts.envUrl) : 'the environment';+ const app = model.appUnique ? `The app \`${model.appUnique}\`` : 'The app';+ // Why a build associates no role of its own with the app, when no persona gets it.+ const noneBecause = optedOut.length ? 'its personas are data-only: `appAccess: false`' : 'it authors no role';+ if (model.state === 'read' && model.roles.length) {+ out.push(`${app} already exists in ${where} and these roles are associated with it, so their users can open it:`, '', '| Role | In this spec |', '|---|---|');+ for (const r of model.roles) out.push(`| ${cell(r.name || r.roleId)} | ${cell(roleSources(r))} |`);+ const changes = [];+ if (gets.length) changes.push(`associates the app with ${rolesOfPersonas(gets)}`);+ if (optedOut.length) changes.push(`removes it from ${rolesOfPersonas(optedOut)} (\`appAccess: false\`) where it is associated`);+ const build = changes.length ? `A build with this spec ${changes.join(', ')}, and leaves every other association as it is.` : 'A build with this spec leaves these associations as they are.';+ out.push('', `${build} Opening the app is one thing and using a table another: the privileges on the tables this spec introduces are declared separately, below.`, '');+ } else if (model.state === 'read') {+ out.push(`${app} exists in ${where}, but no role is associated with it, so only administrators and other makers (System Customizer, Environment Maker) can open it. ${gets.length ? `A build with this spec associates the app with ${rolesOfPersonas(gets)}.` : `This spec associates none with it (${noneBecause}), so that does not change.`}`, '');+ } else if (model.state === 'absent') {+ out.push(gets.length+ ? `${app} does not exist in ${where} yet. A build creates it and associates the System Administrator role with it, and ${rolesOfPersonas(gets)}.`+ : `${app} does not exist in ${where} yet. A build creates it and associates the System Administrator role with it; this spec associates no other role (${noneBecause}), so users without a maker-level role cannot open it until a role is associated with it.`, '');+ } else if (model.state === 'unreadable') {+ out.push(`> ⚠ The roles associated with the app could not be read from ${where} (${text(model.reason)}), so who can open it was not checked.`, '', appAccessCondition(spec), '');+ } else {+ out.push(appAccessCondition(spec), '', 'The roles associated with the app were not read: pass `--env <envUrl>` to read them.', '');+ }+ return out;+}++// A grant that names a role only by name, beside the roles of that name the app has: which of them the grant extends, if any, is for the business unit to say.+function namedGrantNote(grant) {+ const n = grant.candidates.length;+ const have = n === 1 ? '1 associated role has that name' : `${n} associated roles have that name`;+ const ids = `${n === 1 ? 'id' : 'ids'} ${grant.candidates.map((c) => text(c.roleId)).join(', ')}`;+ return `Role "${text(grant.label)}" is named without a role id: ${have} (${ids}), and roles are per business unit, so ${n === 1 ? 'it may not be' : 'at most one of them is'} the role this grant extends. Pin the role with \`roleId\` to be sure.`;+}++// roleGrants[]: privileges ADDED to roles that already exist. Shown with the role they extend — the persona sections above show the roles this spec owns — and,+// when the environment was read, with how each grant stands to the roles the app has: a grant gives a role a table, not the app.+function roleGrantsSection(spec, model) {+ const grants = objs(spec.roleGrants);+ if (!grants.length) return [];+ const rows = [];+ for (const g of grants) {+ const role = typeof g.role === 'string' && g.role.trim() ? g.role.trim() : (typeof g.roleId === 'string' ? g.roleId.trim() : '');+ for (const r of privilegeRows(unionPrivileges(arr(g.privileges)))) rows.push({ role, ...r });+ }+ const out = ['### Roles extended by `roleGrants[]`', '', 'These roles already exist. The build ADDS the privileges below and removes none, and a grant does not associate the role with the app. After a build, `verify-model-app.js` checks that each role holds them.', ''];+ if (rows.length) {+ out.push('| Role | Table | Access | Scope |', '|---|---|---|---|');+ for (const r of rows) out.push(`| ${cell(r.role)} | ${cell(r.entity)} | ${cell(r.access)} | ${cell(r.scope)} |`);+ } else {+ out.push('_No privileges declared._');+ }+ out.push('');+ if (model.state === 'read') {+ for (const g of model.grants) {+ if (g.status === 'not-associated') out.push(`> ⚠ Role "${text(g.label)}" is not among the roles associated with the app, so its users get these privileges but may not be able to open the app.`, '');+ else if (g.status === 'maybe') out.push(namedGrantNote(g), '');+ }+ }+ return out;+}++function security(spec, opts) {const personas = Array.isArray(spec.personas) ? spec.personas.filter((p) => p && typeof p === 'object') : [];- if (!personas.length) return [];+ const model = appAccessModel(spec, opts.appAccess);const out = ['## Security', ''];+ if (!personas.length) out.push('This spec authors no security role (`personas[]` is empty).', '');for (const p of personas) {out.push(`### Role: ${text(p.persona)}`, '');out.push(p.appAccess === false ? '_Data-only — the app is **not** granted to this role._' : 'The app is granted to this role, so it opens for this persona.', '');- // entity -> access -> most permissive declared scope- const byEntity = new Map();- const add = (pr) => {- if (!pr || typeof pr !== 'object') return;- const entity = lc(pr.entity);- if (!entity) return;- let byAccess = byEntity.get(entity);- if (!byAccess) { byAccess = new Map(); byEntity.set(entity, byAccess); }- const scope = String(pr.scope || 'user');- for (const a of Array.isArray(pr.access) ? pr.access : []) {- const prev = byAccess.get(a);- if (prev === undefined || scopeRank(scope) > scopeRank(prev)) byAccess.set(a, scope);- }- };+ const privileges = [];for (const j of Array.isArray(p.jobs) ? p.jobs : []) {- if (j && typeof j === 'object') for (const pr of Array.isArray(j.privileges) ? j.privileges : []) add(pr);+ if (j && typeof j === 'object') privileges.push(...(Array.isArray(j.privileges) ? j.privileges : []));}- for (const pr of Array.isArray(p.additionalPrivileges) ? p.additionalPrivileges : []) add(pr);-- if (byEntity.size) {+ privileges.push(...(Array.isArray(p.additionalPrivileges) ? p.additionalPrivileges : []));+ const rows = privilegeRows(unionPrivileges(privileges));+ if (rows.length) {out.push('| Table | Access | Scope |', '|---|---|---|');- for (const [entity, byAccess] of byEntity) {- // Group the accesses that share a scope so the common case stays one row, while a genuine- // split (read@organization + write@user) renders as two — visibly different access levels.- const byScope = new Map();- for (const [access, scope] of byAccess) {- if (!byScope.has(scope)) byScope.set(scope, []);- byScope.get(scope).push(access);- }- const scopes = [...byScope.keys()].sort((a, b) => scopeRank(b) - scopeRank(a));- for (const scope of scopes) out.push(`| ${cell(entity)} | ${cell(byScope.get(scope).join(', '))} | ${cell(scope)} |`);- }+ for (const r of rows) out.push(`| ${cell(r.entity)} | ${cell(r.access)} | ${cell(r.scope)} |`);out.push('');} else {out.push('_No privileges declared._', '');}}+ // The persona sections already say, per role, whether the app is granted to it; the section on the app is for what they cannot: a spec that gives the app to+ // no role, and what the environment says.+ if ((!model.personas.gets.length && !model.personas.optedOut.length) || model.state !== 'unread') out.push(...appAccessSection(spec, model, opts));+ out.push(...roleGrantsSection(spec, model));+ const withoutAccess = uncoveredTables(spec);+ if (withoutAccess.length) out.push('### Tables with no access declared', '', `> ⚠ ${uncoveredTablesCallout(withoutAccess)}`, '');return out;}@@ -408,7 +511,7 @@ function aiFeatures(spec) {/*** Render an App Spec as a readable Markdown design document.* @param {object} spec migrated App Spec- * @param {object} [opts] { envUrl }+ * @param {object} [opts] { envUrl, appAccess } `appAccess` is the answer of lib/app-roles.js `appRolesOf` for the app when the environment was read, else absent* @returns {string} markdown*/function renderAppSpecDoc(spec, opts = {}) {@@ -420,7 +523,7 @@ function renderAppSpecDoc(spec, opts = {}) {...dataModel(s),...surfaces(s),...navigation(s),- ...security(s),+ ...security(s, opts),...sampleData(s),...designContract(s),...aiFeatures(s),diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex ef35ed79a..d26e83da8 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -929,12 +929,13 @@ function askedPrimaryNameLength(entity) {}// Whether an alternate key is over its table's primary name column while the spec asks that column for a length (askedPrimaryNameLength):-// the key is then in the way of the length. The platform validates a key when it is created, and a key may hold at most 900 bytes — 2 for-// each character of a text column.+// the key is then in the way of the length. The platform validates a key when it is created, and a key may hold at most 1,700 bytes+// (KEY_BYTES_LIMIT) — 2 for each character of a text column.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys// A new table's name column is created asking for a length, but some environments make it 850 characters (1,700 bytes) whatever is-// asked (DEFAULT_PRIMARY_NAME_LENGTH, lib/entity-provision.js), so a key over it can be created only once the build has set the-// length the spec asks for. Matched case-insensitively: a column's logical name is its schema name in lower case.+// asked (DEFAULT_PRIMARY_NAME_LENGTH, lib/entity-provision.js) — the whole of what a key may hold, so a key over it and another column+// can be created only once the build has set the length the spec asks for (keyHasRoomOnlyAfterLength). Matched case-insensitively: a+// column's logical name is its schema name in lower case.function keyNeedsNameLength(entity, key) {if (askedPrimaryNameLength(entity) === undefined || !key || !Array.isArray(key.columns)) return false;const name = String(entity.primaryAttribute.schemaName || '').toLowerCase();@@ -959,8 +960,10 @@ function labelGoesOutInOneLanguage(value) {//// The build sets the length LAST in the phase: the SDK's update reads the column with its labels, and a read that carries labels ahead of// a create that carries several languages is what makes Dataverse keep only the base one. A key with one label has nothing for such a read-// to strip, so it may follow the step; a key labelled in several languages keeps the place it has always had, ahead of it — and where the-// platform then refuses it for the length of its column, the build says so (alternateKeyAheadOfLength, lib/entity-provision.js).+// to strip, so it may follow the step; a key labelled in several languages keeps the place it has always had, ahead of it — except where+// the environment made the name column too long for the key to fit beside the others, which only the environment can say+// (keyHasRoomOnlyAfterLength, decided by the build from the length it reads) — and where the platform then refuses it for the length of+// its column, the build says so (alternateKeyAheadOfLength, lib/entity-provision.js).//// It does not depend on the language the build writes in, so the dry run and the apply cannot disagree about it however either is given one.//@@ -971,6 +974,83 @@ function keyWaitsForNameLength(entity, key) {return keyNeedsNameLength(entity, key) && labelGoesOutInOneLanguage(key.displayName);}+// The most bytes an alternate key may hold. The platform's own answer to a key that is too large names the limit — HTTP 400, code 0x80060895:+// { "error": { "code": "0x80060895", "message": "Index size exceeded the size limit of 1700 bytes. The key is too large. Try removing some columns or making the strings in string columns shorter." } }+// That was measured at 1,700 bytes: a key over a name column of 850 characters (2 bytes each, the most a name column may have: PRIMARY_NAME_MAX_LENGTH)+// alone was accepted, and one that held any other column beside it — even one of a single character — was refused. Microsoft Learn documents 900+// bytes, so this number is what one environment answered, not a promise about all of them: the build uses it only to know that a key CANNOT fit in a+// place (keyHasRoomOnlyAfterLength) — never to refuse one, which the platform does.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys+const KEY_BYTES_LIMIT = 1700;++// The length the SDK gives a text column it is asked to create without one. The attribute it sends for a `string` and for an `autonumber` column+// alike is built with `MaxLength: t.maxLength ?? 100` (vendor/cds-maker-sdk.cjs, for createColumn and createColumns).+const SDK_TEXT_MAX_LENGTH = 100;++// The `maxLength` the build passes on to the SDK when it creates a column of the spec, or undefined when it passes none: only a column that names its+// type `Text` or `Memo` carries one, and only a value that is truthy, as written — the platform judges it. So an auto-number column, and a column that+// gives no type (which the build creates as text all the same), are made SDK_TEXT_MAX_LENGTH characters long whatever `maxLength` the spec writes for+// them. The ONE rule behind what the build sends (columnOptions, lib/entity-provision.js) and the length a key counts a column at (keyBytesAtLeast), so+// that a key is never sized from a length the build does not create.+function maxLengthSent(column) {+ return column && (column.type === 'Text' || column.type === 'Memo') && column.maxLength ? column.maxLength : undefined;+}++// The types of the spec the build creates as a single line of text — a StringAttributeMetadata, which a key holds at 2 bytes a character: `Text`, which+// is also what a column that gives no type is made as (SDK_COLUMN_TYPE[c.type || 'Text'], lib/entity-provision.js), and `AutoNumber`, a text column+// with a format.+const TEXT_COLUMN_TYPES = new Set(['Text', 'AutoNumber']);++// How many characters long the build creates a column of the spec that it creates as a single line of text, or undefined for a column it creates as+// something else (or not at all): the length it sends (maxLengthSent), else the SDK's. A value it sends that is not a whole number of characters is+// the platform's to refuse or to read as it will, so it counts for the one character every text column has.+function textLengthCreated(column) {+ if (!column || typeof column !== 'object' || !TEXT_COLUMN_TYPES.has(column.type || 'Text')) return undefined;+ const sent = maxLengthSent(column);+ if (sent === undefined) return SDK_TEXT_MAX_LENGTH;+ return Number.isInteger(sent) && sent > 0 ? sent : 1;+}++// The fewest bytes a key holds when its table's name column is `nameLength` characters long: a floor, so that what it shows is certain. Each column+// counts as the build creates it. A single line of text takes 2 bytes for each character — the name column at the length the environment made it, and a+// column of the spec at the length the build creates it with (textLengthCreated: a `Text` column's `maxLength`, else 100; an auto-number column, and a+// column that gives no type, 100 whatever `maxLength` they carry). Every other column counts for 1 byte: a column of another type a key can hold —+// Integer, Decimal, DateTime, Choice, a lookup — whose size the limit was not measured with, and one the spec does not describe. That can leave the+// floor under what the platform counts, never over it, and it changes nothing for a key that fits at the length the spec asks: beside a name column of+// 850 characters, 1,700 bytes by themselves, one byte is already too much, and at the length asked such a key's floor is within the limit whatever its+// other columns take. A key whose floor is over KEY_BYTES_LIMIT cannot fit; one whose floor is under it may or may not, and the platform decides.+// Never throws: a key or an entity that is not what it should be holds what can be counted of it.+function keyBytesAtLeast(entity, key, nameLength) {+ const name = String((entity && entity.primaryAttribute && entity.primaryAttribute.schemaName) || '').toLowerCase();+ const declared = (entity && Array.isArray(entity.columns)) ? entity.columns : [];+ let bytes = 0;+ for (const column of (key && Array.isArray(key.columns)) ? key.columns : []) {+ const logical = String(column).toLowerCase();+ if (name !== '' && logical === name) {+ bytes += 2 * (Number.isInteger(nameLength) && nameLength > 0 ? nameLength : 1);+ continue;+ }+ const length = textLengthCreated(declared.find((c) => c && String(c.schemaName).toLowerCase() === logical));+ bytes += length === undefined ? 1 : 2 * length;+ }+ return bytes;+}++// Whether the key cannot fit while the name column is `nameLength` characters long (see keyBytesAtLeast).+const keyCannotFitAt = (entity, key, nameLength) => keyBytesAtLeast(entity, key, nameLength) > KEY_BYTES_LIMIT;++// Whether the length of the name column decides where a key can be made: the key holds the name column (keyNeedsNameLength), cannot fit while that column+// is as long as a name column can be — PRIMARY_NAME_MAX_LENGTH characters are KEY_BYTES_LIMIT bytes by themselves, so any other column in the key is+// too much — and may fit at the length the spec asks. Only then can the length the environment made of the column (850 where it ignores the length asked+// of the create) keep the platform from taking the key, and only then can setting the length first change the platform's answer. A key over the name+// column alone always fits, and one that cannot fit at the length asked either would be refused after the length step as well: waiting helps neither.+// This is the half the spec decides; the other is the length the environment made, which the build reads.+function keyHasRoomOnlyAfterLength(entity, key) {+ return keyNeedsNameLength(entity, key)+ && keyCannotFitAt(entity, key, PRIMARY_NAME_MAX_LENGTH)+ && !keyCannotFitAt(entity, key, askedPrimaryNameLength(entity));+}+// The keys the build READS on each `appShell` level (appDef, sdk-build.js), for the same reason as// ENTITY_KEYS (#537). The levels name their title differently — areas and groups take `label`,// subareas take `title` — and a key with no reader was accepted and dropped: an area written with@@ -1160,6 +1240,19 @@ function labelText(value, languageCode) {return typeof hit === 'string' ? hit : '';}+// The plural a build gives a table whose spec sets no `pluralName`: its display name in the build's+// language, else its schema name, plus "s" — "Ticket" -> "Tickets", "Tag" -> "Tags". This is the ONE+// derivation, so nothing that relies on it can disagree with what the build writes: the build sends it+// as the table's DisplayCollectionName (entity-provision.js), lint predicts the "Active <plural>"+// default-view names with it (spec-lint.js), and a download leaves out exactly the plural that equals+// it (download-model-app.js entityFromMetadata) — a "Tag Catalog" is kept, because a rebuild of a spec+// without it would name the table "Tags". English only: appending "s" is not a plural rule in most+// languages, which is why validateAppSpec requires an explicit `pluralName` beside a localized+// `displayName` rather than reaching this.+function derivedPluralName(entity, languageCode) {+ return `${labelText(entity && entity.displayName, languageCode) || (entity && entity.schemaName)}s`;+}+// Every string a label can legitimately be NAMED by: a plain label is itself; a localized label is// each of its per-language strings. Used wherever an author may reference a label by text — Choice// option → value resolution for `sampleData`, and `personas[].jobs[].surfaces[]` — so a reference@@ -4347,12 +4440,18 @@ module.exports = {askedPrimaryNameLength,keyNeedsNameLength,keyWaitsForNameLength,+ KEY_BYTES_LIMIT,+ maxLengthSent,+ keyBytesAtLeast,+ keyCannotFitAt,+ keyHasRoomOnlyAfterLength,validateSampleDataRows,normalizePageSource,normalizeLanguageCode,validateChoiceOptionLabels,ambiguousChoiceAliases,labelText,+ derivedPluralName,labelAliases,isLocalizedLabelMap,labelIsMissing,diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-store.js b/plugins/model-apps/scripts/lib/apply-snapshot-store.jsindex e889499bc..f15c71a17 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot-store.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot-store.js@@ -25,6 +25,9 @@ const {} = require('./apply-snapshot.js');// The one liveness check, shared with the pages lock and the temporary workspaces (lib/process-owner.js); re-exported below as it always was.const { processAlive } = require('./process-owner.js');+// The one writer of the snapshot, the baseline (`last-applied.json`) and the page ownership and publish records is `writeFileAtomic`, and the text it writes has the access tokens the process obtained taken out first+// (lib/output-redaction.js). The leases, claims and markers this module writes hold process ids, times and random ids, and a reason built from a file system's own words.+const { redactOutput } = require('./output-redaction.js');const SNAPSHOT_FILE = 'apply-snapshot.json';const LEASE_FILE = 'apply-snapshot.lock';@@ -66,7 +69,7 @@ function writeFileAtomic(target, text) {try {const fd = fs.openSync(tmp, 'w');try {- fs.writeFileSync(fd, text);+ fs.writeFileSync(fd, redactOutput(text));fs.fsyncSync(fd);} finally {fs.closeSync(fd);diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.jsindex a678ab9e1..35eddcdb3 100644--- a/plugins/model-apps/scripts/lib/dataverse-auth.js+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js@@ -10,6 +10,9 @@ const { normalizeLanguageCode } = require('./app-spec.js');const { nearestName } = require('./nearest-name.js');const { execFileAsync, runSync, killProcessTree } = require('./process-runner.js');const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./cli-failure.js');+// Every access token read from the Azure CLI below is noted, so that nothing the process writes can carry it (lib/output-redaction.js). That module requires nothing, so it can be required here at the top, which+// lib/sdk-http-client.js — it requires this file — cannot be.+const outputRedaction = require('./output-redaction.js');// Dataverse environment hosts, one family per cloud (the same families power-pages accepts in// scripts/lib/validation-helpers.js, plus the non-numbered `crm<ring>` labels such as crmtest):@@ -140,7 +143,7 @@ function readAzToken(resource, opts = {}) {// re-call returns the same MSAL-cached token (see the ensureOk 401 note below). Reusing that// non-null token within this Node process removes repeated CLI cold-starts without changing// Dataverse semantics; a caller that just saw a 401 passes `{ fresh: true }` to replace it.- if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); }+ if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); outputRedaction.noteToken(token); }else { authTokenMemo.delete(resource); noteTokenFailure(resource, null); }return token;} catch (e) {@@ -193,7 +196,7 @@ function readAzTokenAsync(resource, opts = {}) {// Shares the synchronous helper's memo deliberately: check-auth can pre-warm the token// without blocking the event loop, and later synchronous Dataverse callers in the same// process still avoid a second Azure CLI cold start.- if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); }+ if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); outputRedaction.noteToken(token); }else { authTokenMemo.delete(resource); noteTokenFailure(resource, null); }resolve(token);}@@ -538,6 +541,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})const maxRetries = 2;for (let attempt = 0; attempt <= maxRetries; attempt++) {if (token.length >= MIN_SCRUBBED_TOKEN_LENGTH) tokensSent.add(token);+ outputRedaction.noteToken(token);const headers = {Authorization: `Bearer ${token}`,Accept: 'application/json',@@ -907,19 +911,25 @@ function asciiJson(value) {* ok=false + string → string to stderr, exit 1* `options.ascii` writes the stdout JSON through `asciiJson`, for a script whose output an agent reads off a console.* (stderr is for people and is never escaped.)+ * Every text it writes has the access tokens the process obtained taken out (lib/output-redaction.js). The streams are guarded the moment the first token is obtained, so this is the same guard once more; the result is+ * the one thing every script prints, and it is clean where a caller has replaced `process.stdout.write` (a host that runs a script in its own process, a test that captures it) and so replaced the guard too.+ * Both streams are made blocking before the first write (makeWritesBlocking): the process exits right after the writes, and on Linux and macOS a pipe's writes are otherwise queued, so `process.exit` cut a large+ * result short. It still never returns: the exit follows the writes at once.*/function emitResult(ok, payload, options = {}) {const toJson = options && options.ascii ? asciiJson : JSON.stringify;+ const redact = outputRedaction.redactOutput;+ outputRedaction.makeWritesBlocking(process.stdout, process.stderr);if (ok) {- process.stdout.write(toJson(payload) + '\n');+ process.stdout.write(redact(toJson(payload)) + '\n');process.exit(0);}if (payload instanceof Error) {- process.stderr.write(payload.message + '\n');+ process.stderr.write(redact(payload.message) + '\n');} else if (payload !== null && typeof payload === 'object') {// Structured failure. Emit the payload to stdout so callers can parse it, and exit 1 so shells// still treat it as a failure.- process.stdout.write(toJson(payload) + '\n');+ process.stdout.write(redact(toJson(payload)) + '\n');if (Array.isArray(payload.errors)) {// A genuine PARTIAL failure (bulk insert with some rows rejected): the count is the useful// summary and the detail is per-row on stdout.@@ -930,12 +940,12 @@ function emitResult(ok, payload, options = {}) {// The old branch printed "completed with unknown error(s)" for every one of them, burying the// diagnostic under boilerplate that is both less informative and actively misleading: nothing// "completed", and the error is not unknown.- process.stderr.write(payload.error.trim() + '\n');+ process.stderr.write(redact(payload.error.trim()) + '\n');} else {process.stderr.write('Operation failed with an unstructured error; see stdout JSON\n');}} else {- process.stderr.write(String(payload) + '\n');+ process.stderr.write(redact(String(payload)) + '\n');}process.exit(1);}diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 6766164f5..0cc71126c 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -15,6 +15,7 @@ const {quickCreateEnabledFor,normalizeLanguageCode,labelText,+ derivedPluralName,isLocalizedLabelMap,localizedLabelLcids,sampleKeyIdentity,@@ -24,6 +25,11 @@ const {askedPrimaryNameLength,keyNeedsNameLength,keyWaitsForNameLength,+ keyHasRoomOnlyAfterLength,+ keyCannotFitAt,+ keyBytesAtLeast,+ KEY_BYTES_LIMIT,+ maxLengthSent,PRIMARY_NAME_MAX_LENGTH,} = require('./app-spec.js');const { readColumnLabels, makeTableLabelReader, lookupKey } = require('./lookup-labels.js');@@ -34,13 +40,15 @@ const { odataLit } = require('./odata.js');// The one PublishXml that publishes tables by name (also the pre-app publish of sdk-build.js).const { publishTablesXml } = require('./table-publish.js');const { unreadableAnswer } = require('./collection-answers.js');-const { readRelationshipsOf, findRelationshipHolder, sameRelationship, describeRelationship, pickProjectionRow, projectionHolder } = require('./relationship-metadata.js');+const { readRelationshipsOf, findRelationshipHolder, compareRelationship, describeRelationship, describeIncomplete, intersectRemedy, pickProjectionRow, projectionHolder } = require('./relationship-metadata.js');// Transport-level language reads. Needed here because `MakerSdkOptions.languageCode` is a// construction-time option, so the LCID must be known before the SDK that would normally read it.const { readOrgLanguageCode, readProvisionedLanguages } = require('./dataverse-auth.js');// The build's retry policy (see the header of retry-policy.js): every halt below says what a run again may do, decided where it is raised, and every failure this engine raises itself is made by// refusal() (deterministic) or serviceFailure() (the plugin's words around a failure of the service) — never a bare `new Error`, whose message the build's retry would read.const { RETRY, retryPolicyFor, refusal, serviceFailure } = require('./retry-policy.js');+// What the run's throttle budget says when it refuses a wait (the words of the build's own halt for it), for the step guard in makeRunner.+const { waitDoesNotFit } = require('./throttle-budget.js');// App Spec column type -> SDK ColumnType. Lookup is omitted (side effect of a OneToMany// relationship); Customer is handled specially (createCustomerColumn).@@ -226,6 +234,15 @@ async function resolveLanguageCode({ provision, spec, languageCode, warn, provis}}+// The maximum size, in KB, of a File or Image column whose spec sets no `maxSizeKb`. The build sends no size for one (columnOptions+// below), and the vendored SDK's createColumn then writes its own default, for both types:+// { "@odata.type": "Microsoft.Dynamics.CRM.FileAttributeMetadata", …, "MaxSizeInKB": 10240 }+// Named here because a download leaves out exactly this size (download-model-app.js), so that a column authored without one comes+// back as it was authored — which is right only while it is what the build really makes; download-file-image-columns-real-bundle.test.js+// reads it off the wire of a real build (the vendored bundle, through columnOptions) and fails the day the SDK's default moves. It is NOT+// the platform's default (32768 for a File column made in Maker), which is why a column made there downloads with its size.+const DEFAULT_MAX_SIZE_KB = 10240;+// Map an App Spec column to SDK CreateColumnOptions. `globalChoiceIds` maps a global-choice// name -> its metadataId (so a column can bind to a shared option set).function columnOptions(c, globalChoiceIds, globalChoices, languageCode) {@@ -235,9 +252,12 @@ function columnOptions(c, globalChoiceIds, globalChoices, languageCode) {// skip and easy to forget — so the only reliable moment is the one where the column is authored.// Omitted when absent, so an existing column's description is never blanked by a rebuild.if (c.description) o.description = String(c.description);+ // Which columns carry a `maxLength`, and what, is the ONE rule maxLengthSent (lib/app-spec.js) states: the build counts a key over a column at the+ // length this creates the column with (keyBytesAtLeast), so the two must not disagree.+ const maxLength = maxLengthSent(c);switch (c.type) {- case 'Text': if (c.maxLength) o.maxLength = c.maxLength; if (c.format) o.stringFormat = c.format; break;- case 'Memo': if (c.maxLength) o.maxLength = c.maxLength; break;+ case 'Text': if (maxLength !== undefined) o.maxLength = maxLength; if (c.format) o.stringFormat = c.format; break;+ case 'Memo': if (maxLength !== undefined) o.maxLength = maxLength; break;case 'Integer': case 'BigInt': case 'Decimal': case 'Double': case 'Money':if (c.minValue !== undefined) o.minValue = c.minValue;if (c.maxValue !== undefined) o.maxValue = c.maxValue;@@ -503,7 +523,8 @@ async function checkOwedTable({ provision, debt, logical, primaryLogical, asked// The answer is `{ ok: true }` when the column has the length now; `{ ok: false, error, columnId? }` when it could not be read or set —// which an alternate key over the column needs to know (provisionDataModel creates it only after a step that succeeded) — with the id of// the column when the read before the update answered it, for the debt to keep; and `{ ok: false, left: true }` when the table is not-// the one the debt was recorded for (checkOwedTable, or a request addressed by its ids that answered 404), which is left alone.+// the one the debt was recorded for (checkOwedTable, or a request addressed by its ids that answered 404), which is left alone. A step the runner stopped before it began (`notStarted: true`, with the stop as `error`, and the column's+// id as above) is neither a length that was set nor an update that failed: nothing was sent, and the table is owed the length as it was.//// It is the LAST thing the data-model phase does (provisionDataModel calls it once every table, column, status reason, alternate// key and relationship has been created), not the first thing after the table. The SDK's updateColumn starts by reading the column@@ -527,8 +548,10 @@ async function checkOwedTable({ provision, debt, logical, primaryLogical, asked// updateColumn is not used for that update because it resolves the column by name (updateTextColumnLengthById).// `halted` says the phase stopped before this step: the warning for a length that could not be set then cannot promise that the build// continues, and says what a re-run does instead (it finds the table and leaves an existing table's name column as it is).-// `keys` are the alternate keys that wait for this step: where there are any, the warning is worded from them — the build does not-// continue past a key it cannot create (createWaitingKeys) — and not from the best-effort case, where the rest of the build does.+// `keys` are the alternate keys (the spec's entries) that wait for this step: where there are any, the warning is worded from them — the build+// does not continue past a key it cannot create (createWaitingKeys) — and not from the best-effort case, where the rest of the build does. Of each+// it says what the build can tell at the length the spec asks (keyRoomAtAskedLength), in the words of the stop for that key: no claim about the+// key at the length the column was left at, which the build did not ask the platform about, and no promise that setting the length makes room.async function alignPrimaryNameLength({ runner, sdk, provision, entity, logical, asked, warn, sleep, halted = false, debt = null, carried = false, keys = [] }) {const primaryLogical = String(entity.primaryAttribute.schemaName).toLowerCase();const label = `primary column length ${entity.schemaName}.${entity.primaryAttribute.schemaName}`;@@ -584,20 +607,34 @@ async function alignPrimaryNameLength({ runner, sdk, provision, entity, logical,if (read && bound && !columnId) {return leave({ step: 'nothing shows which column the build created', why: `the answer to the read of ${primaryLogical} carries no MetadataId, so nothing shows which column an update would write to, and the build never writes to a column it cannot name` });}- const waiting = keys.length ? `alt key${keys.length > 1 ? 's' : ''} ${keys.map((k) => `${entity.schemaName}.${k}`).join(', ')}` : '';+ const waiting = keys.length ? `alt key${keys.length > 1 ? 's' : ''} ${keys.map((k) => `${entity.schemaName}.${k.schemaName}`).join(', ')}` : '';const be = keys.length > 1 ? 'are' : 'is';+ // What the build can tell of each waiting key once the length is set (keyRoomAtAskedLength): the words of the stop for that key (createWaitingKeys).+ // Several keys are each named; the reason the length could not be set follows them all, after the sentences (runBestEffort appends it).+ const verdicts = keys.map((k) => {+ const room = keyRoomAtAskedLength(entity, k);+ const said = room.proven+ ? `it ${room.provenTooLarge}`+ : `running the build again once ${primaryLogical} is ${asked} characters long may create it: ${room.condition}. ${room.uncertain} ${room.nextRun}`;+ return keys.length > 1 ? `For alt key ${entity.schemaName}.${k.schemaName}, ${said}` : `${said.charAt(0).toUpperCase()}${said.slice(1)}`;+ }).join(' ');const afterwards = halted- ? `because the data-model phase stopped, and a run that finds the table already there leaves its name column as it is, change the length in Maker if it matters${waiting ? ` — it does for ${waiting}, which ${be} over that column and ${be} refused while the column is that long` : ''}`+ ? `because the data-model phase stopped, and a run that finds the table already there leaves its name column as it is, change the length in Maker if it matters${waiting ? ` — ${waiting} ${be} over that column. ${verdicts} Why the length could not be set` : ''}`: waiting- ? `the build stops at ${waiting}, which ${be} over that column and cannot be created while the column is that long`+ ? `the build stops at ${waiting}, which ${be} over that column and ${be} not asked for while the column is that long. ${verdicts} Why the length could not be set`: 'the rest of the build continues';let failure;let vanished = false;+ // `runner.run` can stop a step before it calls the function (the budget's guard does, for the steps of a phase it stops) and runBestEffort swallows that stop like any failure. Nothing is recorded inside the function then, which is also+ // how a step that succeeded looks, so whether the step began is recorded: a step that did not is neither a length that was set nor an update that failed, and must never be taken for the first.+ let began = false;+ let stopped;await runBestEffort(runner,'data-model',`${label} -> ${asked}${carried ? ` (${OWED_LENGTH})` : ''}`,async () => {+ began = true;try {if (unread) {const what = unconfirmed ? 'it could not be confirmed that the table is the one this build created' : 'the length the platform made is unknown';@@ -622,13 +659,17 @@ async function alignPrimaryNameLength({ runner, sdk, provision, entity, logical,},warn,`could not set the length of the primary name column ${logical}.${primaryLogical} to ${asked} — it keeps the length the platform gave it, and ${afterwards}`,- { skipIf: (err) => (err && err.leftAlone ? `${gone.step} — kept` : false) }+ // This step pays what the build owes for a table it created, which no later run can pay (a run that finds the table leaves its name column as it is), so it is never a step a refused budget stops (makeRunner): not in the settlement+ // of a halted phase, and not in the pass that completes one, where the refusal of one table's update must not keep the next table's from being set.+ { skipIf: (err) => (err && err.leftAlone ? `${gone.step} — kept` : false), settling: true, onFailure: (err) => { stopped = err; } });if (vanished) {warnKept(gone.why);return { ok: false, left: true };}- return failure ? { ok: false, error: failure, ...(read && read.metadataId ? { columnId: read.metadataId } : {}) } : { ok: true };+ const readColumn = read && read.metadataId ? { columnId: read.metadataId } : {};+ if (!began) return { ok: false, notStarted: true, error: stopped || serviceFailure(`asked ${asked}, the step was not run`), ...readColumn };+ return failure ? { ok: false, error: failure, ...readColumn } : { ok: true };}// The primary name column of a table that was found after the create that made it: the answer to that create was lost, or somebody@@ -869,12 +910,18 @@ function outcomeUnknown(err) {// never sends it again after another transient status or a lost answer, because a change set can commit behind those. A change set// still refused with a 429 when that schedule is spent was not a defect of the request, so the warning says the table was throttled// instead of blaming the request, and the one-by-one path then takes its own turn at the lock.-async function createColumnsInOneRequest({ sdk, provision, table, tableSchemaName, columns, optionsFor, warn, sleep }) {+//+// One more refusal is not the platform's: a run's throttle budget (lib/throttle-budget.js) that had no room for the wait a throttled change set asks. The HTTP client hands the 429 back as it came+// and tells the budget; the service has asked the run to hold back, so the columns are NOT then created one by one — each would be one more request to a service that said to wait — and the phase stops+// with the budget's halt. `stop`, when there is a budget, is the check that says so (the runner's `stopIfRefused`): it throws when the budget has refused, and does nothing otherwise, so a change+// set that was refused by anything else, or whose sends ran out while the budget still had room, falls back exactly as it always did.+async function createColumnsInOneRequest({ sdk, provision, table, tableSchemaName, columns, optionsFor, warn, sleep, stop }) {try {// The options are built inside the try: a column the options cannot be built for fails the way it always did, in its own step// on the per-column path, instead of failing the phase from here.await sdk.createColumns(table.logicalName, columns.map(optionsFor));} catch (err) {+ if (typeof stop === 'function') stop();if (outcomeUnknown(err)) {// ONE read, and only an answer that shows EVERY column counts: the change set is atomic, so a table that has only some of them// did not get them from it (a column the platform makes itself under the name of one the spec asks for is there either way).@@ -962,6 +1009,12 @@ class BuildHalt extends Error {}}+// The halt a run's throttle budget makes when it has refused to wait for a throttled request (lib/throttle-budget.js, `declined`): the service asked for longer than the run may wait, so the run ends here and a later one goes on from where it stopped —+// a transient halt, which is what the build's retry loop reports as `throttle-budget-exhausted` (build-model-app.js) in the same words, instead of running the phases again to meet the same answer. See makeRunner.+function budgetStop(throttle, phase) {+ return new BuildHalt(`${phase ? `${phase} stopped` : 'the build stopped'}: ${waitDoesNotFit(throttle, throttle.declined())}`, { phase, code: 'throttle-budget-exhausted', recoverable: true, retry: RETRY.SERVICE, statusCode: 429 });+}+// Collect every `code` along an error's `cause` chain, outermost first.//// A phase-level `skipIf` predicate is handed whatever reached the runner, and that is NOT always the@@ -1117,6 +1170,13 @@ async function findExistingColumns(provision, logical, warn) {// the create's own already-exists handling deal with it, because a table created moments ago// legitimately 404s here.//+// A row that carries the name but does not state its whole identity (a collection row without its+// referencing table or lookup, an N:N row without its intersect table, a projection row with an empty value —+// and the SDK's projection of an N:N always, which has no intersect table to state) is `null` too: it is not the+// declared relationship and it is not another's, so nothing is skipped on its name. The create then+// collides, and its already-exists handling reads the relationship ITSELF — which is where it is+// reused, once that read states everything, or where the build halts (see compareRelationship).+//// `hasLocalizedLabels` closes the same hole `findExistingTable` documents, for the same reason and// with the same rule. `fetchEntityMetadata` → `createRelationship` is one of the three broad-read →// create pairs that makes Dataverse keep ONLY the base-language label (AB#6686428), so falling back@@ -1172,7 +1232,9 @@ async function relationshipExists(provision, entityLogical, schemaName, type, opif (probed.state === 'unknown') return null;if (probed.state === 'absent') return false;const declaredWithName = Object.assign({}, declared, { schemaName: declared.schemaName || schemaName });- if (sameRelationship(declaredWithName, probed.holder)) return true;+ const verdict = compareRelationship(declaredWithName, probed.holder);+ if (verdict.state === 'same') return true;+ if (verdict.state === 'incomplete') return null;return { mismatch: true, holder: probed.holder };}@@ -1212,11 +1274,14 @@ async function readAttributeRequiredLevels({ sdk, provision, logical }) {return out;}-// `options` are the options of runner.run (`skipIf`, for a step that turns out to be a skip once it has started).+// `options` are the options of runner.run (`skipIf`, for a step that turns out to be a skip once it has started, and `settling`) and `onFailure`, which is told what the step failed with: the halt the runner made of what `fn` threw, or the stop+// the runner raised before it called `fn` (the budget's guard, makeRunner). Both are swallowed here, so a caller that records what the step came to inside `fn` cannot tell a step that ran and succeeded from one that never began without it.async function runBestEffort(runner, phase, label, fn, warn, warning, options = {}) {+ const { onFailure, ...runOptions } = options;try {- return await runner.run(phase, label, fn, { recoverable: true, ...options });+ return await runner.run(phase, label, fn, { recoverable: true, ...runOptions });} catch (err) {+ if (typeof onFailure === 'function') onFailure(err);if (typeof warn === 'function') {const cause = err && err.cause ? err.cause : err;warn(`${warning}: ${(cause && cause.message) || cause}`);@@ -1268,9 +1333,22 @@ async function mapLimit(items, limit, fn, { firstInOrder = false } = {}) {// A Runner owns the emit/counter/BuildHalt machinery so both consumers produce the// identical { phase, status, label, n, total } event stream. `total` is supplied by the// consumer (each computes its own plan length), so counting stays consumer-scoped.-function makeRunner({ emit, total }) {+//+// `throttle` is the run's throttle budget (lib/throttle-budget.js), for the runner of a build. Once it has refused to wait for a throttled request (`declined`) the run is over — the build's+// retry loop stops with `throttle-budget-exhausted` rather than run the phases again to meet the same answer — but the refusal can be swallowed on its way up: a best-effort step reports a failure+// and goes on, and a fallback answers a refused request with others (createColumnsInOneRequest). The run would then keep sending requests to a service that asked it to hold back, and could even end as a+// success. So after a refusal no step STARTS: `run` and each item of `mapLimit` stop the phase with the budget's halt (budgetStop), and `stopIfRefused` is the same check for code that must decide before it+// writes. A step that is already running finishes (a request is never cut off), and the step that pays what the run owes is let through (`settling`: the name column's length of a table the run created, in the settlement of a halted phase and in the+// pass that completes one — no later run can set it, because a run that finds the table leaves its name column as it is, so a stop would leave the table at the platform's default for good). One runner is one run of the phases (runSdkBuild makes one for each), so only+// refusals made after it was made count; a runner given no budget — or one that cannot say what it refused — never stops, as before.+function makeRunner({ emit, total, throttle }) {let n = 0;- const run = async (phase, label, fn, { recoverable = false, skipIf } = {}) => {+ const budgeted = Boolean(throttle) && typeof throttle.declined === 'function';+ const refusals = () => (budgeted ? throttle.declined().count : 0);+ const refusedBefore = refusals();+ const stopIfRefused = (phase) => { if (refusals() > refusedBefore) throw budgetStop(throttle, phase); };+ const run = async (phase, label, fn, { recoverable = false, skipIf, settling = false } = {}) => {+ if (!settling) stopIfRefused(phase);const myN = (n += 1);emit({ phase, status: 'start', label, n: myN, total });try {@@ -1296,7 +1374,9 @@ function makeRunner({ emit, total }) {}};const skip = (phase, label) => { emit({ phase, status: 'skip', label, n: (n += 1), total }); };- return { run, mapLimit, skip, emit, total };+ // The one limiter, with each item's start guarded when there is a budget to ask: a runner without one is handed the module's own function, as it always was.+ const limited = budgeted ? (items, limit, fn, options) => mapLimit(items, limit, (item, index) => { stopIfRefused(); return fn(item, index); }, options) : mapLimit;+ return { run, mapLimit: limited, skip, emit, total, stopIfRefused };}// How an operator resets a workspace by hand, where the build cannot do it itself. Most of `.maker-workspace`@@ -1348,19 +1428,10 @@ 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`.-//-// ROW_SUMMARY_TEMPLATE_NOT_FOUND: the SDK found no row-summary AI template. The build skips the summaries only for an org that really has none, so it-// reads the template list itself before it does (sdk-build.js, confirmNoTemplate). When that read FAILED, its failure is the cause the build kept-// beneath the SDK's error (the SDK's error has no cause of its own), and this says so: the SDK's words alone read as if the org had been found to have-// no template, when the build could not find out. No step is named: whether a run again helps is the failure's to say (a throttle, an unavailable service-// or a reset connection is run again by the build itself; a refusal is not), not this text's.function operatorRemedy(err) {if (err && err.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED') {return ' — the table exists. Run the build again: it finds the table, does not create it again, and sets the required level of its primary name column (the call the message names is made for you).';}- if (err && err.code === 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' && err.cause && typeof err.cause === 'object') {- return ` — the build then read the template list itself, to confirm that before skipping the row summaries, and that read failed (${err.cause.message || err.cause.code || 'no reason was given'}), so they were not skipped.`;- }if (err && err.code === 'ARTIFACT_PROJECTION_STALE') {return ` — the workspace copy was saved by an earlier version of this plugin and still holds edits no build pushed (an interrupted build, say). To reset it, ${RESET_WORKSPACE}, and re-run: the build re-reads the copies and re-applies every edit from the spec.`;}@@ -1663,7 +1734,7 @@ async function provisionDataModel(args) {// takes — and answers what each came to: `Map<logical name, { ok, error?, left? }>`, for the keys that wait for them. A table whose length// is right comes out of `owed`; so does one that turned out not to be the table the debt was recorded for (`left`: it is left alone, see// checkOwedTable — only a debt an earlier attempt carried is held to that); one whose step failed stays in it, marked `tried`, with the-// id of the column when the step read it. A debt for a table whose spec asks for no length (the spec cannot change within one build, so+// id of the column when the step read it — and so does one whose step the runner stopped before it began, which is not `tried`: nothing has run for it. A debt for a table whose spec asks for no length (the spec cannot change within one build, so// this is a record that does not match it) is dropped, and said if it was carried; one for a table the spec does not declare is left// alone: it is not this phase's. `waitingKeys` are the keys that wait for the steps, which the warning of a step that fails names.async function payOwedLengths({ runner, sdk, provision, spec, warn, sleep }, owed, carriedIn, { halted, waitingKeys }) {@@ -1680,10 +1751,14 @@ async function payOwedLengths({ runner, sdk, provision, spec, warn, sleep }, owecontinue;}debt.tried = true;- const keys = waitingKeys.filter((waiting) => waiting.logical === logical).map((waiting) => waiting.key.schemaName);+ const keys = waitingKeys.filter((waiting) => waiting.logical === logical).map((waiting) => waiting.key);const outcome = await alignPrimaryNameLength({ runner, sdk, provision, entity, logical, asked, warn, sleep, halted, debt, carried, keys });if (outcome.ok || outcome.left) owed.delete(logical);- else if (outcome.columnId) debt.columnId = outcome.columnId;+ else {+ if (outcome.columnId) debt.columnId = outcome.columnId;+ // A step the runner stopped before it began has tried nothing, so the debt is still one that a build which stops for good pays (settleOwedLengths repeats no step that has run and said what became of it).+ if (outcome.notStarted) debt.tried = false;+ }outcomes.set(logical, outcome);}return outcomes;@@ -1698,13 +1773,54 @@ function alternateKeyStep({ runner, sdk, entity, logical, key, languageCode }) {{ recoverable: true, skipIf: isAlreadyExists });}+// What the build can tell of an alternate key over a table's name column with that column at the length the spec asks — the one wording every+// message about such a key uses: the warning for a key made ahead of the length step and refused (alternateKeyAheadOfLength), the warning of a+// length step that failed while keys wait for it (alignPrimaryNameLength), and the stop for such a key (createWaitingKeys). It is decided from+// the floor of the key's size, counted from its columns as the build creates them (keyBytesAtLeast).+// - `proven`: even the floor is over what a key may hold. No length the build sets makes room for the key, and no run creates it as the spec+// has it, so a message says that, with the bytes, and what to change.+// - otherwise nothing is proven either way: the floor counts a column that is not text, or that the spec does not describe, at one byte, which+// the platform may exceed (a name column of 849 characters beside an Integer column counts 1,699 bytes, and is refused), and an environment+// may allow less than the 1,700 bytes measured. So a message says a run MAY create the key, on that condition, why that is not certain, and+// what to compare when the next run is refused the same way — never that it will.+// None of them offers a label in one language as a way out: that changes where a key is made, not its size.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys+function keyRoomAtAskedLength(entity, key) {+ const column = String(entity.primaryAttribute.schemaName).toLowerCase();+ const asked = askedPrimaryNameLength(entity);+ const atLeast = keyBytesAtLeast(entity, key, asked);+ const bytes = atLeast.toLocaleString('en-US');+ const limit = KEY_BYTES_LIMIT.toLocaleString('en-US');+ const size = `with ${column} at ${asked} characters the key's columns take at least ${bytes} bytes, and a key may hold at most ${limit}, 2 for each character of text`;+ const remedy = 'Take a column out of the key, or make its text columns shorter.';+ return {+ proven: atLeast > KEY_BYTES_LIMIT,+ size,+ remedy,+ // The stop for a key that waited, and the warning of the step it waited for, say this of a key proven too large, after "it".+ provenTooLarge: `cannot fit once the length is set either: ${size} — so no run creates it as the spec has it. ${remedy}`,+ condition: `it does if ${column} at ${asked} characters leaves room for it`,+ uncertain: `That is not certain: the build counts at least ${bytes} bytes for the key at that length — one byte for a column that is not text, `+ + `or that the spec does not describe — and the platform may count more, or allow less than the ${limit} bytes measured.`,+ nextRun: 'If the next run is refused the same way, compare the platform\'s error with the sizes of the key\'s columns, and take a column out of the key or make its text columns shorter.',+ };+}+// An alternate key over the name column of a table whose length is still to be set that cannot wait for it, because its label goes out in// several languages (keyWaitsForNameLength): it is made where it always was, ahead of the length step, so that the read that carries// labels, which setting the length starts with, does not come before a create that carries several languages. Where the platform then-// refuses it — a key may hold at most 900 bytes, which a name column of the 850 characters some environments give a new table is far-// over — the build says why this key was made first and what to do, because the platform's refusal says nothing of the length. The build-// sets the length as the last step before it stops (provisionDataModel), so the run that follows finds the table with it and makes the key.-// Said only when the key fails: where the environment keeps the length asked the key is made, and nothing is wrong.+// refuses it — a key may hold at most 1,700 bytes, which a name column of the 850 characters some environments give a new table fills by+// itself — the build says why this key was made first and what to do, because the platform's refusal says nothing of the length. The build+// sets the length as the last step before it stops (provisionDataModel), so the run that follows finds the table with it, and makes the key+// where that length leaves room for it.+// Said only when the key fails: where the environment keeps the length asked the key is made, and nothing is wrong. What reaches here is+// a key that was not known to be too large — a key over the name column alone fits even at 850 characters, and a read of the length that+// failed leaves a key that would not fit as undecided (keyMustWaitForShorterNameColumn) — or one the platform refused for another reason.+// What the warning tells the reader to do follows from what the build can tell of the key at the length the spec asks (keyRoomAtAskedLength).+// Proven too large, setting the length makes no room for it — which is why it was not made after the step (keyHasRoomOnlyAfterLength) — and the+// run that follows is refused as this one was, so the warning says that, with the bytes. Otherwise it promises nothing: a run again may create+// the key, if the length the spec asks leaves room for it, and where that run is refused the same way, the platform's error and the sizes of+// the key's columns say why.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keysasync function alternateKeyAheadOfLength({ runner, sdk, entity, logical, key, languageCode, warn }) {try {@@ -1712,35 +1828,68 @@ async function alternateKeyAheadOfLength({ runner, sdk, entity, logical, key, la} catch (err) {if (typeof warn === 'function') {const column = String(entity.primaryAttribute.schemaName).toLowerCase();+ const asked = askedPrimaryNameLength(entity);// Said from the languages the label goes out in, which is what keeps the key from waiting. A key that does not wait is a map that does not// name exactly one language, and only one that names several can get here: the SDK refuses an empty map before it sends anything.const languages = Object.keys(key.displayName);const named = languages.length > 1 ? `in several languages (${languages.join(', ')})` : 'a language map that does not name exactly one language';+ const room = keyRoomAtAskedLength(entity, key);+ const whatToDo = room.proven+ ? `It cannot fit at that length either: ${room.size} — so running the build again does not create it. ${room.remedy}`+ : 'If the platform refused it for its size — a key may hold '+ + 'at most 1,700 bytes, 2 for each character of text, so the 850 characters some environments make of a new name column fill it by themselves, and no other column fits beside it — '+ + `the length is set as the build stops, so running the build again may create the key: ${room.condition}. ${room.uncertain} ${room.nextRun}`;warn(`alt key ${entity.schemaName}.${key.schemaName} was not created. It is over the name column ${column} of a table this build created, and its label is ${named}, `- + `so the build creates it before it sets that column to ${askedPrimaryNameLength(entity)} characters `- + '(setting the length reads the column with its labels, which would keep only one of the languages). If the platform refused it for its size — a key may hold '- + 'at most 900 bytes, 2 for each character of text, and some environments make a new name column 850 characters long — run the build again: the length is set '- + 'as the build stops, so the key is created then. A key labelled in one language is created after the length is set.',+ + `so the build creates it before it sets that column to ${asked} characters `+ + `(setting the length reads the column with its labels, which would keep only one of the languages). ${whatToDo}`,);}throw err;}}-// The alternate keys that waited for their table's name column length (keyWaitsForNameLength), in the order the phase met them, made-// once every length step has run. A key whose table's step did not come right is not asked for: the platform would refuse it for the-// length it is left at — a key may hold at most 900 bytes, which a name column of 850 characters is far over — in words that say+// Whether a key labelled in several languages over the name column of a table whose length is still to be set must wait for that step all the+// same: the environment made the column too long for the key to fit beside the others, so the platform would refuse it ahead of the step, and+// shortening the column is the one thing that changes its answer. The platform's refusal is HTTP 400, code 0x80060895, "Index size exceeded the size+// limit of 1700 bytes" (KEY_BYTES_LIMIT, lib/app-spec.js), and it stopped the first build at the key, for the run that followed to make it.+//+// Decided from the length the environment made of the column — 850 characters where it ignores the length asked of the table's create+// (DEFAULT_PRIMARY_NAME_LENGTH), which is every byte a key may hold, the length asked where it keeps it — read with one typed request that selects MaxLength+// and nothing else (readTextColumn): no labels, the kind of read this build keeps ahead of its labelled creates, which does not do to the key what the read that+// carries labels, at the length step, would. A read is made only for a key that the spec shows can be in that position at all (keyHasRoomOnlyAfterLength): a+// key over the name column alone fits even at 850 characters, and a key that cannot fit at the length asked either would be refused after the step as well.+//+// Nothing else changes for such a key: it is the one key labelled in several languages that is made after a read that carries labels, which is what the rule that+// keeps the others ahead of the step avoids — and it is made there only because the platform leaves no other way to make it. Measured live, a key made right after+// that read keeps both of its labels (the SDK's update of the column, then its create of the key).+//+// A read that fails answers no: the key is asked for where it always was, and the platform decides, as it did before the build read the column.+async function keyMustWaitForShorterNameColumn({ provision, entity, logical, key, sleep }) {+ if (!keyHasRoomOnlyAfterLength(entity, key)) return false;+ try {+ const { maxLength } = await readTextColumn(provision, logical, String(entity.primaryAttribute.schemaName).toLowerCase(), { sleep });+ return keyCannotFitAt(entity, key, maxLength);+ } catch {+ return false;+ }+}++// The alternate keys that waited for their table's name column length (keyWaitsForNameLength, keyMustWaitForShorterNameColumn), in the order the phase met them, made+// once every length step has run. A key whose table's step did not come right is not asked for: the platform may refuse it for the+// length it is left at — a key may hold at most 1,700 bytes, which a name column of 850 characters fills by itself — in words that say// nothing of the length, and the step that failed has already said why in its own. So the key is a failed step of its own, naming-// both, and the build stops there as it does for a key the platform refuses. A table that turned out not to be the one the length was-// owed for (`left`, see checkOwedTable) is not one the build set the length of at all: its key is made as the key on any table the build-// found is, and the platform decides.+// both, and the build stops there as it does for a key the platform refuses. What the stop tells the reader to do follows from what the+// build can tell of the key at the length the spec asks (keyRoomAtAskedLength), in the words of the step's warning: a key proven too large+// there is created by no run as the spec has it; of any other, setting the length MAY make room, which the stop does not promise. A table+// that turned out not to be the one the length was owed for (`left`, see checkOwedTable) is not one the build set the length of at all: its+// key is made as the key on any table the build found is, and the platform decides.//// That stop is retried when the step failed the way a build's retry rides out (a 429, a lock, a 503) and not otherwise: it is a halt// raised with the step's failure as its cause and the policy that failure gives (`retry: retryPolicyFor(…)`, lib/retry-policy.js), so the// build's check (isTransientHalt, build-model-app.js) judges the failure of the step — the status it carries (and the status the step// failed with, which the halt declares), the code of the service's answer, a reset, an explicit "never retry" — and never the halt's own-// words or code. The retry then finds the length still owed (`owedLengths`), sets it, and makes the key.+// words or code. The retry then finds the length still owed (`owedLengths`), sets it, and asks for the key.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keysasync function createWaitingKeys({ runner, sdk }, waitingKeys, outcomes) {for (const { entity, logical, key, languageCode } of waitingKeys) {@@ -1749,14 +1898,18 @@ async function createWaitingKeys({ runner, sdk }, waitingKeys, outcomes) {const column = String(entity.primaryAttribute.schemaName).toLowerCase();const asked = askedPrimaryNameLength(entity);const why = (outcome.error && outcome.error.message) || String(outcome.error);+ const room = keyRoomAtAskedLength(entity, key);+ const whatToDo = room.proven+ ? `It ${room.provenTooLarge}`+ : `Set ${column} to ${asked} characters in Maker, or clear the cause above; running the build again may then create the key: ${room.condition}. ${room.uncertain} ${room.nextRun}`;// A halt, not an error with a code of its own: the build's retry takes an error's `code` for a refusal of that kind and reads nothing under it// (lib/retry-policy.js), while a halt's code only names it. So the stop follows the step's failure, which it carries as its cause.const chain = causeChain(outcome.error);const status = chain.map((e) => e.statusCode || e.status).find(Boolean);const halt = new BuildHalt(`alt key ${entity.schemaName}.${key.schemaName} was not created: it is over the name column ${column}, whose length the build could not set to ${asked} (${why}) — `- + 'a key may hold at most 900 bytes, 2 for each character of text, so Dataverse refuses one over a name column left at the 850 characters some environments give a new table. '- + `Nothing was sent for the key. Set ${column} to ${asked} characters in Maker, or clear the cause above, then run the build again: it creates the key.`,+ + 'a key may hold at most 1,700 bytes, 2 for each character of text, and a name column left at the 850 characters some environments give a new table fills that by itself, so Dataverse refuses a key that holds any other column beside it. '+ + `Nothing was sent for the key. ${whatToDo}`,{ phase: 'data-model', code: 'alt-key-name-length-not-set', recoverable: true, cause: outcome.error, retry: retryPolicyFor(outcome.error), ...(Number.isInteger(status) ? { statusCode: status } : {}) },);await runner.run('data-model', `alt key ${entity.schemaName}.${key.schemaName}`, async () => { throw halt; }, { recoverable: true });@@ -1887,7 +2040,9 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, laconst tableDisplayName = isLocalizedLabelMap(e.displayName)? e.displayName: (labelText(e.displayName, resolvedLanguageCode) || e.schemaName);- const createOpts = { schemaName: e.schemaName, displayName: tableDisplayName, pluralName: e.pluralName || `${labelText(tableDisplayName, resolvedLanguageCode) || e.schemaName}s`,+ // A table without `pluralName` gets the ONE derivation (derivedPluralName), which a download also uses to tell a plural it+ // must keep from one a rebuild would write anyway — so the two cannot drift apart.+ const createOpts = { schemaName: e.schemaName, displayName: tableDisplayName, pluralName: e.pluralName || derivedPluralName(e, resolvedLanguageCode),primaryColumnSchemaName: e.primaryAttribute.schemaName, primaryColumnDisplayName: e.primaryAttribute.displayName || 'Name', hasNotes: e.hasNotes === true, languageCode: resolvedLanguageCode,// Always sent, so a later change of the SDK's own default cannot change what a spec without a length gets — see// DEFAULT_PRIMARY_NAME_LENGTH.@@ -1969,6 +2124,8 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, laoptionsFor: (c) => columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode),warn,sleep,+ // A runner without the check (a stand-in for one) never stops here.+ stop: typeof runner.stopIfRefused === 'function' ? () => runner.stopIfRefused('data-model') : undefined,});}}@@ -2168,16 +2325,21 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la// already-exists error is treated as a skip (not a halt) via skipIf.//// A key over the name column of a table whose length is still to be set waits for that step when its label goes out in ONE language- // (keyWaitsForNameLength): it is made at the end of the phase, once the length is right, because a key over the column an environment made- // 850 characters long is refused for its size. A key over that column whose label goes out in several languages cannot wait — the read that- // sets the length carries labels — and is made here, ahead of the step, where the build says what to do if the platform refuses it- // (alternateKeyAheadOfLength). Every other key is made here, with its table, as it always was.+ // (keyWaitsForNameLength): it is made at the end of the phase, once the length is right. A key over that column whose label goes out in+ // several languages cannot wait — the read that sets the length carries labels — and is made here, ahead of the step, where the build says+ // what to do if the platform refuses it (alternateKeyAheadOfLength) — unless the environment made the column too long for the key to fit+ // beside the others: the platform would refuse it here, so it waits too, whatever its label (keyMustWaitForShorterNameColumn).+ // Every other key is made here, with its table, as it always was.for (const k of e.alternateKeys || []) {if (lengthPending && keyWaitsForNameLength(e, k)) {waitingKeys.push({ entity: e, logical, key: k, languageCode: resolvedLanguageCode });continue;}if (lengthPending && keyNeedsNameLength(e, k)) {+ if (await keyMustWaitForShorterNameColumn({ provision, entity: e, logical, key: k, sleep })) {+ waitingKeys.push({ entity: e, logical, key: k, languageCode: resolvedLanguageCode });+ continue;+ }await alternateKeyAheadOfLength({ runner, sdk, entity: e, logical, key: k, languageCode: resolvedLanguageCode, warn });continue;}@@ -2223,7 +2385,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, laif (exists === true) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }if (exists && exists.mismatch) {throw new BuildHalt(- `relationship schema name '${schema}' is already used by ${describeRelationship(exists.holder)}; the spec declares ${describeRelationship(declared)}. Give it an explicit "schemaName".`,+ `relationship schema name '${schema}' is already used by ${describeRelationship(exists.holder)}; the spec declares ${describeRelationship(declared)}. ${intersectRemedy(declared, exists.holder) || 'Give it an explicit "schemaName".'}`,{ phase: 'data-model', code: 'relationship-name-taken', recoverable: false, retry: RETRY.NEVER },);}@@ -2256,19 +2418,27 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la}} catch (err) {if (!isAlreadyExists(err)) throw err;+ // What the relationship held under this name says of itself decides the step. It is the declared one only when it states its whole+ // identity (compareRelationship): the create's own error is then rethrown, marked, which is how skipIf turns the step into a skip. One+ // it contradicts is another relationship's, and the name has to change. One that leaves a part out is neither — it has not been shown+ // to be the declared relationship, so nothing is skipped on its name, and the build stops.+ const unprovenHolder = (verdict) => refusal(`relationship schema name '${schema}' already exists, but ${describeIncomplete(verdict.missing)}, so the build cannot tell it from the declared ${describeRelationship(declared)} and does not reuse it. It was left as it is: run the build again, and if the answer stays incomplete, check this relationship in Power Apps (Solutions > the table > Relationships).`);+ const settle = (heldBy) => {+ const verdict = compareRelationship(declared, heldBy);+ if (verdict.state === 'same') {+ err.sameRelationshipExists = true;+ throw err;+ }+ if (verdict.state === 'incomplete') throw unprovenHolder(verdict);+ throw refusal(`relationship schema name '${schema}' is already used by ${describeRelationship(heldBy)}; the spec declares ${describeRelationship(declared)}. ${intersectRemedy(declared, heldBy) || 'Give it an explicit "schemaName".'}`);+ };// skipIf is synchronous, so classify the holder here and rethrow a marked error. The// SchemaName key is case-sensitive; findRelationshipHolder falls back to the declared// endpoints when the exact spelling 404s.let holder = await findRelationshipHolder(provision && provision.dataverse, schema, {candidates: rel.type === 'ManyToMany' ? [rel.entity1, rel.entity2] : [rel.referenced, rel.referencing],});- if (holder.found === true && sameRelationship(declared, holder.holder)) {- err.sameRelationshipExists = true;- throw err;- }- if (holder.found === true) {- throw refusal(`relationship schema name '${schema}' is already used by ${describeRelationship(holder.holder)}; the spec declares ${describeRelationship(declared)}. Give it an explicit "schemaName".`);- }+ if (holder.found === true) settle(holder.holder);if (holder.found === false) {// The generated name is free, but the lookup column may already belong to a relationship// under a different name (a download that omitted the deployed name, or an authored spec@@ -2280,10 +2450,14 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, laif (owner) {// The row may have become visible on this read — the lag case. If it is the// relationship we declared, skip. Only a different owner (same lookup, other name) halts.- if (sameRelationship(declared, owner)) {+ // A row that holds the lookup but does not state enough to be called the declared relationship+ // is neither: it is not skipped, and it is not another relationship's to name.+ const verdict = compareRelationship(declared, owner);+ if (verdict.state === 'same') {err.sameRelationshipExists = true;throw err;}+ if (verdict.state === 'incomplete') throw unprovenHolder(verdict);const at = (spec.relationships || []).indexOf(rel);throw refusal(`lookup '${wantLookup}' on '${String(rel.referencing).toLowerCase()}' already belongs to relationship '${owner.schemaName}' (${describeRelationship(owner)}); set relationships[${at}].schemaName to '${owner.schemaName}' to reuse it`);}@@ -2297,13 +2471,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, lafor (const delay of [2000, 4000]) {await wait(delay);holder = await findRelationshipHolder(provision && provision.dataverse, schema, { candidates });- if (holder.found === true && sameRelationship(declared, holder.holder)) {- err.sameRelationshipExists = true;- throw err;- }- if (holder.found === true) {- throw refusal(`relationship schema name '${schema}' is already used by ${describeRelationship(holder.holder)}; the spec declares ${describeRelationship(declared)}. Give it an explicit "schemaName".`);- }+ if (holder.found === true) settle(holder.holder);if (holder.found !== false) break;}if (holder.found === false) {@@ -2734,4 +2902,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })return { records: result.records, entitySetFor };}-module.exports = { makeRunner, mapLimit, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, settleOwedLengths, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists, lookupsWithDefaultLabel, relationshipsInCreateOrder };+module.exports = { makeRunner, mapLimit, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, settleOwedLengths, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, DEFAULT_MAX_SIZE_KB, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists, lookupsWithDefaultLabel, relationshipsInCreateOrder };diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.jsindex c738edadf..b7eeac7b4 100644--- a/plugins/model-apps/scripts/lib/feature-flags.js+++ b/plugins/model-apps/scripts/lib/feature-flags.js@@ -212,6 +212,9 @@ module.exports = {if (require.main === module) {const arg = process.argv[2];if (arg === '--list') {+ // The list ends with a warning for each bad entry of the flags file, and the process exits right after it: the writes are+ // made blocking first, or a pipe on Linux and macOS takes only what fits at once (output-redaction.js).+ require('./output-redaction.js').makeWritesBlocking(process.stdout, process.stderr);for (const { flag, enabled, source, status } of describe()) {process.stdout.write(`${flag}: ${enabled ? 'enabled' : 'disabled'} (status: ${status}, source: ${source})\n`diff --git a/plugins/model-apps/scripts/lib/formxml-layers.js b/plugins/model-apps/scripts/lib/formxml-layers.jsindex fb4a89301..f6d9a6002 100644--- a/plugins/model-apps/scripts/lib/formxml-layers.js+++ b/plugins/model-apps/scripts/lib/formxml-layers.js@@ -22,6 +22,25 @@//// What this cannot see is a change to a label in a language the published read does not carry (a translation saved and not published): no read// verify makes shows it, and it changes nothing verify proves of a dashboard — its tiles' tables, views and charts.+//+// THE ROW'S OWN VERSION. The rule above reads two texts, and a text is a PROJECTION for its reader. Measured live in the same organization, for a+// user whose own language (usersettings.uilanguageid) is the second one, 3082, on a dashboard nothing had written since its publish, the published+// read carried BOTH languages, the user's own first, and the saved read the stored order, base language first — in every cell:+// published <labels><label description="Customers" languagecode="3082" /><label description="Gold Customers" languagecode="1033" /></labels>+// saved <labels><label description="Gold Customers" languagecode="1033" /><label description="Work Orders" languagecode="3082" /></labels>+// (the other three cells differ in that order alone). Both languages are carried, so none is set aside, and the texts differ in an order and in one+// caption's wording: "not published", for that user, on a dashboard that is. No rule over the two texts can say which of two captions is "the"+// caption — the published reads of forms nobody had edited differed between the two users the same way — but the platform can say whether the saved+// layer has been written since the publish. The published row and the saved read each answer an `@odata.etag`, the SAME token after a publish,+// whoever reads; a write to the saved layer moves its token and not the row's, even a write that puts the content back (measured: four writes, four+// new tokens, the row's unmoved; a publish moved both to one new token). So when `versions` says the two reads answer the same token, the saved+// layer IS the published row, and the texts can differ only in what each reader is shown of the captions. They are then compared with every caption+// set aside, of any language: a tile, a cell, an element, an attribute, any text and a comment are not captions and are still compared byte for+// byte. That is only for a published read that carries MORE THAN ONE language, which is what the platform gives a user whose own language is not+// the base one (the user's own and the base): the rule above is premised on one language set whoever reads, and this is for a read where that+// premise fails. With another token, with none, or for a published read of one language — the base-language user's — the texts decide as above,+// and the earlier results are as they were by construction: this only adds a way for two reads to be the same dashboard, never a way to differ.+// See https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-apiconst { readXmlElements } = require('./strict-xml.js');const { normalizeLanguageCode } = require('./app-spec.js');@@ -30,6 +49,8 @@ const isLabel = (name) => name === 'label';// a control's parameter, say — is not one, and is compared like any other element.const isCaption = (element) => element.path === 'labels' || element.path.endsWith('/labels');const languageOf = (caption) => normalizeLanguageCode(caption.attrs.languagecode);+// The token is opaque text (W/"7067996"): equal or not, never parsed or ordered. A read that answers none, or an empty one, has no word to give.+const sameVersion = (versions) => !!versions && typeof versions.published === 'string' && versions.published !== '' && versions.published === versions.saved;// The captions of one FormXML, each with where it is in the text, or null when the text is not one well-formed XML document.function captionsOf(xml) {@@ -55,17 +76,24 @@ function withoutCaptionsOutside(xml, captions, carried) {/*** Whether `saved` (a systemform's FormXML as RetrieveUnpublished answers it) is `published` (the FormXML a plain read of the row answers), in the- * languages the published read carries.+ * languages the published read carries — or, when the published read carries more than one language and `versions` says the two reads answer the+ * same `@odata.etag`, in everything but the captions.** sameFormXmlAcrossLayers('<form>…<labels><label description="Open" languagecode="1033" /></labels>…</form>',* '<form>…<labels><label description="Open" languagecode="1033" /><label description="Abierto" languagecode="3082" /></labels>…</form>')* → true (the published read carries 1033 alone, so the 3082 caption is set aside)*+ * sameFormXmlAcrossLayers('<form>…<labels><label description="Abiertos" languagecode="3082" /><label description="Open" languagecode="1033" /></labels>…</form>',+ * '<form>…<labels><label description="Open" languagecode="1033" /><label description="Abierto" languagecode="3082" /></labels>…</form>',+ * { published: 'W/"1001"', saved: 'W/"1001"' })+ * → true (both languages are carried and the captions differ, but it is one row at one version)+ ** @param {*} published the published read's FormXML* @param {*} saved the saved read's FormXML+ * @param {{ published: *, saved: * }} [versions] the `@odata.etag` of the published row and of the saved read* @returns {boolean} false for anything that is not text, and for a text that is not one well-formed XML document unless the two are equal*/-function sameFormXmlAcrossLayers(published, saved) {+function sameFormXmlAcrossLayers(published, saved, versions) {if (typeof published !== 'string' || typeof saved !== 'string') return false;if (published === saved) return true;const publishedCaptions = captionsOf(published);@@ -74,7 +102,14 @@ function sameFormXmlAcrossLayers(published, saved) {const carried = new Set(publishedCaptions.map(languageOf).filter((lcid) => lcid !== null));if (!carried.size) return false;// Set aside from both reads, as the rule says — the published read has, by what `carried` is, no caption in another language to set aside.- return withoutCaptionsOutside(published, publishedCaptions, carried) === withoutCaptionsOutside(saved, savedCaptions, carried);+ if (withoutCaptionsOutside(published, publishedCaptions, carried) === withoutCaptionsOutside(saved, savedCaptions, carried)) return true;+ // A read of one language is the base-language user's, and the texts alone decide it at any version; the token is for a published read that carries+ // more than one language (the second-language user's), where the texts cannot.+ if (carried.size < 2 || !sameVersion(versions)) return false;+ // The same row: no language is "carried" any more, so every caption of a valid language goes, from both reads. A caption that cannot be taken out+ // (one with content or an end tag, or with no valid language) stays in the text and is compared, so it is a change as before.+ const none = new Set();+ return withoutCaptionsOutside(published, publishedCaptions, none) === withoutCaptionsOutside(saved, savedCaptions, none);}module.exports = { sameFormXmlAcrossLayers };diff --git a/plugins/model-apps/scripts/lib/genpage-sdk.js b/plugins/model-apps/scripts/lib/genpage-sdk.jsindex aaeae01a9..09b34fa54 100644--- a/plugins/model-apps/scripts/lib/genpage-sdk.js+++ b/plugins/model-apps/scripts/lib/genpage-sdk.js@@ -689,7 +689,7 @@ function makeGenpageSdk(env, deps = {}) {// The SDK's transport, limited for a page edit of an app (see appScope above and `pushApp`), and watched, so a refused page write's Retry-After reaches this backend, and so does what a change set// refused as a whole proved (watchThrottles): the SDK's error for either carries no headers and no part. The watch is the inner layer, next to the transport, so what it hears is what the service// answered: a post the limit answers itself (an AddAppComponents left with nothing to add) never reached the service.- httpClient: appScope.wrap(watchThrottles(deps.httpClient || (deps.createHttpClient || createAzHttpClient)(env), (ms) => { asked = Math.max(asked, ms); }, deps.now, (found) => { refusal = found; })),+ httpClient: appScope.wrap(watchThrottles(deps.httpClient || (deps.createHttpClient || createAzHttpClient)(env, { throttle: deps.throttle }), (ms) => { asked = Math.max(asked, ms); }, deps.now, (found) => { refusal = found; })),// A page's file downloads overlap (four at a time): a read of a page is its rows' bytes, one request each.readConcurrency: 4,...(options.languageCode ? { languageCode: options.languageCode } : {}),@@ -726,9 +726,16 @@ function makeGenpageSdk(env, deps = {}) {// `readServer`'s answer as the page or the typed error a caller reads, for the operations that cannot go on without it: `GENPAGE_NOT_FOUND` / `GENPAGE_UNREADABLE`.async function presentPage(sdk, id) {+ const declinedBefore = declinedCount();const found = await readServer(sdk, id);if (found.kind === 'absent') throw genpageError(`page ${id} does not exist in this environment`, { code: 'GENPAGE_NOT_FOUND' });- if (found.kind === 'unreadable') throw genpageError(`could not read page ${id}: ${messageOf(found.error)}`, { code: 'GENPAGE_UNREADABLE', cause: found.error });+ if (found.kind === 'unreadable') {+ const message = `could not read page ${id}: ${messageOf(found.error)}`;+ // A throttle the budget had no room to wait for is the service's to say, and a later run may find it ready: it is not the final "this page cannot be read".+ throw isThrottle(found.error) && declinedCount() > declinedBefore+ ? refusedReadError(message, found.error, {})+ : genpageError(message, { code: 'GENPAGE_UNREADABLE', cause: found.error });+ }return found.page;}@@ -774,7 +781,7 @@ function makeGenpageSdk(env, deps = {}) {// A first send the service REFUSED with a throttle (HTTP 429) — as a whole request, or as the one failing part of a change set it answered with HTTP 200 — waited out and sent again — at most THROTTLE_RESENDS times, six sends in// all — and the answer of the last one. The wait is the HTTP client's schedule for every other throttled request (throttleBackoffMs), or what the answer's Retry-After asks when that is longer, WHOLE (watchThrottles): what- // fits is the budget's to say. Every wait comes out of the run's throttle budget (lib/throttle-budget.js), the same one the build's own waits come out of; the wait that does not fit is not taken, nothing more is sent, and the+ // fits is the budget's to say. Every wait comes out of the run's throttle budget (lib/throttle-budget.js), the same one the build's own waits and the HTTP client's come out of; the wait that does not fit is not taken, nothing more is sent, and the// answer comes back marked `stopped` for the caller to say so. Why a send that follows a 429 is safe, and why it is made here and not by the HTTP client re-sending the request (as it does for a conditional delete):// - A 429 is the service declining to START the request: the change set is atomic, so nothing in it committed. The page is as unsent as it was.// - And even a request that had been processed could not write a page twice. A create's ids — the page's, and those of its rows — are minted before the first send, so a second send meets the first and is rolled back whole (the@@ -817,8 +824,20 @@ function makeGenpageSdk(env, deps = {}) {: messageOf(pushed.error));// What an operation says of a write that was throttled and then taken: why it was slow, and that the page was written once. `waited` is what pushThroughThrottle recorded.const throttleNote = (what, waited) => `the service throttled the write of ${what} (HTTP 429) ${waited.length === 1 ? 'once' : `${waited.length} times`}: a refused request writes nothing, so it was sent again after waiting ${waited.map((ms) => `${Math.round(ms / 100) / 10} s`).join(', ')}, and written once`;- // The budget an operation spends its waits from: the run's, which the build hands to every page write (`args.throttle`), or — for a caller that has none, such as the upload script — one of its own for this write.- const budgetOf = (args) => (args && args.throttle && typeof args.throttle.fits === 'function' ? args.throttle : makeThrottleBudget({ warn: deps.warn }));+ // The budget an operation spends its waits from: the run's, which the build hands to every page write (`args.throttle`); else the one the backend was handed (`deps.throttle`: the upload script's, which hands it to its backend because it is a+ // run of one write, and which the backend's own HTTP client draws from as well); else — for a caller that has none — one of its own for this write.+ const budgetOf = (args) => (args && args.throttle && typeof args.throttle.fits === 'function' ? args.throttle : deps.throttle && typeof deps.throttle.fits === 'function' ? deps.throttle : makeThrottleBudget({ warn: deps.warn }));++ // The waits the HTTP client has refused for want of room in a budget (`declined`, lib/throttle-budget.js), counted over the budgets this backend draws on: the one a call was handed and the backend's own, which the client it makes draws from. A read the+ // client hands back as a throttle (HTTP 429) is the BUDGET's refusal when this count grew while it was read — the SDK's error says nothing of that, nor of what the service asked — so a caller takes the count before the read and compares after.+ const budgetsOf = (args) => [...new Set([args && args.throttle, deps.throttle].filter((b) => b && typeof b.declined === 'function'))];+ const declinedCount = (args) => budgetsOf(args).reduce((total, b) => total + b.declined().count, 0);+ // The error of a read before a write that the budget refused to wait for. It is the throttle's own (`throttledError`): not `transient: false`, because nothing was changed and the service's load is not the page's, and it carries what the service+ // asked — which the SDK's error does not — so that the build's retry loop stops with the budget's halt (build-model-app.js). The code and the fields are those the same read gives when it fails for another reason.+ const refusedReadError = (message, cause, props, args) => {+ const askedMs = Math.max(0, ...budgetsOf(args).map((b) => b.declined().askedMs));+ return throttledError(message, { code: 'GENPAGE_UNREADABLE', cause, ...props, statusCode: 429, ...(askedMs > 0 ? { retryAfterMs: askedMs, retryNotBefore: clock() + askedMs } : {}) });+ };// Publish the page and prove the published copy is the one just written. The SDK answers `publish.kind`:// 'verified' the published projection serves exactly what was saved@@ -1093,15 +1112,23 @@ function makeGenpageSdk(env, deps = {}) {// which keeps no base marker and reads every page again when it runs; otherwise the// standalone upload's `genpage-base.js check` (`appId` and `sourceFile` name its arguments).// A first send the service refuses with a throttle (HTTP 429) wrote nothing: it is waited out and sent again (pushThroughThrottle), and the SDK's version check runs again on that send, so a page someone saved meanwhile- // is refused (`VERSION_CONFLICT`), never written over. A throttle that outlasts the waits is reported as nothing written and is not marked `transient: false`, so the build may run again.+ // is refused (`VERSION_CONFLICT`), never written over. A throttle that outlasts the waits is reported as nothing written and is not marked `transient: false`, so the build may run again. So is the read of the page that comes before any send,+ // when the run's budget had no room to wait for its throttle: `GENPAGE_UNREADABLE` with status 429 and what the service asked, nothing changed — a read that failed any other way is final, as it always was.async update(pageId, args = {}) {if (!GUID_RE.test(String(pageId || ''))) throw genpageError(`'${pageId}' is not a page id`, { code: 'GENPAGE_ID_INVALID' });const id = String(pageId).toLowerCase();const fields = contentFieldsOf(args);const sdk = await getSdk();+ const declinedBefore = declinedCount(args);const found = await readServer(sdk, id);if (found.kind === 'absent') throw genpageError(`page ${id} does not exist in this environment — nothing was changed`, { code: 'GENPAGE_NOT_FOUND', outcome: 'nothing', pageId: id });- if (found.kind === 'unreadable') throw genpageError(`could not read page ${id} before updating it (${messageOf(found.error)}) — nothing was changed`, { code: 'GENPAGE_UNREADABLE', cause: found.error, outcome: 'nothing', pageId: id });+ if (found.kind === 'unreadable') {+ const message = `could not read page ${id} before updating it (${messageOf(found.error)}) — nothing was changed`;+ // The read comes before any write, so a throttle the budget had no room to wait for changed nothing and is the service's to say: not final, and the build stops with the budget's halt (build-model-app.js).+ throw isThrottle(found.error) && declinedCount(args) > declinedBefore+ ? refusedReadError(message, found.error, { outcome: 'nothing', pageId: id }, args)+ : genpageError(message, { code: 'GENPAGE_UNREADABLE', cause: found.error, outcome: 'nothing', pageId: id });+ }let baseline = found.page;const who = () => label(baseline.name, id);if (typeof baseline.source !== 'string') {diff --git a/plugins/model-apps/scripts/lib/import-job-proof.js b/plugins/model-apps/scripts/lib/import-job-proof.jsnew file mode 100644index 000000000..96c835e65--- /dev/null+++ b/plugins/model-apps/scripts/lib/import-job-proof.js@@ -0,0 +1,139 @@+'use strict';+// What the import JOB of an import the platform REFUSED to start says about whether that import applied anything: the proof solution-settings.js needs before it sends a refused import again.+//+// The platform answers an import that meets another import or a publish with HTTP 429 and the Dataverse error code 0x80071151 (SolutionConcurrencyFailure):+// { "error": { "code": "0x80071151", "message": "Cannot start another [Import] because there is a previous [Import] running at this moment. Use Solution History for more details. -- The solution+// installation or removal failed due to the installation or removal of another solution at the same time. Please try again later." } }+// ("Cannot start the requested operation [Import] because there is another [Publish] running …" when a publish holds the lock). The code does not say that nothing started — its documented text says an+// installation or removal FAILED — so the import's own job decides. It is read ONCE and AT ONCE: the row of a refused send is final by the time the answer is in hand, and it is not written again. Measured on a+// Public-cloud environment (Dataverse 9.2), a refused send's `importjobs(<id>)` is one of two things:+// - it never exists (HTTP 404, at once and for as long as it was read: hours) — the refusal came at the FIRST lock check, before the platform made a job. An import that was refused for another reason+// before it started (an invalid package, HTTP 400) has no job either;+// - it exists, finished, and says so — the refusal came at the SECOND lock check, when two imports started together. Its row has `completedon` set and a `data` column that is the import's log:+// <importexportxml start="…" stop="…" progress="17.1428571428571" processed="true" errorcode="-2147020463" succeeded="failure" status="Cannot start another [Import] …">+// <solutionManifests><solutionManifest languagecode="1033" id="contoso_sol" LocalizedName="…" processed="false"> … <results /></solutionManifest></solutionManifests>+// <entities><entity … id="contoso_alpha1" processed="false"></entity> …</entities>+// <entitySubhandlers><savedQuery … processed="false"></savedQuery><formXml … processed="false"></formXml><entityRibbon … processed="false"></entityRibbon> …</entitySubhandlers>+// <rootComponents><rootComponent processed="false" /></rootComponents> <dependencies><dependency processed="false" /></dependencies> <workflowAndStepActivations> …+// <upgradeHandlers><upgradeHandler id="…" … processed="true"><result result="success" errorcode="0" errortext="" datetime="…" datetimeticks="…" /></upgradeHandler> …</upgradeHandlers>+// <validateHandlers><validateHandler id="XSDValidationHandler" … processed="true"><result result="success" … /></validateHandler></validateHandlers>+// </importexportxml>+// `-2147020463` is 0x80071151 read as a signed 32-bit integer. The only nodes marked processed="true" are the package's own checks (the in-memory transform of the package and the XSD validation), which+// run before the lock is asked for the second time; nothing of the package — the solution manifest, a table, a view, a form — was applied.+// What a job that is NOT such a refusal looks like, for contrast: a running import has `completedon` null and a log that is the bare `<importexportxml>` with no attribute on the root and no `processed` on any+// node; an import that applied the package has `succeeded="success"` and every node processed="true"; one that FAILED AFTER it began (a managed package over an unmanaged solution, a missing dependency; HTTP 500+// 0x80048033) has the root's `errorcode="-2147188685"` and `solutionManifest processed="true"`. `solutionManifest processed="false"` means nothing was applied because the platform writes the manifest FIRST: in all+// 17 imports that completed, its result time is 2.6–6.1 s before the first component's.+//+// THE RULE (a refused send's job proves that nothing of the package was applied, so a second send cannot meet a half-applied first one, when ALL of this holds):+// - `completedon` is set (a running job proves nothing);+// - `data` is ONE XML document whose root is `importexportxml` with `succeeded="failure"` and `errorcode="-2147020463"`, exactly;+// - there is at least one `solutionManifest`, and every one is `processed="false"`;+// - no other element but the package's own checks (`upgradeHandler`, `validateHandler`) is marked anything but "false".+// Or the job does not exist (HTTP 404). Anything else — a job still running, one that failed after it began, a log that is not what is described, a read that failed — is NOT PROVEN: the import is not sent again.+// Not looked at, because the measurement shows they do not tell a refusal from a running import: `progress` (a running import passes through 17.14 and 40 too), `solutionid` (set even for a solution that was never+// made), `importcontext`, and the VALUE of any timestamp.+//+// WHY A READER AND NOT A PATTERN. The log is an undocumented internal format, and this is a decision that must not be wrong in the dangerous direction: a wrong "nothing was applied" sends a second copy of an import+// that the platform may be running. A pattern over the text finds `processed="true"` only where it expects a tag to end — and a ">" is legal in an attribute value — and finds the attributes it looks for in a comment, a+// CDATA section or another attribute's value. So the log goes through lib/strict-xml.js, which reads exactly one well-formed document and answers with no element at all for anything else, and every doubt is "not+// proven": a value that is not exactly the one measured ("Failure", " failure", "-2147020463.0", "True"), a duplicate attribute, a DOCTYPE, a log longer than MAX_JOB_LOG_CHARS.+//+// Only fixed words and numbers are ever put in a `reason` — never a text the platform wrote — because a reason is shown in a message beside the settings file's values.+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/importsolution ("the ID of the import job that will be created to perform the import"),+// https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/importjob (`completedon`, `data`),+// https://learn.microsoft.com/power-apps/developer/data-platform/reference/web-service-error-codes (0x80071151).+const { readXmlElements } = require('./strict-xml.js');++// 0x80071151 as the signed 32-bit integer the log writes (0x80071151 | 0).+const CONCURRENCY_ERRORCODE = '-2147020463';+// A refused import's log lists every component of the package as unprocessed, about a hundred bytes each, so even a package of tens of thousands of components fits. The limit only bounds the work of the reader+// (linear in the text, plus one look at the text for each kind of element): a log past it is not read.+const MAX_JOB_LOG_CHARS = 8 * 1024 * 1024;+const LOG_LIMIT_TEXT = `${MAX_JOB_LOG_CHARS / (1024 * 1024)} MiB`;+// The package's own checks: they run — in memory, on the package alone — before the second lock check, so a refused import has them processed.+const PACKAGE_CHECKS = new Set(['upgradeHandler', 'validateHandler']);++// How a job was proven: it does not exist, or its log says the import was refused before it applied anything.+const PROOF_ABSENT = 'job-absent';+const PROOF_LOG = 'job-refused-before-any-component';++// What each way of failing the rule says, in fixed words. `why` is the key; `reason` completes "…, but <reason>, so it is not proven that the refused send applied nothing of the package".+const REASONS = Object.freeze({+ 'no-log': 'its import job has no log to read',+ unfinished: 'its import job is not finished (completedon is empty)',+ 'log-too-large': `the log of its import job is longer than ${LOG_LIMIT_TEXT}, which this script does not read`,+ 'log-unreadable': 'the log of its import job is not an XML document this script can read',+ 'not-an-import-log': 'the log of its import job is not an importexportxml document',+ 'not-a-failure': 'the log of its import job does not say that the import failed',+ 'no-manifest': 'the log of its import job has no solution manifest',+ 'manifest-processed': 'the log of its import job shows that the import began to apply the package (its solution manifest is processed)',+ 'manifest-unmarked': 'the log of its import job does not say that its solution manifest was left unprocessed',+ 'component-processed': 'the log of its import job shows that the import began to apply components of the package',+ 'component-unmarked': 'the log of its import job marks a component in a way this script does not recognise',+ 'no-answer': 'the read of its import job got no answer',+});++const notProven = (why, reason = REASONS[why]) => ({ proven: false, why, reason });++// The error code of a log that failed with another: `errorcode` is a signed 32-bit integer as text ("-2147188685"), and the platform spells codes in hex (0x80048033), so a code that is exactly such a number is+// shown that way — numbers only, nothing the platform wrote.+function otherError(errorcode) {+ if (errorcode === undefined) return notProven('other-error', 'the log of its import job does not give the error code the import failed with');+ const canonical = /^(?:0|-?[1-9]\d{0,9})$/.test(errorcode) ? Number(errorcode) : NaN;+ if (!Number.isInteger(canonical) || canonical < -(2 ** 31) || canonical > 2 ** 31 - 1) return notProven('other-error', 'the log of its import job gives an error code this script does not recognise');+ return notProven('other-error', `the log of its import job says the import failed with error 0x${(canonical >>> 0).toString(16).toUpperCase()}, not with 0x80071151`);+}++/**+ * Whether the row of a refused send's job — `GET importjobs(<id>)?$select=importjobid,completedon,data`, as the client parsed it — proves that the import applied nothing (THE RULE, above).+ * `{ proven: true }`, or `{ proven: false, why, reason }`: `why` is a key (`REASONS`, `other-error`), `reason` the words that say it. Never throws, whatever it is given.+ */+function refusedBeforeAnyComponent(row) {+ try {+ if (!row || typeof row !== 'object' || Array.isArray(row)) return notProven('no-log');+ const { completedon, data } = row;+ if (typeof completedon !== 'string' || completedon.trim() === '') return notProven('unfinished');+ if (typeof data !== 'string' || data === '') return notProven('no-log');+ if (data.length > MAX_JOB_LOG_CHARS) return notProven('log-too-large');+ // Every element is wanted: the rule is about ALL of them (none but the package's own checks may be processed).+ const read = readXmlElements(data, () => true);+ if (!read.ok) return notProven('log-unreadable');+ // The one element with no ancestor is the root: a nested element of the same name is an ordinary element.+ const root = read.elements.find((element) => element.path === '');+ if (!root || root.name !== 'importexportxml') return notProven('not-an-import-log');+ if (root.attrs.succeeded !== 'failure') return notProven('not-a-failure');+ if (root.attrs.errorcode !== CONCURRENCY_ERRORCODE) return otherError(root.attrs.errorcode);+ const manifests = read.elements.filter((element) => element.name === 'solutionManifest');+ if (manifests.length === 0) return notProven('no-manifest');+ for (const manifest of manifests) {+ if (manifest.attrs.processed === 'true') return notProven('manifest-processed');+ if (manifest.attrs.processed !== 'false') return notProven('manifest-unmarked');+ }+ for (const element of read.elements) {+ if (element === root || element.name === 'solutionManifest' || PACKAGE_CHECKS.has(element.name)) continue;+ const processed = element.attrs.processed;+ if (processed === undefined || processed === 'false') continue;+ return notProven(processed === 'true' ? 'component-processed' : 'component-unmarked');+ }+ return { proven: true };+ } catch {+ // Not reachable for what the client hands over (parsed JSON), and the answer to anything that does throw is the one answer that is always safe.+ return notProven('no-log');+ }+}++/**+ * What the answer to the read of a refused send's job proves: `{ proven: true, proof }` — PROOF_ABSENT for a 404, PROOF_LOG for a 200 whose row proves it (refusedBeforeAnyComponent) — or `{ proven: false, why, reason }`.+ * `answer` is `{ status, body }` as the client gives it, or null when the read got no answer. A 404 is proof whatever its body says: the job does not exist, so nothing was done under it; any other status+ * than 200 (the job's row), a 401, a 403, a throttle, a 5xx, is no proof, because it says nothing of the job.+ */+function proveRefusedImport(answer) {+ if (!answer || typeof answer !== 'object' || !Number.isInteger(answer.status)) return notProven('no-answer');+ if (answer.status === 404) return { proven: true, proof: PROOF_ABSENT };+ if (answer.status !== 200) return notProven('unreadable', `the read of its import job answered HTTP ${answer.status}, which is neither the job nor a 404`);+ const verdict = refusedBeforeAnyComponent(answer.body);+ return verdict.proven ? { proven: true, proof: PROOF_LOG } : verdict;+}++module.exports = { refusedBeforeAnyComponent, proveRefusedImport, MAX_JOB_LOG_CHARS, CONCURRENCY_ERRORCODE, PROOF_ABSENT, PROOF_LOG, REASONS };diff --git a/plugins/model-apps/scripts/lib/maker-sdk.js b/plugins/model-apps/scripts/lib/maker-sdk.jsindex 7155a8226..a07fa0316 100644--- a/plugins/model-apps/scripts/lib/maker-sdk.js+++ b/plugins/model-apps/scripts/lib/maker-sdk.js@@ -23,14 +23,19 @@// 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// 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 the header from the workspace copy whenever its own comparison-// read of the header cannot be made, and the build never edits a header text that is not plain, so the request itself is the last place to stop one. Guarded here, once, so no script that makes an SDK+// `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 comparison+// read of the header cannot be made, and the build never sends a header text that is not plain (it takes such a text off the copy before it pushes it), so for a push the build did not clean the request itself is the last place to stop one. Guarded here, once, so no script that makes an SDK// can leave an app push unguarded (tests/maker-sdk.test.js pins that no script makes one another way); the refusal is an SdkError (APP_HEADER_NOT_PLAIN_TEXT), which the bundle rethrows as it is. No request// is added or changed: only writes of that row are looked at, and every other member of the client runs on the client itself, so a client whose methods keep private state still works.+//+// The `workspaceStorage` the caller names is handed to the SDK with one addition too (lib/output-redaction.js): every text it is asked to write has the access tokens this process obtained taken out of it. The SDK writes each file+// of its workspace — an artifact, its metadata, the manifest — through the storage's `writeTextAtomic`, and through nothing else, so a token a service repeated in an answer (which is the caller's data and is returned as it came) cannot+// land in a file. The folder, the paths and every other member are the storage's own: the wrapper has it for a prototype, so a caller's `instanceof` and the SDK's own look for a file-system storage still hold.const bundle = require('../vendor/cds-maker-sdk.cjs');const { loadVendoredTypeScript } = require('./typescript-compiler.js');const { guardTableLists } = require('./collection-answers.js');const { guardAppHeaderWrites } = require('./app-header-text.js');+const { guardWorkspaceStorage } = require('./output-redaction.js');// `create` given the vendored compiler unless the options name one, and — only for a caller that asked — the Power Apps service client// (a seam for the test: the bundle's own exports are read-only). The `connectivity` request itself is the factory's, never the SDK's.@@ -40,6 +45,7 @@ function withVendoredCompiler(create) {const made = { typescript: () => loadVendoredTypeScript(), ...forSdk };if (made.httpClient) made.httpClient = guardTableLists(made.httpClient, (code, message) => new bundle.SdkError(code, message));if (made.httpClient) made.httpClient = guardAppHeaderWrites(made.httpClient, (code, message) => new bundle.SdkError(code, message));+ if (made.workspaceStorage) made.workspaceStorage = guardWorkspaceStorage(made.workspaceStorage);if (connectivity && made.powerAppsServiceClient === undefined) {// Required here, not at the top: the client pulls in the Azure CLI token code, which an instance that never reads connections does not need.const { createPowerAppsServiceClient } = require('./power-apps-service-client.js');diff --git a/plugins/model-apps/scripts/lib/output-redaction.js b/plugins/model-apps/scripts/lib/output-redaction.jsnew file mode 100644index 000000000..04441224d--- /dev/null+++ b/plugins/model-apps/scripts/lib/output-redaction.js@@ -0,0 +1,638 @@+'use strict';+// Keeps every access token a process obtained out of everything the plugin WRITES.+//+// THE THREAT. A service that rejects or fails a request may repeat the bearer token it was sent in the diagnostic it answers with — whole, or by a part of it (https://www.rfc-editor.org/rfc/rfc7519#section-3) — and+// spelled however the text was made on its way: PLAIN; FOLDED (a gateway wraps a long value onto several lines, a column is wrapped at any width, a console prints a long string in pieces joined by `' +`, a console+// that prints in colours puts its codes between the pieces); or ESCAPED (a JSON body escapes a character as `\u0073` or a line break as `\r\n`, a body that was JSON inside JSON doubles every backslash, util.inspect+// escapes a control character as `\x0b`, and a literal backslash can stand right before a part of the token). A token the process obtained must not reach anything the plugin writes in any of those spellings. The+// service is NOT assumed to be an adversary that has the token and crafts text to defeat the reader (it would not need to: it has the token); a text that tries is refused, not guessed at (see COST).+//+// THE EXPOSURE. A token reaches a script's output when something the process reads quotes it. The SDK quotes a failed part of a `$batch` answer into the error it raises, returns a refused read as a warning, and hands a+// successful answer's data on; and the scripts print that text, journal it and write it into files. The Dataverse HttpClient (lib/sdk-http-client.js) takes the token out of an answer that is not a success — where the text+// holds it literally — but a success is returned byte for byte: a change set the service refuses as a whole is answered HTTP 200 with the one part that failed, and the strict readers that prove from a `$batch` answer what+// a change set did count the bytes each part declares, so the answer cannot be rewritten (what they prove, and the page backend's retry that follows from it, would change). The answer is the caller's.+//+// WHY AT THE OUTPUT. The text has more roads out of the SDK than anyone can list — the message and stack of an error, an object it keeps beneath it (frozen, or with accessors that must not be run to look), a warning in a+// result, a reason, the data of an answer — and every one of them ends in the same few places: the two streams a script prints on and the files it writes. There the text is a string, nothing is walked and no getter is run;+// the SDK's errors, its warnings and the service's answers stay exactly what they were; and a path nobody thought of cannot miss the token. Every token the process OBTAINED is known (a token is noted where it is read from the Azure+// CLI, lib/dataverse-auth.js, and where a client sends it), and none of them is written. The text is read AFTER a formatter made it (an error printed by `console.error` is formatted inside the console, from objects that+// must not be walked), so the reader reads what every formatter in the plugin adds between two characters of a string — white space, the joins and colour codes of util.inspect, escapes — as a fold (see below).+//+// EVERY OUTPUT PATH (sink), and what covers it:+// - stdout and stderr: `process.stdout.write` and `process.stderr.write` are wrapped (guardStream) the moment the first token is obtained — never before, so a process that has no token is untouched. Every `console.*` call+// (in colours too), every script's result printer and warning printer, the build's progress lines, a library's own `console.warn` and the SDK bundle's end there. A text is cleaned as a STRING; bytes (a Buffer) are passed+// as they are: nothing in the plugin writes bytes to a stream, and a test runner's own frames are bytes. `emitResult` (lib/dataverse-auth.js) also cleans its own text, so a result is clean where a caller has replaced the+// stream's `write`. The writes a `process.exit` follows at once are made blocking first (makeWritesBlocking), so that what is written there is whole when the process ends — not only clean.+// - what Node itself prints when an error ends the process (an uncaught exception, an unhandled rejection): it never passes through `process.stderr.write`, so a handler prints it, cleaned, when nothing else handles the error+// (guardFatalErrors).+// - the files the plugin writes: `writeFileSafe` and `appendFileSafe` (lib/safe-fs.js: the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, the plan, the settings template),+// `writeFileAtomic` (lib/apply-snapshot-store.js: the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records) and the SDK's workspace storage — every file the bundle writes goes through its+// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.+// - in the pcf plugin (which carries a copy of this module): its streams and its fatal errors as above (its scripts note their tokens through the same lib/dataverse-auth.js), the receipt `pcf-push.js` writes+// (`pcf-receipt.json`) and the SDK workspace `makePcfSdk` makes; pcf's tests/pcf-push-token.test.js lists every other write of pcf and says why none of them can carry a token.+// - not covered, by design: bytes (a Buffer given to a writer is written as it is); a token another process obtained (`pac` has its own); another encoding of a token (percent-encoding, base64 of a whole header, HTML+// entities — nothing is known to quote a token in one, and a reader that guessed at them would blank ordinary text); a token written in two separate calls to `write` (no script writes a message in pieces); a token a+// formatter CUT SHORT (util.inspect prints at most 10,000 characters of a string, and the end of a part cut off there is not the part); a raw control character other than white space and ESC between two of its characters.+//+// A TOKEN AS A TEXT SPELLS IT. A token is looked for as the text spells it, one character at a time: a character is itself, or an escape of it (`\u0073` for `s`, in either case of hex; `\x73`; `\/` for `/`), and between+// two characters of the token there may be a fold — any white space, a line break and its indentation (the obsolete line folding of https://www.rfc-editor.org/rfc/rfc9112#section-5.2, a column a gateway wrapped), spelled as+// it is or as its escape (`\r\n`, `\t`, `\b`), the quote, plus sign and line break `util.inspect` prints between the pieces of a long string (`'abc\r\n' +` newline `' def'`), a terminal colour code (`\u001b[32m`, also+// among the quote, plus sign and line break), or a STRAY backslash. A run of backslashes before an escape is one escape: a body that was JSON inside JSON holds `\\u0073` and `\\r\\n`. Nothing in a text says whether a+// backslash before a letter is an escape or a literal backslash (`\n` is a line break, or a backslash and the first `n` of a signature), so an escape that can be both is read BOTH ways, and a token found either way is+// the token. The span from the token's first character to its last — the folds and escapes inside it included, an escape always whole — becomes `<token>`, and the white space before and after it stays. In JSON text the+// span is always inside one string and never leaves half of an escape, so what was JSON is still JSON (the baseline and the journal are read back by the next run).+//+// COST. Every needle (the token, and each of its parts of 24 characters or more: needlesOf) is searched in ONE pass over the characters the text spells, as Knuth-Morris-Pratt does, in lockstep, so a text of any size takes time+// that grows with its size and a near miss of a long needle over and over costs no more than any other text; an escape read the other way starts a reading that is followed next to the pass, and at most MAX_READINGS of them+// per needle are alive at once — a real token keeps one or two — so no text makes the search backtrack or grow faster than the text. A text that would need more is not guessed at: the search fails, and every caller fails+// closed (tests/output-redaction.test.js measures all of it). A text that holds no token comes back as the very string.+const { inspect } = require('node:util');++// What takes the place of a token, or of a part of one, in a text.+const TOKEN_MARKER = '<token>';+// Not the token alone: what an error or a gateway repeats of a bearer token is often one part of it. A token is `header.payload.signature` (three base64url parts joined by dots;+// https://www.rfc-editor.org/rfc/rfc7519#section-3), so each part long enough to be distinctive is taken out too.+const MIN_TOKEN_PART_LENGTH = 24;+// What is kept as a token: the floor of the Dataverse client's own scrubbing. A shorter value is a test's, and would be taken out of ordinary words.+const MIN_TOKEN_LENGTH = 16;++// The texts of one token that are taken out of a message: the token itself and each of its parts that is long enough to be distinctive, the longest first, once each.+function needlesOf(token) {+ const needles = new Set([token]);+ for (const part of token.split('.')) if (part.length >= MIN_TOKEN_PART_LENGTH) needles.add(part);+ return [...needles].sort((a, b) => b.length - a.length);+}++// ---- Reading a text as it spells a token ----------------------------------------------------------------------------------------------------------------------------------------------------------++// White space as a regular expression's `\s` reads it: a fold can be made of any of it, and the plugin's own tests normalize a text with that class.+function isSpace(unit) {+ return unit === 0x20 || (unit >= 0x09 && unit <= 0x0d) || unit === 0xa0 || unit === 0x1680 || (unit >= 0x2000 && unit <= 0x200a)+ || unit === 0x2028 || unit === 0x2029 || unit === 0x202f || unit === 0x205f || unit === 0x3000 || unit === 0xfeff;+}++// A needle the reader cannot read: it holds white space, which the reader skips, a backslash, which it reads as the start of an escape, or an ESC, which it reads as the start of a terminal colour code. Such a token is+// searched for literally (see redactWith).+function unreadable(needle) {+ for (let i = 0; i < needle.length; i += 1) {+ const unit = needle.charCodeAt(i);+ if (unit === 0x5c || unit === 0x1b || isSpace(unit)) return true;+ }+ return false;+}++const hexValue = (unit) => (unit >= 0x30 && unit <= 0x39 ? unit - 0x30 : unit >= 0x41 && unit <= 0x46 ? unit - 0x37 : unit >= 0x61 && unit <= 0x66 ? unit - 0x57 : -1);++// What the reader makes of one item: -1 nothing (a fold), a character's code, or DUAL — an escape that is read two ways, because nothing in a text says whether its backslash is an escape or a literal backslash: as the+// escape (`primaryCode`: the character it stands for, or -1 for one that is white space or a control character) and as the letters after the backslashes (`literalFrom` up to the item's end: `n`, `u0073`, `x41`).+// Variables and not part of a result: this runs for every character of a text that may be megabytes long, and an object for each would be most of its cost.+const DUAL = -2;+let spelledWidth = 1;+let primaryCode = -1;+let literalFrom = 0;++// The item at `at` that begins with a backslash. A RUN of backslashes and what follows it is ONE item, whatever the run's length (JSON inside JSON doubles every backslash), and it is always read whole, so that a match+// never leaves half of an escape behind:+// `\u0073` `\\u0073` (either case of hex) → 's', or the letters `u0073` width of the run + 5 (a white space it spells is nothing)+// `\x73` (how util.inspect escapes a control) → 's', or the letters `x73` width of the run + 3+// `\/` → '/' width of the run + 1+// `\n` `\r` `\t` `\f` `\b` `\v` → nothing (a line break, a control), or the letter itself width of the run + 1+// any other backslash run, before anything else or at the end of the text — a STRAY backslash between two characters of a token: nothing, a fold, width of the run (what follows is read on its own)+// https://www.rfc-editor.org/rfc/rfc8259#section-7 lists the escapes of a JSON string; util.inspect adds `\x..` and `\v` for a JavaScript string. A run read as one item (and not one backslash at a time) is what keeps a+// long run of backslashes from being read again at each of them: the reader stays linear.+function readEscape(text, at) {+ let end = at + 1;+ while (text.charCodeAt(end) === 0x5c) end += 1;+ const run = end - at;+ const letter = text.charCodeAt(end);+ const digits = letter === 0x75 ? 4 : letter === 0x78 ? 2 : 0;+ if (digits > 0) {+ let decoded = 0;+ for (let i = 1; i <= digits && decoded >= 0; i += 1) {+ const value = hexValue(text.charCodeAt(end + i));+ decoded = value < 0 ? -1 : (decoded << 4) | value;+ }+ if (decoded >= 0) {+ spelledWidth = run + 1 + digits;+ primaryCode = isSpace(decoded) ? -1 : decoded;+ literalFrom = end;+ return DUAL;+ }+ } else if (letter === 0x2f) {+ spelledWidth = run + 1;+ return 0x2f;+ } else if (letter === 0x6e || letter === 0x72 || letter === 0x74 || letter === 0x66 || letter === 0x62 || letter === 0x76) {+ spelledWidth = run + 1;+ primaryCode = -1;+ literalFrom = end;+ return DUAL;+ }+ spelledWidth = run;+ return -1;+}++// The most parameter bytes a terminal colour code is read with: util.inspect writes two or three (`\u001b[32m`); a longer one is no code anybody prints, and a bound keeps the reader from scanning on.+const MAX_CODE_PARAMETERS = 32;++// Where the terminal code that begins at `at` (an ESC) ends, or -1 for an ESC that does not begin one: ESC, `[`, up to MAX_CODE_PARAMETERS parameter and intermediate bytes (0x20-0x3f), and one final byte (0x40-0x7e) —+// a control sequence of ECMA-48 (https://ecma-international.org/publications-and-standards/standards/ecma-48/, section 5.4), the shape of every colour code (`\u001b[32m`, `\u001b[1;31m`, `\u001b[39m`).+function codeEnd(text, at) {+ if (text.charCodeAt(at + 1) !== 0x5b) return -1;+ const limit = at + 2 + MAX_CODE_PARAMETERS;+ for (let i = at + 2; i <= limit; i += 1) {+ const unit = text.charCodeAt(i);+ if (unit >= 0x40 && unit <= 0x7e) return i + 1;+ if (!(unit >= 0x20 && unit <= 0x3f)) return -1;+ }+ return -1;+}++// What may stand between the quote, the plus sign and the line break that join the pieces of a long string: spaces, tabs and — on a console that prints in colours — the codes that end one piece's colour and begin the next's.+function skipJoin(text, at) {+ let i = at;+ for (;;) {+ const unit = text.charCodeAt(i);+ if (unit === 0x20 || unit === 0x09) {+ i += 1;+ continue;+ }+ const end = unit === 0x1b ? codeEnd(text, i) : -1;+ if (end < 0) return i;+ i = end;+ }+}++// A long string as `util.inspect` prints it — `console.error(error)` prints the body an error keeps that way — is cut after each line break and the pieces are joined as source code joins them; on a console that prints in+// colours (a terminal, or FORCE_COLOR=1) each piece is wrapped in its own colour codes:+// message: 'Rejected bearer abcdefgh\r\n' + message: \u001b[32m'Rejected bearer abcdefgh\r\n'\u001b[39m ++// ' ijklmnop\r\n' + \u001b[32m' ijklmnop\r\n'\u001b[39m ++// ' qrstuvwx' \u001b[32m' qrstuvwx'\u001b[39m+// The closing quote, the codes, the plus sign, the line break, the indentation and the same quote again stand where the string has no character, so they are skipped like a fold. Anything else after a quote is the quote, a+// character of its own.+function readContinuation(text, at, quote) {+ let i = skipJoin(text, at + 1);+ if (text.charCodeAt(i) !== 0x2b) return quote;+ i = skipJoin(text, i + 1);+ if (text.charCodeAt(i) === 0x0d) i += 1;+ if (text.charCodeAt(i) !== 0x0a) return quote;+ i = skipJoin(text, i + 1);+ if (text.charCodeAt(i) !== quote) return quote;+ spelledWidth = i + 1 - at;+ return -1;+}++// `skip` says what an ASCII character is to the reader: 0 a character like any other, 1 white space, 2 a quote that may begin a continuation (it is 0 where a needle holds that character), 3 an ESC — a terminal code, or a+// lone ESC, is a fold: a console that prints in colours puts codes between the pieces of a string, and a colourful log line can put one anywhere.+function readSpelled(text, at, skip) {+ const unit = text.charCodeAt(at);+ spelledWidth = 1;+ if (unit === 0x5c) return readEscape(text, at);+ if (unit < 128) {+ const kind = skip[unit];+ if (kind === 0) return unit;+ if (kind === 1) return -1;+ if (kind === 3) {+ const end = codeEnd(text, at);+ if (end > 0) spelledWidth = end - at;+ return -1;+ }+ return readContinuation(text, at, unit);+ }+ return isSpace(unit) ? -1 : unit;+}++// The longest proper prefix of `needle.slice(0, i + 1)` that is also its suffix, for each i: where a search for the needle goes on after a mismatch, so that it never reads a character twice+// (https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm).+function failureTable(needle) {+ const table = new Int32Array(needle.length);+ for (let i = 1, k = 0; i < needle.length; i += 1) {+ while (k > 0 && needle.charCodeAt(i) !== needle.charCodeAt(k)) k = table[k - 1];+ if (needle.charCodeAt(i) === needle.charCodeAt(k)) k += 1;+ table[i] = k;+ }+ return table;+}++// How many readings of ONE needle that took an escape's letters (and not the escape) the search follows at once. A random token keeps one or two alive on any text, and a needle that is one letter over and over keeps+// one per letter; more than this needs a text made to match the needle almost everywhere — i.e. made by someone who has the token. The bound keeps the cost linear on any text: past it the search does not guess which+// reading to drop (a dropped one could be the token), it fails, and every caller fails closed (a stream writes WITHHELD, a file is not written).+const MAX_READINGS = 128;+const TOO_MANY_READINGS = 'output-redaction: a text holds too many ways to read a token for it to be checked';++// Everything the search needs of a set of tokens, made once and not for each text: the needles it can read and each one's failure table, the first character of each (a text is only looked at closely where one could start,+// or where a needle is already being matched), what the reader skips, and the tokens that still need a literal search for a needle of their own that the reader cannot read.+function prepare(tokens) {+ const live = [...new Set(tokens.filter((token) => typeof token === 'string' && token !== ''))];+ if (live.length === 0) return null;+ const needles = [...new Set(live.flatMap(needlesOf))].filter((needle) => !unreadable(needle));+ const skip = new Uint8Array(128);+ for (const unit of [0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20]) skip[unit] = 1;+ for (const unit of [0x22, 0x27, 0x60]) skip[unit] = 2;+ skip[0x1b] = 3;+ const firstUnits = new Uint8Array(65536);+ for (const needle of needles) {+ firstUnits[needle.charCodeAt(0)] = 1;+ for (let i = 0; i < needle.length; i += 1) {+ const unit = needle.charCodeAt(i);+ if (unit < 128) skip[unit] = 0;+ }+ }+ return {+ needles,+ tables: needles.map(failureTable),+ longest: needles.reduce((length, needle) => Math.max(length, needle.length), 0),+ firstUnits,+ skip,+ literal: live.filter((token) => needlesOf(token).some(unreadable)),+ // The search's working memory, kept with what it is made for: a stream is written in many small pieces, and an array of the longest needle's length made for each would cost more than the search. The search+ // never calls out and never starts another, so one set at a time is all there is.+ starts: new Int32Array(needles.reduce((length, needle) => Math.max(length, needle.length), 1)),+ states: new Int32Array(needles.length),+ // For each needle, the readings that took an escape's letters: how far each is (`states`) and where it began (`begins`), with a second pair the next set is made in, and `slot` — for a state, 1 + its index in the next+ // set — so that two readings that have come equally far are kept once, with the earlier beginning (whatever the later one would find, the earlier one finds with a span that holds it).+ readings: needles.map((needle) => ({+ count: 0,+ states: new Int32Array(MAX_READINGS),+ begins: new Int32Array(MAX_READINGS),+ nextCount: 0,+ nextStates: new Int32Array(MAX_READINGS),+ nextBegins: new Int32Array(MAX_READINGS),+ slot: new Int32Array(needle.length + 1),+ })),+ };+}++// Puts a reading that has come `state` characters into the needle, begun at `begin`, into the next set of `readings`.+function keepReading(readings, state, begin) {+ const index = readings.slot[state] - 1;+ if (index >= 0) {+ if (begin < readings.nextBegins[index]) readings.nextBegins[index] = begin;+ return;+ }+ if (readings.nextCount === MAX_READINGS) {+ for (let i = 0; i < readings.nextCount; i += 1) readings.slot[readings.nextStates[i]] = 0;+ throw new RangeError(TOO_MANY_READINGS);+ }+ readings.nextStates[readings.nextCount] = state;+ readings.nextBegins[readings.nextCount] = begin;+ readings.nextCount += 1;+ readings.slot[state] = readings.nextCount;+}++// A reading that has come `state` characters into `needle`, begun at `begin`, read on through the letters `text[from, end)` of one escape: it ends there (a letter that is not the needle's next character), is a match+// (the span reaches to the end of the escape, so that no half of it is left), or goes on in the next set.+function readLetters(text, from, end, needle, readings, state, begin, spans) {+ let at = state;+ for (let j = from; j < end; j += 1) {+ if (needle.charCodeAt(at) !== text.charCodeAt(j)) return;+ at += 1;+ if (at === needle.length) {+ spans.push([begin, end]);+ return;+ }+ }+ keepReading(readings, at, begin);+}++// An escape that is read two ways (DUAL), spanning `[begin, end)`. For each needle the next set of readings is made of: every reading already followed, taking the escape as the character it stands for (or as nothing) AND+// as its letters; every alignment the main search follows (its state, and each shorter one that is also alive: the failure table's chain), taking the letters; and a new reading beginning at any of the letters. The main+// search then takes the escape's first reading itself. Returns whether any reading is alive.+function forkReadings(text, begin, end, prepared, read, spans) {+ const { needles, tables, longest, starts, states, readings: all } = prepared;+ const primary = primaryCode;+ const from = literalFrom;+ let alive = false;+ for (let n = 0; n < needles.length; n += 1) {+ const needle = needles[n];+ const readings = all[n];+ readings.nextCount = 0;+ for (let i = 0; i < readings.count; i += 1) {+ const state = readings.states[i];+ const began = readings.begins[i];+ if (primary === -1) keepReading(readings, state, began);+ else if (needle.charCodeAt(state) === primary) {+ if (state + 1 === needle.length) spans.push([began, end]);+ else keepReading(readings, state + 1, began);+ }+ readLetters(text, from, end, needle, readings, state, began, spans);+ }+ for (let state = states[n]; state > 0; state = tables[n][state - 1]) readLetters(text, from, end, needle, readings, state, starts[(read - state) % longest], spans);+ const first = needle.charCodeAt(0);+ for (let j = from; j < end; j += 1) if (text.charCodeAt(j) === first) readLetters(text, j, end, needle, readings, 0, begin, spans);+ for (let i = 0; i < readings.nextCount; i += 1) readings.slot[readings.nextStates[i]] = 0;+ [readings.states, readings.nextStates] = [readings.nextStates, readings.states];+ [readings.begins, readings.nextBegins] = [readings.nextBegins, readings.begins];+ readings.count = readings.nextCount;+ if (readings.count > 0 || states[n] > 0) alive = true;+ }+ return alive;+}++// Every needle searched for in ONE pass over the items the text spells, in time that grows with the text: a search that starts again at every character takes seconds on a text that is a needle's first thousand+// characters over and over. A needle's state is how many of its first characters the last items spell — on the escapes' first readings (as the character an escape stands for, or nothing), as Knuth-Morris-Pratt does it.+// An escape that can also be its letters (a literal backslash before an `n`) starts readings that the search follows next to it, a bounded set (forkReadings). A match runs from where the first of its characters is+// spelled to where its last ends — the folds and escapes between them are inside it, and the white space before and after is not. `starts` remembers where each of the last items began, in a ring as long as the longest+// needle, which is all a match can reach back over; an item that cannot start a match while no needle is being matched is counted and not stored, because no match will ever ask for its start. The spans of all the+// needles are then merged where they overlap (a token and its parts do) and each merged span is replaced by one marker; two spans that only touch stay two, as two tokens written one after the other are two.+function takeOutSpelled(text, prepared) {+ const { needles, tables, longest, firstUnits, skip, starts, states, readings: all } = prepared;+ const count = needles.length;+ states.fill(0);+ for (const readings of all) readings.count = 0;+ const spans = [];+ let read = 0;+ let matching = false;+ for (let at = 0; at < text.length;) {+ const begin = at;+ let code = readSpelled(text, at, skip);+ at += spelledWidth;+ if (code === -1) continue;+ let forked = false;+ if (code === DUAL) {+ code = primaryCode;+ let letterStarts = false;+ for (let j = literalFrom; j < at && !letterStarts; j += 1) letterStarts = firstUnits[text.charCodeAt(j)] === 1;+ if (matching || letterStarts) {+ matching = forkReadings(text, begin, at, prepared, read, spans);+ forked = true;+ }+ if (code === -1) continue;+ }+ if (!matching && firstUnits[code] === 0) {+ read += 1;+ continue;+ }+ starts[read % longest] = begin;+ matching = false;+ for (let n = 0; n < count; n += 1) {+ const needle = needles[n];+ const readings = all[n];+ if (!forked && readings.count > 0) {+ let kept = 0;+ for (let i = 0; i < readings.count; i += 1) {+ const state = readings.states[i];+ if (needle.charCodeAt(state) !== code) continue;+ if (state + 1 === needle.length) {+ spans.push([readings.begins[i], at]);+ continue;+ }+ readings.states[kept] = state + 1;+ readings.begins[kept] = readings.begins[i];+ kept += 1;+ }+ readings.count = kept;+ }+ if (readings.count > 0) matching = true;+ const table = tables[n];+ let state = states[n];+ while (state > 0 && needle.charCodeAt(state) !== code) state = table[state - 1];+ if (needle.charCodeAt(state) === code) state += 1;+ if (state === needle.length) {+ spans.push([starts[(read - state + 1) % longest], at]);+ state = table[state - 1];+ }+ states[n] = state;+ if (state > 0) matching = true;+ }+ read += 1;+ }+ if (spans.length === 0) return text;+ spans.sort((a, b) => a[0] - b[0] || b[1] - a[1]);+ let out = '';+ let kept = 0;+ let [from, to] = spans[0];+ for (let i = 1; i <= spans.length; i += 1) {+ const span = spans[i];+ if (span !== undefined && span[0] < to) {+ to = Math.max(to, span[1]);+ continue;+ }+ out += text.slice(kept, from) + TOKEN_MARKER;+ kept = to;+ if (span !== undefined) [from, to] = span;+ }+ return out + text.slice(kept);+}++// `text` with the tokens `prepared` stands for taken out: what the reader finds, and then — only for a token that has a needle the reader cannot read (white space, a backslash or an ESC in it) — a literal search, as the Dataverse+// client's scrubber does it. The reader first, so that a token spelled in one piece is one marker: a literal search first would take out the parts of a token whose dots are inside a fold, and leave `<token>.<token>`+// where the reader finds the whole.+function redactWith(prepared, text) {+ let out = text;+ if (prepared.needles.length > 0) out = takeOutSpelled(out, prepared);+ for (const token of prepared.literal) out = needlesOf(token).reduce((current, needle) => current.split(needle).join(TOKEN_MARKER), out);+ return out;+}++/**+ * `text` with every token in `tokens` taken out of it — whole, and by each of its parts of 24 characters or more — wherever the text spells it: plainly, with a fold in it, with an escape in it (or a stray backslash), or+ * printed over several lines the way `util.inspect` prints a long string, in colours or not. A text that holds none is returned as the same string. Throws a RangeError for a text that holds too many ways to read a token+ * to be checked (MAX_READINGS): a caller must then not write the text.+ * @param {string} text+ * @param {string[]} tokens+ * @returns {string}+ */+function redactTokens(text, tokens) {+ const prepared = prepare(Array.isArray(tokens) ? tokens : []);+ return prepared === null || typeof text !== 'string' || text === '' ? text : redactWith(prepared, text);+}++// ---- The tokens this process obtained -------------------------------------------------------------------------------------------------------------------------------------------------------------++const obtained = new Set();+// Bumped when a token joins, so that what is prepared from the set is made again only then.+let version = 0;+let preparedFor = { version: -1, prepared: null };++/**+ * Notes an access token this process obtained or sent, once, and — the first time — puts the guards on what the process writes (installOutputGuard). Called where a token is read from the Azure CLI and where a client sends+ * one, so a token is known from the moment it exists, and before any text that could repeat it can be written. A value shorter than 16 characters is no access token and is ignored.+ * @param {unknown} token+ */+function noteToken(token) {+ if (typeof token !== 'string' || token.length < MIN_TOKEN_LENGTH || obtained.has(token)) return;+ obtained.add(token);+ version += 1;+ installOutputGuard();+}++/** Every access token this process has obtained, once each, the first obtained first. */+function obtainedTokens() {+ return [...obtained];+}++/**+ * `text` with every token this process has obtained taken out of it. Anything that is not a string — bytes, a number — is returned as it is, and so is a text when no token has been obtained yet. Throws as `redactTokens`+ * does for a text that cannot be checked; every caller then fails closed (the guard on a stream writes a notice instead of the text, a file writer writes nothing and reports the failure).+ * @template T+ * @param {T} text+ * @returns {T}+ */+function redactOutput(text) {+ if (typeof text !== 'string' || obtained.size === 0 || text === '') return text;+ if (preparedFor.version !== version) preparedFor = { version, prepared: prepare([...obtained]) };+ return redactWith(preparedFor.prepared, text);+}++// ---- The streams, an error that ends the process, and the SDK's workspace --------------------------------------------------------------------------------------------------------------------------++// Put on the function that wraps a stream's `write`, so that a stream is wrapped once however many times it is asked.+const GUARDED = Symbol.for('power-platform-skills.output-redaction.guarded');+// What is written where a text could not be cleaned (the cleaning itself failed): not the text, which may hold the token — a failure here is rare enough to be loud.+const WITHHELD = '[output withheld: it could not be checked for an access token]\n';+// A string given with one of these encodings is not text (`write('6162', 'hex')`), so it is not read as text.+const BINARY_ENCODINGS = /^(?:hex|base64|base64url)$/i;++/**+ * Makes `stream.write` take the tokens out of every string it is given. The wrapper is the stream's own `write` property, put where the original was: whatever replaces it later replaces it whole, and a caller that wraps it+ * (`const write = stream.write; stream.write = …`) wraps it with the guard inside. Bytes are passed on as they are. Returns false for a stream that is already guarded or has no `write`.+ * @param {{ write: Function }} stream+ * @param {(text: string) => string} [redact]+ * @returns {boolean}+ */+function guardStream(stream, redact = redactOutput) {+ if (!stream || typeof stream.write !== 'function' || stream.write[GUARDED]) return false;+ const write = stream.write;+ const guarded = function writeWithoutTokens(chunk, ...rest) {+ let given = chunk;+ if (typeof chunk === 'string' && !(typeof rest[0] === 'string' && BINARY_ENCODINGS.test(rest[0]))) {+ try {+ given = redact(chunk);+ } catch {+ given = WITHHELD;+ }+ }+ return write.call(this, given, ...rest);+ };+ guarded[GUARDED] = true;+ stream.write = guarded;+ return true;+}++/**+ * Makes the writes to each of `streams` blocking from here on: a `write` returns when the stream has taken the whole text. For the last writes of a process — the ones a `process.exit` follows at once (`emitResult` in+ * lib/dataverse-auth.js, the printer of an error that ends the process below, a script's own result printer). Nothing else about the stream changes: the text still goes through its `write`, the guard above included.+ * Each plugin's tests keep a tripwire on this (tests/exit-writes-inventory.test.js in model-apps, tests/pcf-exit-writes-inventory.test.js in pcf): a syntactic scan of the source that fails on a new exit that has+ * no such call before it and is not listed with the bound that makes it safe, and on a call that comes after a write in its own block or leaves out a stream written before the exit. It reads the source, not what+ * runs: the tests that record the order of a process's own calls (tests/printers-whole-before-exit.test.js with helpers/write-order-preload.js) are what show that a printer makes its stream blocking before it writes.+ *+ * WHY. Node writes to a pipe asynchronously on Linux and macOS, and synchronously on Windows (https://nodejs.org/api/process.html#a-note-on-process-io). What the pipe does not take at once — more than its buffer holds,+ * 64 KiB on Linux — is queued, and `process.exit` ends the process without waiting for the queue (https://nodejs.org/api/process.html#processexitcode). An agent reads a script's result through a pipe, so a large+ * result reached it cut short: on the Linux and macOS CI jobs the 3.5 MB result of tests/output-token-boundary.test.js ended mid-string (for example "Unterminated string in JSON at position 146176").+ * A blocking handle is what Node itself gives a terminal (`tty.WriteStream` calls `setBlocking(true)`) and, on Windows, a pipe on stdout or stderr (`net.Socket`: "Make stdout and stderr blocking on Windows"); libuv then+ * completes every write synchronously (uv_stream_set_blocking: https://docs.libuv.org/en/v1.x/stream.html). tests/result-whole-before-exit.test.js gives a script the kind of pipe Linux and macOS give it, on every+ * platform: without this, a 3.5 MB result arrived in part on Windows too; with it, whole.+ *+ * SAFE because it is done at the end: the process exits right after, so no other work waits behind a blocking write. A reader that is reading takes the text; one that has stopped reading now holds the script at its last+ * write — as a pipe on Windows always has — instead of receiving a result cut short. A hook is no exception: a host that read a hook's output only after the hook had exited would now wait until its own time limit+ * for the hook ends it, where it used to read a message cut short; a reader that closes its end does not hold it: the write fails at once (EPIPE).+ * On POSIX the flag belongs to the pipe's open file description, which every process holding that end shares, and Node puts it back as+ * it found it when the process exits (ResetStdio, src/node.cc). A write queued BEFORE this call (only when the reader has left more than a pipe's buffer unread, with no turn of the event loop since) stays queued, and the+ * writes after it wait behind it in the stream's own buffer: Node has no synchronous flush of a queued write. That is why this is called before the last writes, not just before `process.exit`.+ *+ * A stream with no such handle — a file (written synchronously already), a worker's stdout, a test's stand-in — is left as it is, and so is a handle that answers with an error code (a terminal on Windows answers EINVAL:+ * libuv blocks only a pipe there). Never throws: the text is written either way.+ * @param {...?{ _handle?: ?{ setBlocking?: Function } }} streams+ */+function makeWritesBlocking(...streams) {+ for (const stream of streams) {+ try {+ const handle = stream && stream._handle;+ if (handle && typeof handle.setBlocking === 'function') handle.setBlocking(true);+ } catch {+ // A handle that throws (a closed or foreign one): the text goes out as it always did.+ }+ }+}++// Node prints an error that ends the process (an exception nothing caught, a promise rejected and never handled) from its own code, and not through `process.stderr.write`, so the wrapper on the stream does not see it+// (measured on Node 20 and 22: a replaced `write` is never called). With a listener the default — print, exit with status 1 — is replaced by this one, which prints the same error, cleaned, and exits with the same status.+// Only when nothing else handles the error: a test runner has its own listener, and a host that added one after this one has taken the decision over. `breakLength: Infinity` keeps `inspect` from cutting a long string+// into pieces joined with `+`, which is the one thing that could make a cleaned text differ from the text a person reads. The write is made blocking first (makeWritesBlocking): this handler exits right after it, so a+// long error (an answer the SDK quoted into it) would otherwise reach a pipe on Linux and macOS cut short.+function guardFatalErrors() {+ if (process.listenerCount('uncaughtException') > 0) return false;+ process.on('uncaughtException', function fatalWithoutTokens(error, origin) {+ if (process.listenerCount('uncaughtException') > 1) return;+ let text;+ try {+ text = inspect(error, { breakLength: Infinity, depth: 10 });+ } catch {+ text = 'an error that could not be printed';+ }+ try {+ // Inside the try, with the write: reading `process.stderr` can itself throw (a host that replaced it with an accessor that does), and the+ // process must still end with status 1, as an error nothing caught always does — a throw out of this handler would end it with 7 instead+ // ("Internal Exception Handler Run-Time Failure": https://nodejs.org/api/process.html#exit-codes).+ makeWritesBlocking(process.stderr);+ process.stderr.write(`${redactOutput(`${origin === 'unhandledRejection' ? 'Uncaught (in promise) ' : 'Uncaught '}${text}`)}\n`);+ } catch {+ // The stream is gone: there is nobody to tell.+ }+ process.exit(1);+ });+ return true;+}++let installed = false;+/**+ * Puts the guards on this process: stdout, stderr and the error that ends the process. Called by `noteToken` the first time a token is noted — not at load, so that a process that never has a token is untouched —+ * and harmless to call again. It never throws: a token has already been obtained, and failing here would fail the read that obtained it.+ */+function installOutputGuard() {+ if (installed) return;+ installed = true;+ for (const attempt of [() => guardStream(process.stdout), () => guardStream(process.stderr), guardFatalErrors]) {+ try {+ attempt();+ } catch {+ // A host with no usable stream: the rest is still guarded.+ }+ }+}++/**+ * `storage` (an SDK WorkspaceStorage) with the tokens taken out of every text it is asked to write. The SDK writes each file of its workspace — an artifact, its metadata, the manifest — through `writeTextAtomic(key, text)`, and+ * through nothing else, so this is every file the SDK writes. Everything else is the storage's own and runs ON the storage: a method is called with the storage as `this` and an accessor is read from it, because a+ * storage may keep its state in `#private` fields, which only the object they were made for can read (a wrapper that is merely a child of the storage would be `this` instead, and fail). The wrapper is a Proxy over an+ * empty child of the storage — not over the storage itself, whose own frozen members would bind what a Proxy may answer — so the SDK still finds the folder (`pathFor`, `getRoot`) and an `instanceof` still holds; a value+ * set through it is set on the storage.+ * @template T+ * @param {T} storage+ * @param {(text: string) => string} [redact]+ * @returns {T}+ */+function guardWorkspaceStorage(storage, redact = redactOutput) {+ if (storage === null || typeof storage !== 'object' || typeof storage.writeTextAtomic !== 'function') return storage;+ const writeTextAtomic = function writeTextAtomicWithoutTokens(key, text, ...rest) {+ return storage.writeTextAtomic(key, typeof text === 'string' ? redact(text) : text, ...rest);+ };+ // One function per member, so that a member read twice is the same function, as it is on the storage.+ const onStorage = new Map();+ return new Proxy(Object.create(storage), {+ get(target, key) {+ if (key === 'writeTextAtomic') return writeTextAtomic;+ const value = Reflect.get(storage, key, storage);+ if (typeof value !== 'function' || key === 'constructor') return value;+ if (!onStorage.has(value)) onStorage.set(value, function onTheStorage(...args) { return value.apply(storage, args); });+ return onStorage.get(value);+ },+ set(target, key, value) {+ return Reflect.set(storage, key, value, storage);+ },+ });+}++module.exports = {+ TOKEN_MARKER,+ needlesOf,+ noteToken,+ obtainedTokens,+ redactTokens,+ redactOutput,+ guardStream,+ makeWritesBlocking,+ guardFatalErrors,+ installOutputGuard,+ guardWorkspaceStorage,+};diff --git a/plugins/model-apps/scripts/lib/relationship-metadata.js b/plugins/model-apps/scripts/lib/relationship-metadata.jsindex 251a00273..2de52406b 100644--- a/plugins/model-apps/scripts/lib/relationship-metadata.js+++ b/plugins/model-apps/scripts/lib/relationship-metadata.js@@ -18,9 +18,23 @@// A derived property in $select without the matching cast → 400, which is why each collection select// below omits the entity the collection is already scoped to and the caller stamps that end.// Some Web API surfaces capitalize the error envelope as "Error", so both spellings are read.+//+// An N:N is read with three properties more than the three measured above — IntersectEntityName, Entity1IntersectAttribute and Entity2IntersectAttribute —+// because its identity is not its two tables: it is the table that holds the links and the column each table has in it (MANY_TO_MANY_SELECT).+// They are documented properties of ManyToManyRelationshipMetadata, in the collection and in the cast alike, and are read here like the others (scalars):+// …/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute → 200+// {"value":[{"SchemaName":"contoso_project_contoso_task","Entity1LogicalName":"contoso_project","Entity2LogicalName":"contoso_task",+// "IntersectEntityName":"contoso_project_task_links","Entity1IntersectAttribute":"contoso_projectid","Entity2IntersectAttribute":"contoso_taskid"}]}+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/manytomanyrelationshipmetadata+// (documented, not yet measured live.)const { odataLit } = require('./odata.js');+// The properties that say which N:N a row is. The name and the two tables alone do not say it: the create names the intersect table too — `relationships[].intersectEntityName`,+// or the lower-cased schema name when the spec names none — so a relationship under the same name and tables with another intersect table is not the one the spec asked+// for. The two columns are the key each table has in the intersect table (typically `<table>id`).+const MANY_TO_MANY_SELECT = 'SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute';+const COLLECTION = {OneToMany: {segment: 'OneToManyRelationships',@@ -32,7 +46,7 @@ const COLLECTION = {},ManyToMany: {segment: 'ManyToManyRelationships',- select: 'SchemaName,Entity1LogicalName,Entity2LogicalName',+ select: MANY_TO_MANY_SELECT,},};@@ -70,6 +84,16 @@ async function get(client, path) {}}+// What a read of an N:N states of the table that holds its links and the column each table has in it. Absent (or empty) is kept as it came: it is what+// compareRelationship reads as "not stated". The two spellings are the Web API's (`IntersectEntityName`) and the normalized holder's.+function intersectOf(raw) {+ return {+ intersectEntityName: raw && (raw.IntersectEntityName || raw.intersectEntityName),+ entity1IntersectAttribute: raw && (raw.Entity1IntersectAttribute || raw.entity1IntersectAttribute),+ entity2IntersectAttribute: raw && (raw.Entity2IntersectAttribute || raw.entity2IntersectAttribute),+ };+}+function mapCollectionRow(raw, kind, entityLogical) {const schemaName = raw && (raw.SchemaName || raw.schemaName);if (kind === 'ManyToMany') {@@ -78,6 +102,7 @@ function mapCollectionRow(raw, kind, entityLogical) {type: 'ManyToMany',entity1: raw && (raw.Entity1LogicalName || raw.entity1),entity2: raw && (raw.Entity2LogicalName || raw.entity2),+ ...intersectOf(raw),};}if (kind === 'ManyToOne') {@@ -136,12 +161,15 @@ function castKind(body) {}function holderFromCast(body, kind) {+ // The body is taken as it is. A 200 that carries none of the selected properties (`{}`) gives a holder with nothing stated:+ // the name is known to be held, and nothing about whose it is — which compareRelationship reads as unproven, never as the declared one.if (kind === 'ManyToMany') {return {schemaName: body && body.SchemaName,type: 'ManyToMany',entity1: body && body.Entity1LogicalName,entity2: body && body.Entity2LogicalName,+ ...intersectOf(body),};}return {@@ -163,7 +191,7 @@ async function readExact(client, schemaName) {const kind = castKind(base.body);if (!kind) return { found: null, status: base.status, error: 'relationship type was not in the base read' };const select = kind === 'ManyToMany'- ? 'SchemaName,Entity1LogicalName,Entity2LogicalName'+ ? MANY_TO_MANY_SELECT: 'SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute';const castName = kind === 'ManyToMany' ? 'ManyToManyRelationshipMetadata' : 'OneToManyRelationshipMetadata';const cast = await get(client, `${key}/Microsoft.Dynamics.CRM.${castName}?$select=${select}`);@@ -230,12 +258,17 @@ function pickProjectionRow(rows, schemaName) {function projectionHolder(row, probedEntity) {const probed = lc(probedEntity);if (!row) return null;- // A name-only test double has no type. Inventing OneToMany ends from the probed entity made- // that row a false conflict. The vendored projection always sets type; without it, compare by name.+ // A row with no type (a test double that lists names) says nothing of its ends. Inventing OneToMany+ // ends from the probed entity made that row a false conflict, so only its name is kept — which+ // compareRelationship reads as unproven, neither the declared relationship nor another's. The+ // vendored projection always sets type.if (row.type !== 'OneToMany' && row.type !== 'ManyToOne' && row.type !== 'ManyToMany') {return { schemaName: row.schemaName };}if (row.type === 'ManyToMany') {+ // The projection lists an N:N as { schemaName, type: 'ManyToMany', relatedEntity: <the other table>, relatedAttribute: '' }: nothing of its+ // intersect table or of the column each table has in it. So its holder states neither, and compareRelationship reads it as unproven: the+ // projection can say an N:N of this name exists, never that it is the declared one.return { schemaName: row.schemaName, type: 'ManyToMany', entity1: probed, entity2: row.relatedEntity };}if (row.type === 'ManyToOne') {@@ -261,38 +294,92 @@ function kindOf(r) {return '';}-function pairOf(a, b) {- if (!a || !b) return null;- return [lc(a), lc(b)].sort();+// Two pairs of table names are the same pair whichever order they are written in.+function sameTables(a, b) {+ const x = [...a].sort();+ const y = [...b].sort();+ return x[0] === y[0] && x[1] === y[1];}-function sameRelationship(declared, holder) {- if (!declared || !holder || typeof declared !== 'object' || typeof holder !== 'object') return false;- const dName = lc(declared.schemaName || declared.effectiveName);- const hName = lc(holder.schemaName || holder.SchemaName);- if (dName && hName && dName !== hName) return false;- const dKind = kindOf(declared);- const hKind = kindOf(holder);- if (dKind && hKind && dKind !== hKind) return false;- if (dKind === 'nn' || hKind === 'nn') {- const declaredPair = pairOf(declared.entity1, declared.entity2);- const holderPair = pairOf(- holder.entity1 || holder.Entity1LogicalName || holder.entity1LogicalName,- holder.entity2 || holder.Entity2LogicalName || holder.entity2LogicalName,- );- if (declaredPair && holderPair) return declaredPair[0] === holderPair[0] && declaredPair[1] === holderPair[1];- return !holderPair;+// Is this holder — what the environment says a schema name belongs to — the relationship the spec declares?+//+// { state: 'same', missing: [] } every part of its identity is stated, and equals the declaration+// { state: 'different', missing: [] } a part it states contradicts the declaration, whatever else it states or leaves out+// { state: 'incomplete', missing: [parts] } nothing it states contradicts, but it does not state every part+//+// The identity of a relationship is its schema name, its type and its two tables, and for a 1:N the lookup column, for an N:N the intersect+// table and the column each table has in it. The holder has to STATE all of them: a part that is absent from a successful answer (a+// collection row without its ReferencingAttribute, a typed read that answers 200 with `{}`, the empty string the vendored SDK's+// projection writes for a value it lacked) is a part nobody checked.+// Reading "absent" as "nothing contradicts" certified a relationship on its name alone — the build skipped the create of a+// relationship it could not identify, and verify passed it — and the name is the one thing a different relationship can share: a 1:N+// and an N:N between the same two tables derive the same one, and two lookups of a self-reference differ only in the column.+// So an incomplete holder is UNPROVEN: neither reused nor refused as another's, but looked at again, and reported as it is.+//+// The declaration is compared on the parts it states (the build's and verify's declared relationships always state all of them, except+// the intersect table of an N:N, which a spec may leave to the platform — see below).+function compareRelationship(declared, holder) {+ const d = declared && typeof declared === 'object' ? declared : {};+ const h = holder && typeof holder === 'object' ? holder : {};+ const missing = [];+ let differs = false;+ const part = (label, stated, declaredValue) => {+ if (!stated) missing.push(label);+ else if (declaredValue && stated !== declaredValue) differs = true;+ };+ part('schema name', lc(h.schemaName || h.SchemaName), lc(d.schemaName || d.effectiveName));+ const dKind = kindOf(d);+ const hKind = kindOf(h);+ if (dKind && hKind && dKind !== hKind) differs = true;+ if (!hKind) missing.push('relationship type');+ if ((dKind || hKind) === 'nn') {+ const e1 = h.entity1 || h.Entity1LogicalName || h.entity1LogicalName;+ const e2 = h.entity2 || h.Entity2LogicalName || h.entity2LogicalName;+ if (!e1) missing.push('first table');+ if (!e2) missing.push('second table');+ const declaredTables = [lc(d.entity1), lc(d.entity2)].filter(Boolean);+ const holderTables = [lc(e1), lc(e2)].filter(Boolean);+ if (declaredTables.length === 2 && holderTables.length === 2) {+ // The pair is unordered, and a self-referencing N:N names the same table twice.+ if (!sameTables(declaredTables, holderTables)) differs = true;+ } else if (declaredTables.length === 2) {+ // The holder names one table or none: what it names must still be one of the declared two.+ if (holderTables.some((table) => !declaredTables.includes(table))) differs = true;+ } else if (holderTables.length === 2) {+ // The declaration names fewer than two tables: each it names must be one of the holder's.+ if (declaredTables.some((table) => !holderTables.includes(table))) differs = true;+ }+ // The table that holds the links is part of what an N:N is, and the answer has to state it (and the column each table has in it) like the+ // tables. It is compared only with what the spec states: `intersectEntityName` is optional — the reference calls an unnamed one "auto-named",+ // a download never writes it, and a relationship adopted from the environment (`existing: true`) has the intersect table its maker chose — so a+ // spec that names none is held to none, and a spec that names one is held to it (without regard to case, as every name compared here). The two+ // columns are the key each table has in the intersect table: the spec cannot say them and the platform derives them, so they are required,+ // not compared.+ part('intersect table', lc(h.intersectEntityName || h.IntersectEntityName), lc(d.intersectEntityName));+ part('first intersect column', lc(h.entity1IntersectAttribute || h.Entity1IntersectAttribute), '');+ part('second intersect column', lc(h.entity2IntersectAttribute || h.Entity2IntersectAttribute), '');+ } else {+ part('referenced table', lc(h.referencedEntity || h.ReferencedEntity || h.referenced), lc(d.referenced));+ part('referencing table', lc(h.referencingEntity || h.ReferencingEntity || h.referencing), lc(d.referencing));+ part('lookup column', lc(h.referencingAttribute || h.ReferencingAttribute), lc(d.lookup && d.lookup.schemaName));}- const ref = lc(declared.referenced);- const ring = lc(declared.referencing);- const lookup = lc(declared.lookup && declared.lookup.schemaName);- const hRef = lc(holder.referencedEntity || holder.ReferencedEntity || holder.referenced);- const hRing = lc(holder.referencingEntity || holder.ReferencingEntity || holder.referencing);- const hLookup = lc(holder.referencingAttribute || holder.ReferencingAttribute);- if (hRef && ref && hRef !== ref) return false;- if (hRing && ring && hRing !== ring) return false;- if (hLookup && lookup && hLookup !== lookup) return false;- return true;+ if (differs) return { state: 'different', missing: [] };+ return missing.length ? { state: 'incomplete', missing } : { state: 'same', missing: [] };+}++// True only when the holder is PROVEN to be the declared relationship (compareRelationship says 'same'). `false` is not "another+// relationship": it is also an answer that left out a part of its identity, so a caller that must tell those apart asks+// compareRelationship.+function sameRelationship(declared, holder) {+ return compareRelationship(declared, holder).state === 'same';+}++// What an incomplete answer left out, in the words every message about it uses:+// the environment's answer for it is incomplete (it does not state its referencing table and its lookup column)+function describeIncomplete(missing) {+ const parts = (missing || []).map((part) => `its ${part}`);+ const list = parts.length < 2 ? parts.join('') : `${parts.slice(0, -1).join(', ')} and ${parts[parts.length - 1]}`;+ return `the environment's answer for it is incomplete (it does not state ${list})`;}function describeRelationship(r) {@@ -300,7 +387,10 @@ function describeRelationship(r) {if (kindOf(r) === 'nn') {const a = r.entity1 || r.Entity1LogicalName || r.entity1LogicalName;const b = r.entity2 || r.Entity2LogicalName || r.entity2LogicalName;- return `N:N ${lc(a)} <-> ${lc(b)}`;+ // The intersect table when there is one to name — the declaration's when the spec names it, the holder's when its answer stated it — so a+ // refusal that is only about the intersect table does not read as two identical relationships.+ const intersect = lc(r.intersectEntityName || r.IntersectEntityName);+ return intersect ? `N:N ${lc(a)} <-> ${lc(b)} (intersect ${intersect})` : `N:N ${lc(a)} <-> ${lc(b)}`;}const referenced = r.referenced || r.referencedEntity || r.ReferencedEntity;const referencing = r.referencing || r.referencingEntity || r.ReferencingEntity;@@ -309,12 +399,26 @@ function describeRelationship(r) {return lookup ? `1:N ${ends} (lookup ${lc(lookup)})` : `1:N ${ends}`;}+// What to tell the maker when the name is held by an N:N that is the declared one in every part but the intersect table the spec names. Reusing it is+// one edit away — name its intersect table, or name none — and so is making another (an explicit schema name), which is why the generic "give it an+// explicit schemaName" is not enough here. '' for any other difference: another table or another type cannot be reused by changing the intersect table.+function intersectRemedy(declared, holder) {+ const d = declared && typeof declared === 'object' ? declared : {};+ if (!lc(d.intersectEntityName)) return '';+ if (compareRelationship(Object.assign({}, d, { intersectEntityName: undefined }), holder).state !== 'same') return '';+ const held = lc(holder.intersectEntityName || holder.IntersectEntityName);+ return `Set "intersectEntityName" to '${held}' (or leave it out) to reuse that relationship, or give the declared one an explicit "schemaName" to create another.`;+}+module.exports = {readRelationshipsOf,findRelationshipHolder,readExact,pickProjectionRow,projectionHolder,+ compareRelationship,sameRelationship,describeRelationship,+ describeIncomplete,+ intersectRemedy,};diff --git a/plugins/model-apps/scripts/lib/safe-fs.js b/plugins/model-apps/scripts/lib/safe-fs.jsindex 13eec7ffa..152450cfa 100644--- a/plugins/model-apps/scripts/lib/safe-fs.js+++ b/plugins/model-apps/scripts/lib/safe-fs.js@@ -26,6 +26,9 @@const fs = require('node:fs');const path = require('node:path');const crypto = require('node:crypto');+// Everything this module writes has the access tokens the process obtained taken out first: it is the one writer of the build's journal and status file, of what a download writes, of a page's file and its deployed copy+// (tests/output-token-writers.test.js lists every other write in the plugin and why none of them can carry a token). Text only: bytes a caller gives are written as they are.+const { redactOutput } = require('./output-redaction.js');const UNSAFE = 'UNSAFE_OUTPUT';@@ -231,6 +234,7 @@ function assertPlainFileTarget(filePath, opts) {function writeFileSafe(filePath, data, opts) {if (typeof filePath !== 'string' || !filePath.trim()) unsafe('refusing to write: no path was given', 'uninspectable');+ data = redactOutput(data);const fsImpl = (opts && opts.fs) || fs;const resolved = path.resolve(filePath);const realDir = assertSafeOutputDir(path.dirname(resolved), { fs: fsImpl });@@ -440,6 +444,7 @@ function removeTreeWithRetry(dir, opts) {function appendFileSafe(filePath, data, opts) {if (typeof filePath !== 'string' || !filePath.trim()) unsafe('refusing to append: no path was given', 'uninspectable');+ data = redactOutput(data);const fsImpl = (opts && opts.fs) || fs;const resolved = path.resolve(filePath);const realDir = assertSafeOutputDir(path.dirname(resolved), { fs: fsImpl });diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex da07d8009..16f02022f 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -26,7 +26,7 @@ const { unreadableAnswer } = require('./collection-answers.js');// normalizePageSource: read the page source from the discriminated `source` field (v2) or the// legacy top-level `codeFile` (pre-migration). PHASES: canonical ordered phase list — imported// here so the engine and the stage layer can never drift.-const { describeRelationship, readExact, sameRelationship, findRelationshipHolder } = require('./relationship-metadata.js');+const { describeRelationship, describeIncomplete, readExact, compareRelationship, findRelationshipHolder } = require('./relationship-metadata.js');const {sampleRecordsFor,resolveSampleRecords,@@ -141,7 +141,7 @@ const { appWriteTables, appPushTables, preAppTables, publishTablesXml, readSavedconst { hasUnsyncedEdits } = require('./unsynced-edits.js');const { createSolutionMembership, ensureSolutionComponent } = require('./solution-membership.js');const { navigationEntryKind, navigationVerdict } = require('./app-navigation.js');-const { isAppTextMap, appTextKind, localizedAppText, describeHeldAppText } = require('./app-header-text.js');+const { isAppTextMap, appTextKind, localizedAppText } = require('./app-header-text.js');// The build's retry policy (retry-policy.js): every halt below is raised with what a run again may do — RETRY.NEVER, or a policy decided from the failure it wraps — and every failure the engine// 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.@@ -296,11 +296,21 @@ function dashboardTileOpts(spec, tile, result) {// Map a resolved dashboard tile (dashboardTileOpts output) to a canonical DashboardComponent for// addElement('dashboard', id, '/components', …). The adapter mints the cell/control ids and lays the-// grid out from `position`; the caller supplies the classId (chart/list share the grid control id —-// ChartGridMode disambiguates), the `<parameters>` map, and the placement. Tiles stack vertically-// (one per row in the first section). Param keys match the Dataverse control XML; note that a chart+// tiles out in the first section: a grid two columns wide, filled in tile order from left to right,+// where a tile too wide for what is left of a row starts the next one and a `colspan` wider than the+// grid is narrowed to it (measured on the bundled SDK; `dashboard-roundtrip.test.js` pins it). The+// caller supplies the classId (chart/list share the grid control id — ChartGridMode disambiguates),+// the `<parameters>` map, and the size. Param keys match the Dataverse control XML; note that a chart// tile keys its visualization as `VisualizationId`, NOT `ChartId` — see the comment on that line,// and `lcid-real-bundle.test.js`, which pushes this exact payload through the real bundle.+//+// A tile's height is its rowspan, in rows of the dashboard grid, and the app draws a one-row tile as+// its title bar alone: no chart, no list. The platform's own dashboards give chart and list tiles 9 to+// 24 rows, most often 12, so a tile the spec does not size gets that common height. The default used+// to be 1, which rendered every tile of a generated dashboard as a bare title bar. The width stays 1+// column, so two unsized tiles share a row. An authored `rowspan` or `colspan` wins, a `rowspan` of 1+// included. Only a dashboard the build CREATES gets this: an existing one is reused as it is.+const DEFAULT_TILE_ROWSPAN = 12;function dashboardComponent(t, index) {const parameters = {};if (t.type === 'chart') {@@ -325,7 +335,7 @@ function dashboardComponent(t, index) {return {type: t.type, name: t.name || '', classId: TILE_CLASS_ID[t.type] || TILE_CLASS_ID.webresource,position: { tabIndex: 0, columnIndex: 0, sectionIndex: 0, rowIndex: index, cellIndex: 0 },- colspan: t.colspan || 1, rowspan: t.rowspan || 1, parameters,+ colspan: t.colspan || 1, rowspan: t.rowspan || DEFAULT_TILE_ROWSPAN, parameters,};}@@ -564,7 +574,9 @@ function planFor(spec, opts) {// (keyWaitsForNameLength, which depends on what the key's label is sent as and not on the language the build writes in, so the plan and the// apply cannot disagree about it). The plan lists it// where a table the build creates has it; a table that already exists is not written to, and- // its keys are made with the table — the same steps, in another place, so the count holds.+ // its keys are made with the table — the same steps, in another place, so the count holds. The same goes for a key labelled in several+ // languages that the environment made the name column too long to fit beside (keyMustWaitForShorterNameColumn, lib/entity-provision.js):+ // only the environment can say, so the plan lists such a key with its table, and the apply makes it after the length step.for (const e of spec.entities) {for (const k of e.alternateKeys || []) {if (keyWaitsForNameLength(e, k)) items.push({ phase: 'data-model', label: `alt key ${e.schemaName}.${k.schemaName}` });@@ -1340,11 +1352,11 @@ async function applyAppAiDescription(provision, spec, appId) {// the text each edit REPLACED — `{ description: 'Tickets' }`, `{}` when nothing was edited — which is what a refused push puts back// (pushAppHeader), and which says whether the artifact now needs a push.//-// The SDK's header push writes `name` AND `description` — and the routing description, when the artifact says something new about it —-// in ONE PATCH, conditioned on the row's own token, whenever the artifact holds any of them differently from the row (and no PATCH when-// all three are equal). Whichever of them an edit changed, the others ride along as the artifact holds them: it writes the copy, not the-// edit (pinned against the real bundle in app-header-text-real-bundle.test.js). So these edits ride the push the app already gets (the-// sitemap rewrite): never a second push from the same fetch, which would race the first on its If-Match.+// The SDK's header push writes only the texts that CHANGED: in ONE PATCH, conditioned on the row's own token, the artifact's `name`, `description` and routing+// description that differ from the header it has just read (no PATCH when none does), and it neither compares nor writes a text REMOVED from the copy+// (cds-maker-sdk 9a0c9f03; pinned against the real bundle in app-header-text-real-bundle.test.js). It used to write the whole copy, the texts an edit had not+// changed included. So these edits ride the push the app already gets (the sitemap rewrite): never a second push from the same fetch, which would race the+// first on its If-Match.//// * Only a non-blank string is written, and only when it differs from the FETCHED artifact (the draft layer the push compares the// header against). The two guards a view's and a chart's description already have: a spec that leaves the text out — or carries@@ -1355,35 +1367,31 @@ async function applyAppAiDescription(provision, spec, appId) {// app, which the app step creates, rather than renaming this one.// * A fetched app always carries both keys (the adapter reads `description` as '' when the row has none), so updateElement has a// path to write — unlike the routing description, which is added when the row has none.-// * The header is written only while BOTH texts are PLAIN TEXT. Both columns are localizable, and whether a plain write of the-// base-language text keeps a translation beside it has not been measured against an environment; the adapter hands back one-// string, so a translation held beside it is invisible here. What this can see is a value that is not a string at all — a text per-// language, as an LCID map, a list, a number — and that is never sent: not as it is (these are String columns, and a map-shaped-// PATCH of one is no write the platform defines), and not replaced by a scalar. It is not enough to leave that one field alone:-// the push would still send it, as the sibling of an edit of the other text or of the routing description. So while either text-// is not plain NO header edit is made at all — the other text's, and the routing description's (applyAppHeader) — and each edit the-// spec asked for is reported as not applied, with the reason. A localized value the spec's text already equals (the-// unchanged-name, changed-description case) needs no edit of its own and no word.-// * THAT WHOLE-HEADER HOLD IS THE CHOSEN POLICY, not a stopgap — and the SDK is the reason. It has no partial header write: its PATCH is-// built from the whole workspace copy, `{ name, description[, aiappdescription] }` (pinned in app-header-text-real-bundle.test.js, which fails-// if a re-vendored bundle makes it partial), and the row token it is conditioned on is private to it. So the one plain field that changed-// cannot be sent alone. A PATCH of the plugin's own would need a row token read afresh, which is a blind overwrite of whatever changed since-// the fetch. Taking the text that is not plain off the copy, for the SDK to leave out of its request, would lean on an SDK internal (the-// serializer dropping `undefined`) whose failure mode — a re-vendor that writes `name: ''` — blanks an app's name. Neither is done: a plain-// edit beside a text that is not plain is a warning and a navigation-only push. Writing only the changed field would need an SDK operation-// (a partial header write), which is a follow-up; the hold could then be narrowed to the one field.-// * The hold is on the workspace COPY, and the SDK decides for itself whether the header is written: when its own comparison read of the-// header cannot be made it writes the copy's header as it is, so "no header edit" is not "no header PATCH". The client every SDK is made-// with refuses that write (lib/app-header-text.js, APP_HEADER_NOT_PLAIN_TEXT, wired in lib/maker-sdk.js): a text that is not plain never-// reaches the wire, whatever the copy holds, and the push fails before its navigation is written (pushAppHeader).+// * A TEXT THAT IS NOT PLAIN is never edited and never sent, and holds nothing else back. Both columns are localizable, and whether a plain write of the+// base-language text keeps a translation beside it has not been measured against an environment; the adapter hands back one string, so a translation+// held beside it is invisible here. What this can see is a value that is not a string at all — a text per language, as an LCID map, a list, a number — and+// that is never sent: not as it is (these are String columns, and a map-shaped PATCH of one is no write the platform defines), and not replaced by a+// scalar. Its OWN edit is held back and reported as not applied, with the reason (a warning, never a halt); a localized value the spec's text already+// equals (the unchanged-name, changed-description case) needs no edit and no word. The other text, and the routing description (applyAppHeader), are+// applied as usual and written alone: that is what the SDK's partial write is for. (While the SDK wrote the whole copy, one text that was not plain held+// the whole header back, and this said so.)+// * It is kept off the wire by being kept off the COPY. The SDK decides for itself whether the header is written: when its own comparison read of the+// header cannot be made (503, 403, a thrown error, an empty 200) it writes EVERY text the copy holds. So the texts the copy holds that are not plain+// (`held`, answered by applyAppHeader) are taken off it with `removeElement('app', id, '/name')` right before the push (pushAppHeader), and the SDK+// then neither compares nor writes them — now its documented contract, where it was once an internal (the serializer dropping `undefined`) whose failure,+// a re-vendor that writes `name: ''`, would blank an app's name; the bundle's behaviour is pinned, and so is that nothing else of the copy changes. Not+// here, and not earlier: a copy holding an edit that no push follows is refused by the next run (refuseUnpushedAppCopy), and the routing description+// of a page-backed app is pushed only when it changed.+// * The client every SDK is made with still refuses a write of a text that is not plain (lib/app-header-text.js, APP_HEADER_NOT_PLAIN_TEXT, wired in+// lib/maker-sdk.js), whatever the copy holds: the last line of defence for a push of a copy the build did not clean (the page backend's, say).// name holds at most 100 characters and description 2,000 (validateDescription).// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmoduleasync function applyAppHeaderText(provision, spec, appId, warn) {return (await editAppHeaderText(provision, spec, appId, warn)).replaced;}-// applyAppHeaderText's work, which also answers `held` — the header's texts that are not plain, `[{ key, have }]` — for applyAppHeader to-// hold the routing description back by.+// applyAppHeaderText's work, which also answers `held` — the header's texts that are not plain, `[{ key, have }]` — for applyAppHeader to hand on to the push,+// which takes them off the copy (see applyAppHeaderText).async function editAppHeaderText(provision, spec, appId, warn) {const app = (spec && spec.app) || {};const current = (await provision.getArtifact('app', appId)) || {};@@ -1394,7 +1402,7 @@ async function editAppHeaderText(provision, spec, appId, warn) {for (const key of ['name', 'description']) {const want = app[key];if (typeof want !== 'string' || !want.trim() || have[key] === want) continue;- const kept = whyAppTextIsKept(key, have[key], want, held);+ const kept = whyAppTextIsKept(key, have[key], want);if (kept !== undefined) {if (kept && typeof warn === 'function') warn(`app "${app.name}": its ${key} was not applied: ${kept}`);continue;@@ -1405,19 +1413,14 @@ async function editAppHeaderText(provision, spec, appId, warn) {return { replaced, held };}-// How a header text that is not plain reads in a warning (isAppTextMap, localizedAppText, appTextKind, describeHeldAppText) is lib/app-header-text.js's:+// How a header text that is not plain reads in a warning (isAppTextMap, localizedAppText, appTextKind) is lib/app-header-text.js's:// the client refuses a write of such a text in the same words.// Why an app's name or description (`have`, as fetched) is NOT written over with the spec's text (`want`) — or `undefined` when it is-// plain text and nothing else holds it back. `''` means the spec asks for nothing the header does not already say, so there is nothing to-// report. `held` is what editAppHeaderText found not to be plain text: a plain text is held back too while another text of the header is,-// because the SDK's one request writes both.-function whyAppTextIsKept(key, have, want, held) {- if (typeof have === 'string') {- return held.length- ? `${describeHeldAppText(held)}, and the app's name and description are written in one request, so changing its ${key} would send the ${held[0].key} too — a rebuild never sends a text that is not plain. Change it in Power Apps.`- : undefined;- }+// plain text, which nothing else holds back: not the other text of the header, plain or not. `''` means the spec asks for nothing the+// header does not already say, so there is nothing to report.+function whyAppTextIsKept(key, have, want) {+ if (typeof have === 'string') return undefined;if (isAppTextMap(have)) {if (Object.values(have).includes(want)) return '';return `it is ${localizedAppText(have)}, and a rebuild does not replace a localized text — it cannot tell which language the spec's text is for, nor that the other translations would be kept. Change it in Power Apps.`;@@ -1430,26 +1433,14 @@ function whyAppTextIsKept(key, have, want, held) {// already wrote the spec's (appDef), the compare would be a read the build never made for a new app. Answers// changed whether the artifact now holds any header change, and so needs a push;// routing whether one of them is the routing description — an explicit request that a never-published app's refusal must HALT on;-// replaced the text the name / description edits replaced (applyAppHeaderText), for pushAppHeader to put back.-// While a text of the header is not plain, no edit is made at all — the routing description's included: it is written by the same request-// as the two texts, so it would send the one that is not plain (see applyAppHeaderText). That is a warning, not a halt: the navigation is-// the app step's own work and goes on, and a text left for a maker costs the build nothing it could have kept.+// replaced the text the name / description edits replaced (applyAppHeaderText), for pushAppHeader to put back;+// held the texts of the copy that are not plain, `[{ key, have }]`, which pushAppHeader takes off the copy before it pushes it.+// A text that is not plain holds back its own edit only, with a warning, never a halt: the other text and the routing description are applied as usual+// (see applyAppHeaderText), and the navigation is the app step's own work and goes on.async function applyAppHeader(provision, spec, appId, { text = true, warn } = {}) {const { replaced, held } = text ? await editAppHeaderText(provision, spec, appId, warn) : { replaced: {}, held: [] };- const routing = held.length ? await holdBackAppRouting(provision, spec, appId, held, warn) : await applyAppAiDescription(provision, spec, appId);- return { changed: routing || Object.keys(replaced).length > 0, routing, replaced };-}--// The routing description is never edited while the header holds a text that is not plain. Says so when the spec asks for one the fetched-// copy does not have; answers false, as applyAppAiDescription does for "nothing to push".-async function holdBackAppRouting(provision, spec, appId, held, warn) {- const want = spec.app && spec.app.aiDescription;- if (typeof want !== 'string' || !want.trim() || typeof warn !== 'function') return false;- const current = (await provision.getArtifact('app', appId)) || {};- if (current.aiDescription !== want) {- warn(`app "${spec.app.name}": its routing description (app.aiDescription) was not applied: ${describeHeldAppText(held)}, and the app's name, description and routing description are written in one request, so changing it would send ${held.length === 1 ? `the ${held[0].key}` : 'both'} too — a rebuild never sends a text that is not plain. Change it in Power Apps.`);- }- return false;+ const routing = await applyAppAiDescription(provision, spec, appId);+ return { changed: routing || Object.keys(replaced).length > 0, routing, replaced, held };}// An app's tile icon is written when the app is created and a rebuild cannot replace it: the appmodule's `webresourceid` is effectively@@ -1534,19 +1525,25 @@ async function haltOnUnpublishedAppHeader(provision, appId, pushed, name) {// with the header already put back (halted on, never looped on). A header that cannot be put back halts too: pushing a copy that// still holds the edit would be refused again.//-// ANOTHER refusal comes from the HTTP client, not from the SDK, and it is not recovered from either: the SDK writes the copy's header whenever its own-// comparison read of the header cannot be made, and a name or description that is not plain text never leaves the process (APP_HEADER_NOT_PLAIN_TEXT,-// lib/app-header-text.js) — whether or not this run edited the header at all. It is thrown before the header or the navigation is written, so the generic-// path below is the right one: the copy, which this push never recorded, is reset to the server's, and the typed error is thrown as it is. Its message says a-// re-run normally succeeds, and `transient: false` keeps the build from running the phase again on its own: whether the read answers next time is for that-// re-run to find out, and a retry of the same push here would hide the one thing the message tells.+// A text of the copy that is not plain (`header.held`) is taken off it first (takeNonPlainTextOffCopy): the SDK writes every text the copy holds when its own comparison read of+// the header cannot be made, and it neither compares nor writes a text that is not on the copy, so it has no text that is not plain to write. That is done here and not when the+// header is edited because this is the one place the build pushes a copy: a copy that is taken from and then not pushed would be left holding an edit (refuseUnpushedAppCopy).+//+// The HTTP client still refuses a write of a text that is not plain, whatever pushes it, and that refusal is not recovered from: a name or description that is not plain text never+// leaves the process (APP_HEADER_NOT_PLAIN_TEXT, lib/app-header-text.js). This push does not meet it — the text is off the copy — but a push the build does not make through here can: the page+// backend's push of the app, say. It is thrown before the header or the navigation is written, so the generic path below is the right one: the copy, which that push never recorded, is+// reset to the server's, and the typed error is thrown as it is. Its message says a re-run normally succeeds, and `transient: false` keeps the build from running the phase again on its own:+// whether the read answers next time is for that re-run to find out, and a retry of the same push here would hide the one thing the message tells.async function pushAppHeader(provision, appId, name, header, mainFormsByTable, warn) {- const { routing, replaced } = header !== null && typeof header === 'object' ? header : { routing: header === true, replaced: {} };+ const { routing, replaced, held } = header !== null && typeof header === 'object' ? header : { routing: header === true, replaced: {}, held: [] };const textKeys = Object.keys(replaced || {});const carriesHeader = routing || textKeys.length > 0;const attempt = async (first) => {try {- if (first) await applyAppMainForms(provision, appId, mainFormsByTable);+ if (first) {+ await applyAppMainForms(provision, appId, mainFormsByTable);+ await takeNonPlainTextOffCopy(provision, appId, held);+ }return { pushed: await explainAppPushWarnings(provision.dataverse, await provision.pushArtifact('app', appId), name) };} catch (thrown) {return { thrown };@@ -1571,6 +1568,20 @@ async function pushAppHeader(provision, appId, name, header, mainFormsByTable, wreturn pushed;}+// Take the texts of the copy that are not plain (applyAppHeader's `held`) off it, right before the push that would offer them to the SDK. The SDK neither compares nor writes a text that is+// not on the copy — even when its own comparison read of the header fails, which makes it write every text the copy holds — so none of them can be in its request. A text with no value is not on+// the copy: there is nothing to take off. A path the copy no longer has is as gone as it needs to be.+async function takeNonPlainTextOffCopy(provision, appId, held) {+ for (const { key, have } of held || []) {+ if (have === undefined) continue;+ try {+ await provision.removeElement('app', appId, `/${key}`);+ } catch (err) {+ if (!err || err.code !== 'PATH_NOT_FOUND') throw err;+ }+ }+}+// Put the text a refused push's edits replaced (applyAppHeaderText's answer) back on the workspace copy, so the next push carries no// header write. True when every one is back; false when a write failed, which leaves the copy holding an edit the caller must not push.async function putBackAppText(provision, appId, replaced) {@@ -2260,11 +2271,18 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {// held by a 1:N). One exact-name read, no collection scan — the plan stays cheap.const exact = await readExact(provision && provision.dataverse, k.name);const declared = Object.assign({}, k.declared, { schemaName: (k.declared && k.declared.schemaName) || k.name });- if (exact.found === true && sameRelationship(declared, exact.holder)) item.state = 'reuse';- else if (exact.found === true) {+ // A holder that exists is reused only when it states its whole identity. Otherwise the item is unknown, and the reason says+ // whether the name belongs to another relationship or the environment's answer left a part out (compareRelationship).+ const judgeHolder = (heldBy) => {+ const verdict = compareRelationship(declared, heldBy);+ if (verdict.state === 'same') { item.state = 'reuse'; return; }item.state = 'unknown';- item.stateWhy = `schema name '${k.name}' is already used by ${describeRelationship(exact.holder)}, not the declared relationship`;- } else if (exact.found === false) {+ item.stateWhy = verdict.state === 'incomplete'+ ? `schema name '${k.name}' exists, but ${describeIncomplete(verdict.missing)}, so it cannot be told from the declared relationship`+ : `schema name '${k.name}' is already used by ${describeRelationship(heldBy)}, not the declared relationship`;+ };+ if (exact.found === true) judgeHolder(exact.holder);+ else if (exact.found === false) {// The SchemaName key is case-sensitive. A differently-cased holder 404s here and would// otherwise be planned as create. The collection scan is case-insensitive; skipExact// because this read already 404'd that spelling.@@ -2272,11 +2290,8 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {? (k.relType === 'ManyToMany' ? [k.declared.entity1, k.declared.entity2] : [k.declared.referenced, k.declared.referencing]): [k.entity];const holder = await findRelationshipHolder(provision && provision.dataverse, k.name, { candidates: ends, cache: relationshipReads, skipExact: true });- if (holder.found === true && sameRelationship(declared, holder.holder)) item.state = 'reuse';- else if (holder.found === true) {- item.state = 'unknown';- item.stateWhy = `schema name '${k.name}' is already used by ${describeRelationship(holder.holder)}, not the declared relationship`;- } else if (holder.found === false) item.state = 'create';+ if (holder.found === true) judgeHolder(holder.holder);+ else if (holder.found === false) item.state = 'create';else {item.state = 'unknown';item.stateWhy = 'the relationship metadata read was inconclusive';@@ -2660,7 +2675,8 @@ async function runSdkBuildPhases(spec, opts, owed) {// The full-build path never sets opts.changedOnly, so result.created.app stays null and app-shell// creates/updates it exactly as before — this branch is a no-op (byte-identical) on the normal path.if (opts.changedOnly && opts.changedOnly.resolvedAppId) result.created.app = opts.changedOnly.resolvedAppId;- const runner = makeRunner({ emit, total: plan.length });+ // The runner stops the run at the next step once the budget has refused a wait (entity-provision.js, makeRunner): the build's retry loop does not run the phases again to meet the same answer.+ const runner = makeRunner({ emit, total: plan.length, throttle: opts.throttle });const sol = spec.solution;// ADO 6691114: a view-filter label the environment already shows to be wrong stops the build here, before it@@ -6130,9 +6146,10 @@ async function runSdkBuildPhases(spec, opts, owed) {// also avoids spinning up genpage enumeration for every page-less app build).if (has('pages') && ((spec.pages || []).length || appWasExisting)) {// The page backend: the SDK on a throwaway workspace of its own, removed in the finally below (never the app folder's, whose copies of a- // page would be stale the moment anyone saved it). `opts.genpage` is a seam for the tests, and is the caller's to dispose.+ // page would be stale the moment anyone saved it). `opts.genpage` is a seam for the tests, and is the caller's to dispose. The run's throttle budget+ // (`opts.throttle`) is handed to it, so the HTTP client it makes draws its waits for a throttled read or publish from the same five minutes as the page writes do.const ownGenpage = !opts.genpage;- const genpage = opts.genpage || makeGenpageSdk(opts.env);+ const genpage = opts.genpage || makeGenpageSdk(opts.env, { throttle: opts.throttle });const appUnique = appUniqueName(spec);// Recovery guard: the app id is only populated by app-shell (this run). If pages runs without it// (e.g. --from pages), there is nothing to upload against — HALT and require a FULL rerun.@@ -6234,6 +6251,12 @@ async function runSdkBuildPhases(spec, opts, owed) {try { page = await genpage.read(record.pageId); } catch (e) {// Gone since the listing: it is not there now, which settles nothing (see below), so it is resumed like any page that was not listed.if (e && e.code === 'GENPAGE_NOT_FOUND') { resume(); continue; }+ // A read the service throttled and the run's budget had no room to wait for says nothing of the page (genpage-sdk.js reports it as the throttle's own error, which is not marked final): it is not a conflict that the maker has to settle by+ // deleting a record, but a stop for a later run. The record stays, so the run that can read the page proves it and adopts it. A read that failed any other way is final (`transient: false`) and is the conflict it always was.+ const judged = judgeFailure(e);+ if (!judged.never && judged.transientStatus) {+ throw new BuildHalt(`could not read page ${record.pageId}, which an earlier build started creating for "${key}", because the service throttled the read (${(e && e.message) || e}) — nothing was changed; the record of that create is kept, so a later run reads the page and settles it`, { phase: 'pages', code: 'pages-read-throttled', recoverable: true, ...retryFrom(e) });+ }pendingConflicts.push({ key, reason: 'pending-create-unreadable', pageId: record.pageId, error: String((e && e.message) || e) });continue;}@@ -7143,35 +7166,14 @@ async function runSdkBuildPhases(spec, opts, owed) {// An org without the AI template a row summary is built from. The SDK reads the template before its first write and refuses with its own// code (`configureRowSummary`: ROW_SUMMARY_TEMPLATE_NOT_FOUND, "Nothing was written"), where it used to publish a model that named no template and let the// platform answer. It is the same kind of environment gate as the licence refusal below — nothing in the spec can fix it — so it skips the same way.+ // The code is the SDK's word for an EMPTY template list and for nothing else (cds-maker-sdk 9a0c9f03):+ // GET /msdyn_aitemplates?$select=msdyn_aitemplateid&$filter=msdyn_uniquename eq 'GptPowerPrompt'&$top=1 -> { "value": [] } the org has no template: this code+ // Every other answer it cannot read as a template — no `value` list, a first row that is no row (`[ null ]`), a row without a GUID `msdyn_aitemplateid` (`[ {} ]`) — is a+ // ConnectionError, which stops the build like any read that failed (and is run again when it was the service that failed it, lib/retry-policy.js). So the code needs no+ // confirming read of the build's own: before that SDK it was raised for `[ {} ]` and `[ null ]` as well, and 2.16.0 read the list a second time to tell them apart.const NO_TEMPLATE_REASON = 'no row-summary AI template in this environment';- // The code alone does not prove that the org has no template, though. The SDK's lookup is- // GET /msdyn_aitemplates?$select=msdyn_aitemplateid&$filter=msdyn_uniquename eq 'GptPowerPrompt'&$top=1 -> { "value": [ { "msdyn_aitemplateid": "<guid>" } ] }- // and it raises the code whenever the FIRST row has no `msdyn_aitemplateid`, without checking that there is a row: `{ "value": [] }`, `{ "value": [ {} ] }` and- // `{ "value": [ null ] }` all raise it. Only the empty list says the org has no template; the other two are answers that cannot be read, and an answer that cannot be- // read stops the build (as it did before the skip) instead of passing for an environment gate. So the first time the code is seen, the build asks the same question- // through `queryRecords` — which refuses an answer without its `value` array — and skips only on an empty list. Rows, a row that is no row and a read that fails leave- // the SDK's own error to stop the build. The verdict is kept: every table's lookup is the same question, so one read settles the whole build.- // This mirrors the SDK's lookup (its template name, its select) and can go once the SDK raises the code for an empty list only and answers a malformed first row with a- // ConnectionError. If the SDK ever looks for another template, this read can only fail to confirm, which stops the build: the safe side.- // `msdyn_aitemplate` is the table behind the SDK's `/msdyn_aitemplates` set:- // https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/msdyn_aitemplate- // The verdict is `{ absent }` — true only for an empty list — and, when the read itself failed, `{ absent: false, failure }`, what it threw. The read is two requests, the first time:- // the one that names the template table's set (the SDK looks it up once and keeps it) and the one that reads the list; either can fail.- const ROW_SUMMARY_TEMPLATE_NAME = 'GptPowerPrompt';- let templateVerdict;- const confirmNoTemplate = async () => {- if (templateVerdict === undefined) {- try {- const rows = await provision.queryRecords('msdyn_aitemplate', { select: ['msdyn_aitemplateid'], filter: `msdyn_uniquename eq '${ROW_SUMMARY_TEMPLATE_NAME}'`, top: 1 });- templateVerdict = { absent: Array.isArray(rows) && rows.length === 0 };- } catch (failure) {- templateVerdict = { absent: false, failure };- }- }- return templateVerdict;- };const aiSummaryUnsupported = (err) => {- if (err && err.code === 'ROW_SUMMARY_TEMPLATE_NOT_FOUND') return templateVerdict && templateVerdict.absent ? NO_TEMPLATE_REASON : false;+ if (err && err.code === 'ROW_SUMMARY_TEMPLATE_NOT_FOUND') return NO_TEMPLATE_REASON;const detail = `${(err && err.message) || ''} ${JSON.stringify((err && err.cause) || '')}`;// Match the platform's own error CODE, not the prose: the message is localized and the status// alone (403/400) is also what a plain privilege or validation failure returns, which must@@ -7222,25 +7224,7 @@ async function runSdkBuildPhases(spec, opts, owed) {const override = summaryOverrides.get(String(logical).toLowerCase());await runner.run('ai-features', `row summary for ${logical}`, async () => {const promptSpec = buildPromptSpec(ent, { spec, override });- let res;- try {- res = await provision.configureRowSummary(promptSpec, { solutionUniqueName });- } catch (err) {- // `skipIf` is synchronous, so the read that confirms the template is absent is made here, before the error reaches it. The error is never replaced: when the- // read does not confirm it, it stops the build as it is — the SDK's own error, whole, as the halt's own cause.- if (err && err.code === 'ROW_SUMMARY_TEMPLATE_NOT_FOUND') {- const { failure } = await confirmNoTemplate();- // A read that FAILED is kept beneath the SDK's error. The runner decides from the chain of causes whether the build may run this attempt again (lib/retry-policy.js, judgeFailure): a throttle, an- // unavailable service or a reset connection that stopped the read has to be on that chain, or the halt is final whatever the read failed with — and the halt's text says that the read failed, and why- // (operatorRemedy). It is only a failure of the SERVICE that makes the halt transient: a missing template on its own, and a read that answered, however wrongly, stay final. The SDK's error has no- // cause of its own, so the one it has here is this one. `withCause` is the link a result carries for the same reason (a failure reported by value); an error that cannot take it (a frozen one)- // stops the build as it did before, final.- if (failure !== undefined) {- try { withCause(err, failure); } catch { /* nothing to carry it on */ }- }- }- throw err;- }+ const res = await provision.configureRowSummary(promptSpec, { solutionUniqueName });result.created.ai.summaries[logical] = res;return res.modelId;}, {diff --git a/plugins/model-apps/scripts/lib/sdk-http-client.js b/plugins/model-apps/scripts/lib/sdk-http-client.jsindex 9f74206ef..f7d57df3e 100644--- a/plugins/model-apps/scripts/lib/sdk-http-client.js+++ b/plugins/model-apps/scripts/lib/sdk-http-client.js@@ -14,6 +14,7 @@// token taken out of it, and so does a transport failure's text (see "The access token, taken out of what a// service says"): the SDK quotes such a body in the message a script prints. A success is returned untouched.const { dataverseOrigin, getAuthToken, makeRequest, tokenFailureMessage } = require('./dataverse-auth.js');+const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');// How Dataverse reports that SQL Server chose a request's transaction as a deadlock VICTIM and rolled// it back. Two live captures, both HTTP 500 (a process-flow delete during a teardown, and PublishXml):@@ -50,7 +51,8 @@ const DEADLOCK_RESENDS = 3;// The longest `Retry-After` honoured in full. Dataverse's service protection limits answer 429 with// `Retry-After` in seconds and ask the caller to wait that long; a request sent sooner is refused again// and spends one of the few attempts. The cap keeps a large value from stalling a build or a teardown-// for minutes per attempt.+// for minutes per attempt. A client given a run's throttle budget (`deps.throttle`) does not use it for a throttled answer: the budget+// bounds all of its waits together, and what the service asked is waited whole when it fits and not at all when it does not.// See: https://learn.microsoft.com/power-apps/developer/data-platform/api-limits#retry-operationsconst RETRY_AFTER_CAP_MS = 60000;@@ -65,8 +67,8 @@ const RAW_VALUE = /\/\$value(?:\?|$)/;* Retry-After: Wed, 30 Sep 2026 10:00:20 GMT* Node lowercases response header names; a test double may not, so the name is matched case-insensitively.* The cap is for this client's own retries, which must not stall a build for minutes per attempt. A caller that has a bound of its own on the whole of what it waits passes `Infinity` and gets the- * service's request as it is, to decide for itself whether it fits: solution-settings.js, when it sends a refused import again, inside one budget for the whole retry; and the page backend, which spends a- * run's throttle budget (lib/throttle-budget.js).+ * service's request as it is, to decide for itself whether it fits: solution-settings.js, when it sends a refused import again, inside one budget for the whole retry; the page backend, which spends a+ * run's throttle budget (lib/throttle-budget.js); and this client itself when it was given that budget, for the throttled answers it waits out (waitOutThrottle).* See: https://www.rfc-editor.org/rfc/rfc9110#field.retry-after*/function retryAfterMs(headers, now = Date.now(), cap = RETRY_AFTER_CAP_MS) {@@ -535,15 +537,12 @@ function transportError(res, message) {// never touched: its bytes are the caller's data. The same rule keeps the Power Apps client's answers clean (lib/power-apps-service-client.js takes `scrub` and `scrubAnswer` from here, which is// why they are exported: there is one scrubber).//-// Not the token alone: what an error or a gateway repeats of a bearer token is often one part of it. A token is `header.payload.signature` (three base64url parts joined by dots;-// https://www.rfc-editor.org/rfc/rfc7519#section-3), so each part long enough to be distinctive is taken out too.-const MIN_TOKEN_PART_LENGTH = 24;+// Not the token alone: what an error or a gateway repeats of a bearer token is often one part of it, so `needlesOf` (lib/output-redaction.js, the one list of what is taken out of a token: the token and each of its dot-separated+// parts that is long enough to be distinctive — https://www.rfc-editor.org/rfc/rfc7519#section-3) is what this scrubber takes out, as what the process writes is kept free of it by the same list.function scrub(text, token) {const message = String(text);if (!token) return message;- const needles = new Set([token]);- for (const part of token.split('.')) if (part.length >= MIN_TOKEN_PART_LENGTH) needles.add(part);- return [...needles].sort((a, b) => b.length - a.length).reduce((out, needle) => out.split(needle).join('<token>'), message);+ return needlesOf(token).reduce((out, needle) => out.split(needle).join(TOKEN_MARKER), message);}// The same for a whole ANSWER: every string of it is scrubbed, keys included, whatever the status: the rest of the answer is left as it is, so the status and the typed `error.code` the SDK reads survive.@@ -572,8 +571,10 @@ function scrubBearer(text, headers) {/*** Build an HttpClient bound to one Dataverse org.* @param {string} orgUrl - e.g. https://contoso.crm.dynamics.com- * @param {object} [deps] - test seam: { getToken(orgUrl)->string|null, request(opts)->Promise }, and one policy a caller may set:- * `sendOnce(method, url)` -> true for a request that must be sent exactly once, whatever answers it (see `once` in `call`).+ * @param {object} [deps] - test seam: { getToken(orgUrl)->string|null, request(opts)->Promise }, and two things a caller may set:+ * `sendOnce(method, url)` -> true for a request that must be sent exactly once, whatever answers it (see `once` in `call`); and+ * `throttle`, the budget a run allows itself for waiting out a throttled service (lib/throttle-budget.js: `fits`, `spend`, `announce`, `decline`, `note`), which every wait this client takes for a throttled answer (HTTP 429) is+ * then drawn from — see `waitOutThrottle`. A client given none waits exactly as it always did, and the pcf plugin, which has none, never passes one.* @returns {{get,post,patch,delete,put,postRaw,patchRaw}}*/function createAzHttpClient(orgUrl, deps = {}) {@@ -636,6 +637,33 @@ function createAzHttpClient(orgUrl, deps = {}) {// for longer in `Retry-After` (retryAfterMs, capped).const retryWaitMs = (res, attempt) => Math.max(backoffMs(attempt), retryAfterMs(res.headers, now()));+ // The run's budget for waiting out a throttle (lib/throttle-budget.js), when the caller gave one — and it must have everything this client calls on it, or it is no budget. This file is copied into the pcf plugin, which has no+ // budget and no such module, so the budget is something a caller hands in and never something this file loads: a client made without one waits exactly as it always did.+ const throttle = ['fits', 'spend', 'announce', 'decline', 'note'].every((name) => deps.throttle && typeof deps.throttle[name] === 'function') ? deps.throttle : null;+ // What THROTTLING is here: the service refusing a request because of its limits — HTTP 429, alone or as every operation of a `$batch`. A 5xx is not: a customization lock or a SQL deadlock victim is a 500, and a gateway's hiccup a 502, 503+ // or 504, each is re-sent on its own schedule (with the Retry-After it carries, capped at a minute), and neither is a reset connection. None of those waits is the budget's.+ //+ // The wait before a throttled request is sent again, for a client that has a budget: the schedule's wait or what the service asked in `Retry-After`, whichever is longer — and the ask WHOLE, not capped at a minute. The cap keeps a large value+ // from stalling a run for minutes on every attempt, which the budget now does for all the attempts together, and a request sent before the service is ready is refused again and spends one of its six attempts. The wait is drawn from the budget,+ // placed on the clock (`at`: the requests this client sends at once are throttled alike and wake together, and what the run waited is the time it spent waiting, not the sum of their waits), and announced when it is long.+ // Resolves true when the wait was taken. It resolves false when the wait does not fit: nothing is waited for, and the caller hands the throttled answer back as it came — as it does when the sends run out — so what the SDK reports is the 429 it is, a+ // refusal that started nothing. That answer says nothing of what the service asked (the SDK's error holds no headers) or of why no more was sent, so the budget is told (`decline`), and the build, which owns the halt, says it.+ // See https://learn.microsoft.com/power-apps/developer/data-platform/api-limits#retry-operations for what a service protection limit asks of the caller.+ async function waitOutThrottle({ res, attempt, method, url, batch }) {+ const at = now();+ // `batch`: an operation refused inside a `$batch` answer carries its own Retry-After, which the outer response need not repeat.+ const asked = Math.max(retryAfterMs(res.headers, at, Infinity), batch ? batchRetryAfterMs(res, at, Infinity) : 0);+ const wait = Math.max(backoffMs(attempt), asked);+ if (!throttle.fits(wait, at)) {+ throttle.decline({ askedMs: asked, waitMs: wait });+ return false;+ }+ const added = throttle.spend(wait, at);+ throttle.announce(`the service throttled ${method} ${new URL(url).pathname} (HTTP 429); waiting ${Math.ceil(wait / 1000)} s before sending it again (${throttle.note()})`, added);+ await sleep(wait);+ return true;+ }+// 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();@@ -722,6 +750,24 @@ function createAzHttpClient(orgUrl, deps = {}) {// (429, 5xx) keeps the status retry above; that trade-off is unchanged.const conditional = isWrite && Object.keys((options && options.headers) || {}).some((h) => h.toLowerCase() === 'if-match');+ // 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) => {+ if (!(res.statusCode >= 200 && res.statusCode < 300)) {+ const text = (value) => (typeof value === 'string' ? scrubText(value) : value);+ return {+ status: res.statusCode,+ headers: scrubValue(res.headers || {}),+ body: ctl.bytes ? scrubBytes(res.body) : ctl.rawBody ? text(res.body) : scrubValue(parseBody(text(res.body))),+ };+ }+ return {+ status: res.statusCode,+ headers: res.headers || {},+ body: ctl.rawBody || ctl.bytes ? res.body : parseBody(res.body),+ };+ };+// Retry: refresh the token once on 401 (no backoff); back off on transient 5xx/429.// 6 attempts with capped jittered backoff rides out a per-entity customization lock that// can stay held for ~20s while a prior metadata op or publish settles.@@ -730,6 +776,8 @@ function createAzHttpClient(orgUrl, deps = {}) {const last = attempt === maxAttempts - 1;const bearer = ensureToken();if (bearer.length >= MIN_SCRUBBED_TOKEN_LENGTH) tokensSent.add(bearer);+ // Noted for everything the process writes, not only for this client's answers: a service may repeat a token it was sent by any client, in an answer that is a success (lib/output-redaction.js).+ noteToken(bearer);const headers = {Authorization: `Bearer ${bearer}`,Accept: 'application/json',@@ -775,6 +823,12 @@ function createAzHttpClient(orgUrl, deps = {}) {continue;}if (TRANSIENT.has(res.statusCode) && !last && !noRetry) {+ // A throttle (HTTP 429) is waited out inside the run's budget when the client has one, and handed back as it came when the wait does not fit (waitOutThrottle). What else is re-sent here — a customization lock or a deadlock+ // 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);+ }await sleep(retryWaitMs(res, attempt));continue;}@@ -803,6 +857,10 @@ function createAzHttpClient(orgUrl, deps = {}) {// has not said that of.const throttled = !once && ((recordDelete && res.statusCode === 429) || ((conditionalDeleteBatch || columnCreateBatch) && isBatchThrottled(res)));if (throttled && !last) {+ if (throttle) {+ if (await waitOutThrottle({ res, attempt, method: method_, url, batch: isBatch })) continue;+ return deliver(res);+ }// 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));continue;@@ -813,21 +871,7 @@ function createAzHttpClient(orgUrl, deps = {}) {await sleep(1000 * 2 ** attempt);continue;}- // 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.- if (!(res.statusCode >= 200 && res.statusCode < 300)) {- const text = (value) => (typeof value === 'string' ? scrubText(value) : value);- return {- status: res.statusCode,- headers: scrubValue(res.headers || {}),- body: ctl.bytes ? scrubBytes(res.body) : ctl.rawBody ? text(res.body) : scrubValue(parseBody(text(res.body))),- };- }- return {- status: res.statusCode,- headers: res.headers || {},- body: ctl.rawBody || ctl.bytes ? res.body : parseBody(res.body),- };+ return deliver(res);}/* istanbul ignore next */throw new Error('Unreachable retry loop');diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex afa1cacf9..91517d420 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -1123,32 +1123,30 @@ const KIND_HANDLERS = {aiSummary: {// AI row-summary records reference the table and would block its delete; remove them first.//- // The SDK's removeRowSummary answers nothing, both when it removes a row summary and when it finds none to remove: it looks up the- // skill row `ais_RowSummary_<table>` and returns at once without one. A step that only called it reported `(1 deleted)` for every- // table that had no row summary. So the step looks first, with the SDK's own request (`GET /aiskillconfigs?…$filter=uniquename eq '…'`,- // which teardown-row-summary-lookup.test.js holds to what the real bundle asks for), and a table with none is "not found" like any- // other step's. The request is the SDK's own, so a lookup that fails is one the removal would fail too: 404 means the environment has- // no such table (so no row summary), and any other answer leaves what is there unknown, which the step says rather than guesses.+ // The SDK looks the row summary up itself and says what it did: `removeRowSummary` answers `{ removed: true }` when the table had one and it is gone, and `{ removed: false }` —+ // deleting nothing — when it had none (cds-maker-sdk 9a0c9f03). It used to answer nothing in both cases, so a step that only called it reported `(1 deleted)` for every table that+ // had no row summary, and 2.16.0 looked for the skill row first with a read of its own. The step makes no read now: it names the table's one candidate, and what the removal+ // answers decides what its line says (`foundNothing`, see deleteStep): a table with none is "not found" like any other step's, and is not counted as a deletion.async resolve(sdk, target) {- const name = `ais_RowSummary_${target.entityLogicalName}`;- let res;+ return [{ id: target.entityLogicalName, entityLogicalName: target.entityLogicalName }];+ },+ async del(sdk, item) {try {- res = await sdk.dataverse.get(`/aiskillconfigs?$select=aiskillconfigid&$filter=uniquename eq '${odataStr(name)}'&$top=1`);+ return await sdk.removeRowSummary({ entityLogicalName: item.entityLogicalName });} catch (err) {- if (isNotFound(err)) return [];- return { items: [], skipReason: `not looked up — ${errMsg(err)}; a row summary left behind is reported by the table's delete` };+ // An environment without the AI skill table (no AI Builder) answers the SDK's lookup of the skill row 404 — "Resource not found for the segment 'aiskillconfigs'" — so it holds+ // no row summary either, which the step has always said as "not found", not as a failure:+ // HTTP 404 from https://contoso.crm.dynamics.com/api/data/v9.0/aiskillconfigs?$select=aiskillconfigid,_aimodel_value&$filter=uniquename eq 'ais_RowSummary_new_memo'&$top=1: ...+ // Only the lookup's 404 says that. The same status on another request of the removal says nothing about the skill row, so it stays the failure it is. The request is the SDK's own,+ // which teardown-row-summary-removal.test.js holds to what the real bundle asks for.+ if (err && err.statusCode === 404 && /\/aiskillconfigs\?/.test(String(err.url || ''))) return { removed: false };+ throw err;}- if (res && res.status === 404) return [];- const rows = res && res.body && res.body.value;- const unknown = (why) => ({ items: [], skipReason: `not looked up — ${why}; a row summary left behind is reported by the table's delete` });- if (!res || res.status < 200 || res.status >= 300) return unknown(`the lookup answered ${res && res.status ? `HTTP ${res.status}` : 'nothing'}`);- if (!Array.isArray(rows)) return unknown('the lookup\'s answer was no list');- return rows.length ? [{ id: target.entityLogicalName, entityLogicalName: target.entityLogicalName }] : [];},- del: (sdk, item) => sdk.removeRowSummary({ entityLogicalName: item.entityLogicalName }),+ foundNothing: (outcome) => Boolean(outcome) && outcome.removed === false,// Best-effort by design: a removal that fails does not fail the teardown — the table's delete that follows reports the dependency if the- // skill row is still there. But it is not a deletion either, so it is said on the step's line, in the SDK's own words (a model it could- // not delete, a skill row it could not confirm gone), where it used to be swallowed and reported as `(1 deleted)`.+ // skill row is still there. But it is not a deletion either, so it is said on the step's line, in the SDK's own words (a lookup it could+ // not make, a model it could not delete, a skill row it could not confirm gone), where it used to be swallowed and reported as `(1 deleted)`.tolerateFailure: (err) => errMsg(err),},solution: {@@ -1510,13 +1508,18 @@ function planTeardown(spec) {// there. `skippedIds` is retained as the union of both for callers that only need the count.// A third reason, `failed` (with a `detail`), is a removal the handler tolerates (`tolerateFailure`).// A not-found error counts as already-gone. Throws only on a genuine failure.+//+// A removal that looks for its artifact itself answers whether there was one: the handler's `foundNothing(outcome)` says so (aiSummary: the SDK's `{ removed: false }`), and that id is+// answered in `absentIds`. It is neither deleted nor skipped — nothing was there — and runTeardown reports it as a step that found nothing, like one whose resolver finds none.async function deleteStep(sdk, handler, items, ctx) {const deletedIds = [];+ const absentIds = [];const skipped = [];for (const item of items) {try {- await handler.del(sdk, item, ctx);- deletedIds.push(item.id);+ const outcome = await handler.del(sdk, item, ctx);+ if (typeof handler.foundNothing === 'function' && handler.foundNothing(outcome)) absentIds.push(item.id);+ else deletedIds.push(item.id);} catch (err) {if (handler.tolerateNotFound && isNotFound(err)) {// Table delete throws not-found even on success; treat as deleted@@ -1560,7 +1563,7 @@ async function deleteStep(sdk, handler, items, ctx) {throw err;}}- return { deletedIds, skippedIds: skipped.map((s) => s.id), skipped };+ return { deletedIds, absentIds, skippedIds: skipped.map((s) => s.id), skipped };}// Execute a teardown. Dry-run discovers page candidates when an SDK reader is supplied, without writes.@@ -1777,7 +1780,13 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {emit({ phase: step.phase, status: 'skip', skip: 'kept', label: why, n: myN, total });continue;}- const { deletedIds, skipped } = await deleteStep(sdk, handler, items, step.kind === 'resetDefaultViews' || step.kind === 'genpage' ? deferredResetPublishes : undefined);+ const { deletedIds, absentIds, skipped } = await deleteStep(sdk, handler, items, step.kind === 'resetDefaultViews' || step.kind === 'genpage' ? deferredResetPublishes : undefined);+ // A removal that looked for its artifact itself and found none is a step that found nothing — the line and the counts a resolver that finds none gets — and not a deletion.+ if (!deletedIds.length && !skipped.length && absentIds.length) {+ result.skipped.push(step.label);+ emit({ phase: step.phase, status: 'skip', skip: 'not-found', label: `${step.label} (not found)`, n: myN, total });+ continue;+ }(result.deleted[step.kind] = result.deleted[step.kind] || []).push(...deletedIds);if (step.kind === 'genpage') {completePageDeletions(opts.workspaceDir, step.target.appUnique, deletedIds, opts.env);diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.jsindex de7a4ef7a..9aa45c861 100644--- a/plugins/model-apps/scripts/lib/source-literals.js+++ b/plugins/model-apps/scripts/lib/source-literals.js@@ -1216,7 +1216,8 @@ function blockBraceAt(out, k) {// left-hand-side expressions that the parser reads as it reads any other (parseExpressionWithTypeArguments, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts), and a `)` ends the last of them when it is a call or a parenthesis:// class C extends mixin(A) { class C extends (Base) { class C extends a.b.mixin(A) { class C extends new Base() { valid// class C implements B() { class C implements (B) { class C extends A, B() { interface I extends A, B() { parse, and only the checker objects (TS2500, TS1174, TS2499)-// A call or a parenthesis that follows the keyword `extends` or `implements` (heritageKeywordAt), `new`, directly or as the last of the names that dots join (`a.b.mixin`), or that follows a comma of such a list (heritageListBefore), may be one, so it is not taken for a head.+// A call or a parenthesis that follows the keyword `extends` or `implements` (heritageKeywordAt), `new`, directly or as the last of the names that dots join (`a.b.mixin`), or that follows a comma of such a list (heritageListBefore), may be one, so it is not taken for a head — but for a `new` that+// names a field of a class and is ended by a line break, whose call is the head of the next member (newNamesField).// Neither is a call that follows anything the names do not go back to: a `)`, a `]`, a `>` (type arguments), a `?.` or a `!`, an escape, a letter beyond ASCII — what is not read is not a head. A comma that no heritage list holds separates the members of an object// literal, and the call after it is a method's head (`{ a: 1, m() { … } }`); and a word that a class's head does not lead to is no keyword but a name, whose call is a head all the same (`class C { implements() { … } }`, `{ extends() { … } }`).function closesBodyHead(out, close) {@@ -1235,13 +1236,31 @@ function closesBodyHead(out, close) {if (before.ch !== '.') {const { token, index } = tokenBeforeAngle(out, name.start + 1);if (token === ',') return !heritageListBefore(out, index);- return token !== 'new' && !heritageKeywordAt(out, token, index - token.length);+ if (token === 'new') return newNamesField(out, index, name.start + 1);+ return !heritageKeywordAt(out, token, index - token.length);}name = wordBefore(out, before.index);}return false;}+// Whether the `new` that ends at `index`, which stands right before the name that starts at `nameStart` of the call that a `{` follows, is the name of a class field that a line break ends, and no operator: the call is then the head of the next member, a method, and its braces are+// its body. The two are the same text up to the `{`:+// class C extends new⏎ Base() { the operator: `Base()` is an element of the heritage, and the braces hold members+// class C { new⏎ render() { a field named `new` and a method: a line break ends a field with no `;` (https://tc39.es/ecma262/#sec-automatic-semicolon-insertion)+// What stands before the `new` tells them apart. A field begins a member of a class, so a member may begin at it and the braces around it are a class's body (the head of one that is read back to its `class`, as a class that is complete is: a block, the body of a function and the braces of an object+// literal have no such field); and it follows no element of a heritage, which is what the operator's `new` does — the keyword that begins the list (`implements⏎ new⏎ Base() {`: for memberMayBeginAt a line break after a word that may name a field ends a member) or a comma of the list.+// A `new` and a name on one line are no field and member (a field's name is followed by a `;`, a `}` or a line break), and what is not told stays the operator, as it was: the braces after the call may hold members.+function newNamesField(out, index, nameStart) {+ const start = index - 'new'.length + 1;+ if (cutsWord(out, start - 1) || !lineBreakBetween(out, index + 1, nameStart)) return false;+ const body = openerBefore(out, start);+ if (body.ch !== '{' || !memberMayBeginAt(out, start, 0) || completedClassStart(out, body.index, start) < 0) return false;+ const before = tokenBeforeAngle(out, start);+ if (before.token === ',') return !heritageListBefore(out, before.index);+ return !heritageKeywordAt(out, before.token, before.index - before.token.length);+}+// Whether `word`, which ends right before a `(` or a name and starts after the character at `before`, is the keyword `extends` or `implements` of a heritage clause, whose elements follow it, and not a name that spells it: a method (`class C { implements() { … } }`), a function// (`function implements() { … }`), a property or a value of an object literal (`{ extends() {} }`, `{ a: implements, m() {} }`). The keyword follows the head of a class or an interface — its name, its type parameters, another heritage clause — and that head is read back from the word to// `class` or `interface` (readHeritageBack, which reads what a head holds). A name stands after what a head has no place for — a `{` that nothing closed, a `;`, a `:`, an `=`, a modifier, a line break after a member — and the scan stops there; a decorator is read through, as the one of a@@ -1271,6 +1290,9 @@ function heritageListBefore(out, comma) {// What readHeritageBack answers: where the `class` or the `interface` that begins the head stands (a heritage is there), NO_HERITAGE (none is), or HERITAGE_UNREAD, where an escape or a window that ended first left it open (a heritage may be there).const NO_HERITAGE = -1;const HERITAGE_UNREAD = -2;+// How many class expressions may stand one in the head of the other with no parenthesis between them (`class extends class extends class {} {} {`), for the scan that reads a head alone (`flat`): it counts the braces that it crosses, and stops at the limit. A head that+// is nested deeper — none that a page has — is read as it was: no class that is complete. The limit is also what keeps the head of every method of an object literal from being read back over all the methods before it, whose braces are crossed too until a `class` is wanted for them.+const HEAD_NESTING = 4;// The scan behind heritageListBefore (`list`: the elements of a list, read back from a comma to the keyword that begins it) and heritageKeywordAt (not `list`: the head of a class or an interface, read back from a keyword to `class` or `interface`). The two read the same tokens; they differ// in the word that ends them: a keyword `extends` or `implements` for a list — which is a heritage's only where a head leads to it, so the scan of the head decides — and `class` or `interface` for a head. A property (`a.class`) is neither.@@ -1278,24 +1300,30 @@ const HERITAGE_UNREAD = -2;// const registry = { Adapter: class extends Base {}, render() { … } }; the comma and `render` come after a class that is complete: the braces of `render` are a method's body// class Q {}⏎function implements() { … } `implements` names a function// completedClassStart reads such braces back to their class; the scan goes on from before its `class`, where what stands is what the class is the value or the element of: a `:` or an `=` (a value: no heritage), an `extends`, an `implements` or a `,` (an element of a list:-// `class C extends class {} implements (B) {` has the heritage of C), a `;` or the start of the source. `flat` reads such a head alone, to its `class`, and crosses no braces: the scan of a list reads a head for each braces that it meets, and one that read the heads-// of all the braces before them would read them all again for each (a run of methods in an object literal).+// `class C extends class {} implements (B) {` has the heritage of C), a `;` or the start of the source. `flat` reads such a head alone, to its `class`. The braces at its own level are crossed only as the bodies of class expressions (`class extends class {} {`: the head of the base is read on from before its `class`, as the head of the element it is). Braces are crossed where+// what stands before them ends a head (endsClassHead: not after `extends`, `implements`, a comma or `new`, where they are an object literal's) and are counted; a `class` that is read takes one off, and the head is read where none is left. A function expression has no `class` for its braces — the scan meets its `function` — so its+// head is not read (no class that is complete), and no more than HEAD_NESTING braces are crossed at a time: the scan of a list reads a head for each braces that it meets, and one that read the heads of all the braces before them would read them all again for each (a run of methods in an object literal).function readHeritageBack(out, from, list, flat = false) {let brackets = 0; // the closing brackets read whose opener is not read yetlet angles = 0; // the same for the `>` that ends type arguments+ let pending = 0; // flat: the braces at the head's own level that are crossed and whose `class` is not read yet+ let nested = false; // flat: the head holds a class expression, read wholelet k = from - 1;for (; k >= 0 && from - k <= LOOKAHEAD; k -= 1) {const c = out[k];if (c === ')' || c === ']' || c === '}') {- // Braces at the head's own level are no part of a head that is read alone.- if (flat && c === '}' && brackets === 0 && angles === 0) return NO_HERITAGE;brackets += 1;} else if (c === '(' || c === '[' || c === '{') {if (brackets === 0) return NO_HERITAGE;brackets -= 1;- if (c === '{' && brackets === 0 && angles === 0 && !flat) {- const head = completedClassStart(out, k, from);- if (head >= 0) k = head;+ if (c === '{' && brackets === 0 && angles === 0) {+ if (!flat) {+ const head = completedClassStart(out, k, from);+ if (head >= 0) k = head;+ } else if (!endsClassHead(out, k, from - LOOKAHEAD) || ++pending > HEAD_NESTING) {+ // The braces are no class's body where nothing that ends a head stands before them (`extends {} {`, `, {} {`: an object literal), or are too many.+ return NO_HERITAGE;+ }}} else if (brackets > 0) {continue;@@ -1322,11 +1350,17 @@ function readHeritageBack(out, from, list, flat = false) {if (flat && word === 'function') return NO_HERITAGE;if (list && (word === 'extends' || word === 'implements')) return readHeritageBack(out, start, false);// A class may be named `interface` (`class interface {}`): the `class` before the name is the head's.- if (!list && (word === 'class' || (word === 'interface' && wordBefore(out, start).word !== 'class'))) return start;+ if (!list && (word === 'class' || (word === 'interface' && wordBefore(out, start).word !== 'class'))) {+ if (pending === 0) return start;+ // The `class` of a class expression whose braces were crossed: it belongs to the head that those braces are the body of, and the one that holds it is read on.+ if (word === 'interface') return NO_HERITAGE;+ pending -= 1;+ nested = true;+ }}k = start;- } else if (isTrivia(c) || ',.!*/\'"`'.includes(c) || (c === '@' && !flat)) {- // The `@` of a decorator on a class expression, which is an element like the class it decorates: `class C implements new @d class {}, B() {`.+ } else if (isTrivia(c) || ',.!*/\'"`'.includes(c) || (c === '@' && (!flat || nested))) {+ // The `@` of a decorator on a class expression, which is an element like the class it decorates: `class C implements new @d class {}, B() {`. A head that is read alone has none of its own, but its class expressions have.continue;} else if ((c === '+' || c === '-') && /[eE]/.test(out[k - 1] || '') && /[\d.]/.test(out[k - 2] || '')) {// The sign of a number's exponent, which belongs to the one token that `1e+5` is.@@ -1352,25 +1386,27 @@ function significantBefore(out, at, floor) {}// Where the class whose body begins with the `{` at `open` starts — the index of its `class` or its `interface` — or NO_HERITAGE where the braces are no class's body, for the scan that readHeritageBack makes back from `from`. A class is complete, and crossed by the scan,-// when what stands before its `{` ends a head and a head that no braces interrupt leads from it back to a `class`: a name (`class Named {`, `class extends Base {`, `class {`), the `)` of a call (`extends mixin(A) {`), a `]`, the `>` of type arguments (`extends Base<T> {`),-// a `!` or a literal. Braces are an object literal's, which a head has no place for, after `extends`, `implements` (but for a class named so: `class implements {}`) or any other word that takes an operand (EXPR_START_WORDS), a comma, a `:`, an `=` or an operator; the braces+// when what stands before its `{` ends a head and a head that no braces interrupt — but the bodies of class expressions, which a head may hold (`class extends class {} {`) — leads from it back to a `class`: a name (`class Named {`, `class extends Base {`, `class {`), the `)` of a call (`extends mixin(A) {`), a `]`, the `>` of type arguments (`extends Base<T> {`),+// a `!` or a literal, or the `}` that ends the body of such a class expression (what the scan makes of it is readHeritageBack's). Braces are an object literal's, which a head has no place for, after `extends`, `implements` (but for a class named so: `class implements {}`) or any other word that takes an operand (EXPR_START_WORDS), a comma, a `:`, an `=` or an operator; the braces// of an arrow function (`=> {`) and of a function (`function () {`) are read back to no `class` either, and a JSX container (`<p>{a}</p>`) to the `<` of its tag, which no program that parses has a `class` before (an element follows an operator or a separator). What is not told is left// to the scan, which then meets the class's own `extends` and `class` as it would the keyword of a list: the guess side, since the braces after the call may hold members.function completedClassStart(out, open, from) {- const floor = from - LOOKAHEAD;+ return endsClassHead(out, open, from - LOOKAHEAD) ? readHeritageBack(out, open, false, true) : NO_HERITAGE;+}++// Whether what stands before the `{` at `open`, no further back than `floor`, ends the head of a class, which the braces are the body of: a name that is no word that takes an operand, a `)`, a `]`, a `>`, a `!`, a literal, or the `}` of a class expression that the head ends in.+// Braces after anything else are an object literal's (`extends {`, `, {`, `= {`, `new {`) or a block's, and are no body of a class.+function endsClassHead(out, open, floor) {const before = significantBefore(out, open, floor);const c = before.ch;- let endsHead = false;- if (')]>!"\'`'.includes(c) && c !== '') {- endsHead = true;- } else if (c !== '' && isNamePart(c)) {- let start = before.index;- while (start > 0 && start > floor && isNamePart(out[start - 1])) start -= 1;- let word = '';- for (let q = start; q <= before.index; q += 1) word += out[q];- endsHead = !EXPR_START_WORDS.has(word) && (word !== 'implements' || wordBefore(out, start).word === 'class');- }- return endsHead ? readHeritageBack(out, open, false, true) : NO_HERITAGE;+ if (c === '') return false;+ if (')]>!"\'`}'.includes(c)) return true;+ if (!isNamePart(c)) return false;+ let start = before.index;+ while (start > 0 && start > floor && isNamePart(out[start - 1])) start -= 1;+ let word = '';+ for (let q = start; q <= before.index; q += 1) word += out[q];+ return !EXPR_START_WORDS.has(word) && (word !== 'implements' || wordBefore(out, start).word === 'class');}// Whether a member may begin at `at`, where a word or a `*` starts. After a separator it does; after a modifier on the same line it does if a member may begin at the modifier (`a in delete <U>(y)</U>` has an operator, not a modifier,@@ -4423,4 +4459,4 @@ function ellipsisFollowedByStatement(mask, k) {return STATEMENT_WORDS.has(word) || word === 'import' || word === 'export';}-module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES };+module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING };diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.jsindex d42b3c69d..44e0bccd3 100644--- a/plugins/model-apps/scripts/lib/spec-lint.js+++ b/plugins/model-apps/scripts/lib/spec-lint.js@@ -2,7 +2,7 @@// Pure App Spec guardrail. Returns { ok, errors, warnings }. errors block the plan// gate; warnings teach. Bakes in the modeling lessons hit live — notably the// relationship schema-name vs lookup-name collision Dataverse rejects.-const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef, labelText, appMembershipWarnings, subgridPlacementProblems, subgridDuplicateProblems, subgridUnknownKeys } = require('./app-spec.js');+const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef, labelText, derivedPluralName, appMembershipWarnings, subgridPlacementProblems, subgridDuplicateProblems, subgridUnknownKeys } = require('./app-spec.js');const { compileFormIntent, formFieldLogicals, NON_FORM_RENDERABLE_TYPES } = require('./artifact-intent.js');const { normalizeSpecShape } = require('./spec-shape.js');const { resolveSurfaces, unresolvedSurfaceMessage } = require('./surface-resolver.js');@@ -10,6 +10,7 @@ const { nearestName } = require('./nearest-name.js');const { isAppSourcePath } = require('./app-source-path.js');const { labelLintWarnings } = require('./view-filter-labels.js');const { navigationVerdict } = require('./app-navigation.js');+const { noPersonasWarning, uncoveredTables, uncoveredTablesWarning } = require('./app-access.js');const CHOICE_OPTION_WARN = 12;const SEQNUM_RE = /\{SEQNUM(:\d+)?\}/i;@@ -467,7 +468,7 @@ function lintAppSpec(spec) {// author picks a distinct name (or knowingly customizes the stock default).const ve = (spec.entities || []).find((x) => lc(x.schemaName) === lc(v.entity));if (ve && v.name) {- const plural = labelText(ve.pluralName, spec && spec.languageCode) || `${labelText(ve.displayName, spec && spec.languageCode) || ve.schemaName}s`;+ const plural = labelText(ve.pluralName, spec && spec.languageCode) || derivedPluralName(ve, spec && spec.languageCode);if (lc(v.name) === `active ${lc(plural)}` || lc(v.name) === `inactive ${lc(plural)}`) {W(`View '${v.name}' has the same name as ${ve.schemaName}'s stock default view — it will MERGE onto that default (columns are unioned and the stock "Created On" is kept, but its filters/sort are ignored). Use a distinct name to author a separate view.`);}@@ -609,10 +610,17 @@ function lintAppSpec(spec) {.filter((j) => j && typeof j === 'object').map((j) => ({ persona: p.persona, job: j })));if (!personas.length) {- W('no personas[] — no jobs-to-be-done are recorded and no security role is authored, so the app opens only for system administrators. Capture who uses this app and what each of them needs to get done.');+ // Says what the spec authors, and who can open the app only as a condition: no personas[] is also how an extension of an app that already has roles+ // is written on purpose (a persona's role is converged to the declared privileges, so it is not how to add one table to somebody else's role), and+ // a spec cannot tell the lint whether the app is new. See lib/app-access.js.+ W(noPersonasWarning(spec));} else if (!jobs.length) {W('personas[] declares no jobs — a persona with no jobs-to-be-done neither documents the app nor sizes its security role.');}+ // A table this spec creates is used by the users of a role only once a privilege on it is granted: by a persona, or by a roleGrants[] entry for a role that+ // already exists. Whatever roles the app has, nothing here gives any of them this table.+ const withoutAccess = uncoveredTables(spec);+ if (withoutAccess.length) W(uncoveredTablesWarning(withoutAccess));for (const { persona, job } of jobs) {if (!(Array.isArray(job.surfaces) && job.surfaces.length)) {W(`persona "${persona}" job "${job.name}" is not mapped to a surface (jobs[].surfaces[]) — nothing in this app demonstrably lets that persona do the job.`);diff --git a/plugins/model-apps/scripts/lib/strict-xml.js b/plugins/model-apps/scripts/lib/strict-xml.jsindex a5e18ab6f..32e0d2fa4 100644--- a/plugins/model-apps/scripts/lib/strict-xml.js+++ b/plugins/model-apps/scripts/lib/strict-xml.js@@ -2,7 +2,8 @@// ONE strict reader of ONE XML document, in ONE pass, for the decision in this plugin that must not be wrong in the dangerous direction: which// elements a document holds, when a generative page is DELETED because an element of an app's sitemap names it (sitemap-pages.js, navigationGenPageIds).// It also reads the two FormXML documents verify compares to prove a dashboard's tiles are the published ones (formxml-layers.js): there, a document it-// does not read is a difference, never the same document.+// does not read is a difference, never the same document. And it reads the workbook of a translation export, from which verify settles a form's captions+// (translation-labels.js), with the two options a caller that does not trust a document's shape needs (`maxDepth`, `elementOnly`: see readXmlElements).//// WHY NOT REGULAR EXPRESSIONS. The navigation used to be read by three passes over the text, each taking one kind of construct out of it (comments, then// CDATA sections, then processing instructions) before the elements were matched. XML has no such order: a delimiter is data wherever the construct that@@ -153,21 +154,36 @@ function position(xml, at) {* readXmlElements('<labels><label languagecode="3082" /></labels>', (name) => name === 'label', { spans: true })* → { ok: true, elements: [ { name: 'label', path: 'labels', attrs: { languagecode: '3082' }, start: 8, end: 37 } ] }*+ * Two more options are for a caller that reads a document it does not trust to be the shape it expects (lib/translation-labels.js reads a translation export+ * with them); without them nothing changes:+ * - `maxDepth`: the deepest an element may be (the root is at depth 1). Each element answered carries its `path`, the names of its ancestors, so a document+ * nested deep and asked for at every level costs the SQUARE of its depth: some 140 KB of `<a><a>…` exhaust the heap of the process that reads them. A+ * document nested deeper is refused at the start tag of the first element that goes over, before that element is read.+ * - `elementOnly`: a function of an element's name that says the element holds elements and white space only (a spreadsheet's Table, Row and Cell). Text, a+ * reference, a CDATA section, a comment or a processing instruction directly inside such an element is refused: what a caller that reads elements skips+ * there could be what the document meant.+ ** @param {*} xml the text of the document; anything that is not a string is refused* @param {(name: string) => boolean} wanted decides which elements are answered, by their names as written- * @param {{ spans?: boolean }} [options]+ * @param {{ spans?: boolean, maxDepth?: number, elementOnly?: (name: string) => boolean }} [options]* @returns {{ ok: true, elements: { name: string, path: string, attrs: Object<string, string>, start?: number, end?: number }[] } | { ok: false, detail: string }}+ * @throws {TypeError} when `maxDepth` is given and is not a whole number of at least 1, or `elementOnly` is given and is not a function — a mistake of the+ * caller, which must not read as "no bound"*/function readXmlElements(xml, wanted, options) {+ const maxDepth = options ? options.maxDepth : undefined;+ if (maxDepth !== undefined && !(Number.isSafeInteger(maxDepth) && maxDepth >= 1)) throw new TypeError(`maxDepth must be a whole number of at least 1, not ${String(maxDepth)}`);+ const elementOnly = options ? options.elementOnly : undefined;+ if (elementOnly !== undefined && typeof elementOnly !== 'function') throw new TypeError('elementOnly must be a function of an element name');try {- return { ok: true, elements: scan(xml, wanted, !!options && options.spans === true) };+ return { ok: true, elements: scan(xml, wanted, !!options && options.spans === true, maxDepth === undefined ? Infinity : maxDepth, elementOnly) };} catch (e) {if (!(e instanceof Refusal)) throw e;return { ok: false, detail: e.at === undefined ? e.message : `${e.message}, at ${position(xml, e.at)}` };}}-function scan(xml, wanted, spans) {+function scan(xml, wanted, spans, maxDepth, elementOnly) {if (typeof xml !== 'string') throw new Refusal(undefined, 'the XML is not text');const illegal = ILLEGAL_CHAR.exec(xml);if (illegal) throw new Refusal(illegal.index, 'a character that XML does not allow');@@ -177,6 +193,11 @@ function scan(xml, wanted, spans) {// The names of the elements that are open, outermost first, and the default namespace each is in (a `xmlns="…"` attribute sets it, and an element inherits it).const open = [];const defaultNamespace = [];+ // With `elementOnly`, beside `open`: whether each open element holds elements and white space only.+ const openElementOnly = [];+ const inElementOnly = () => openElementOnly.length > 0 && openElementOnly[openElementOnly.length - 1];+ // What may not be directly inside an element that holds elements only, said where it is.+ const notInElementOnly = (at, what) => new Refusal(at, `${what} inside <${open[open.length - 1]}>, which holds elements only`);// With `spans`, beside `open`: the answered element each open one is (null for one not asked for), so that its end tag can say where it ends.const openAnswered = [];// For each kind of element, where the SDK's parser looks for the end of an element of that kind: the last place the text `</name>` is, or `</name` if there is none after the first start tag.@@ -245,6 +266,8 @@ function scan(xml, wanted, spans) {if (!found) throw new Refusal(from, 'a "<" that starts no element, comment, processing instruction or CDATA section');if (state === EPILOG) throw new Refusal(from, 'a second root element (a document has exactly one)');const name = found[0];+ // The bound holds before anything of the element is read: its path is never built, its attributes never decoded.+ if (open.length >= maxDepth) throw new Refusal(from, `elements nested more than ${maxDepth} levels deep`);const attrs = Object.create(null);let p = from + 1 + name.length;let selfClosing = false;@@ -295,6 +318,7 @@ function scan(xml, wanted, spans) {} else {noteWhatTheSdkParserMisreads(from, p - 1, name, attrs);open.push(name);+ if (elementOnly) openElementOnly.push(!!elementOnly(name));if (spans) openAnswered.push(answered);state = CONTENT;}@@ -335,6 +359,7 @@ function scan(xml, wanted, spans) {if (found[0] !== expected) throw new Refusal(from, `closing tag </${found[0]}> where </${expected}> is expected`);open.pop();defaultNamespace.pop();+ openElementOnly.pop();if (spans) {const answered = openAnswered.pop();if (answered) answered.end = p + 1;@@ -358,8 +383,19 @@ function scan(xml, wanted, spans) {return end;}+ // The content of an element that holds elements only, from `from` up to the next "<": white space as written, and nothing else — a reference, even to a+ // space, is text.+ function whiteSpaceOnly(from) {+ let p = from;+ for (; p < n && xml.charCodeAt(p) !== LT; p += 1) {+ if (!isSpace(xml.charCodeAt(p))) throw notInElementOnly(p, 'text');+ }+ return p;+ }+// `<!-- … -->`: the content has no "--" in it (so it cannot end in a "-" either: "--->" is refused), which is why the first "--" has to be the end.function comment(from) {+ if (state === CONTENT && inElementOnly()) throw notInElementOnly(from, 'a comment');const dashes = xml.indexOf('--', from + 4);if (dashes < 0) throw new Refusal(from, 'a comment that is never closed');if (xml.charCodeAt(dashes + 2) !== GT) throw new Refusal(dashes, "'--' inside a comment");@@ -372,6 +408,7 @@ function scan(xml, wanted, spans) {const target = NCNAME.exec(xml);if (!target) throw new Refusal(from, 'a processing instruction with no target');if (/^xml$/i.test(target[0])) throw new Refusal(from, 'a processing instruction named "xml" (only the XML declaration at the very start of the document may be)');+ if (state === CONTENT && inElementOnly()) throw notInElementOnly(from, 'a processing instruction');const p = from + 2 + target[0].length;if (xml.startsWith('?>', p)) return p + 2;if (!isSpace(xml.charCodeAt(p))) throw new Refusal(p, 'a processing instruction whose target is not followed by white space or "?>"');@@ -385,6 +422,7 @@ function scan(xml, wanted, spans) {if (xml.startsWith('<!--', from)) return comment(from);if (xml.startsWith('<![CDATA[', from)) {if (state !== CONTENT) throw new Refusal(from, 'a CDATA section outside the root element');+ if (inElementOnly()) throw notInElementOnly(from, 'a CDATA section');const end = xml.indexOf(']]>', from + 9);if (end < 0) throw new Refusal(from, 'a CDATA section that is never closed');return end + 3;@@ -404,7 +442,7 @@ function scan(xml, wanted, spans) {while (at < n) {if (xml.charCodeAt(at) !== LT) {- if (state === CONTENT) at = characterData(at);+ if (state === CONTENT) at = inElementOnly() ? whiteSpaceOnly(at) : characterData(at);else if (isSpace(xml.charCodeAt(at))) at += 1;else throw new Refusal(at, state === PROLOG ? 'text before the root element' : 'text after the root element');continue;diff --git a/plugins/model-apps/scripts/lib/throttle-budget.js b/plugins/model-apps/scripts/lib/throttle-budget.jsindex fc2db7dcd..681fe42c1 100644--- a/plugins/model-apps/scripts/lib/throttle-budget.js+++ b/plugins/model-apps/scripts/lib/throttle-budget.js@@ -1,17 +1,26 @@'use strict';-// The budget a run allows itself for the waiting its OWN retry layers add when the service throttles.+// The budget a run allows itself for the waiting it does when the service throttles.//-// Two layers of the build wait out a throttle on top of what the HTTP client does for a request. The page backend (lib/genpage-sdk.js) sends a throttled page write again after each answer — a page's change set is a `$batch` the client never-// re-sends — waiting what the service asked (`Retry-After`) or its own schedule; and when its sends are not enough, the build (build-model-app.js) runs the phase again after a wait of its own. With an account in each layer, a service that kept-// asking for a minute would cost one page 24 sends and about twenty minutes of waiting in which nothing was said, and the wait the service asked for would be lost where the one layer hands over to the other.+// Three layers of a run wait out a throttle. The HTTP client (lib/sdk-http-client.js) sends a throttled read, publish, delete or column create again — at most five re-sends, after the schedule's wait (1, 2, 4, 8 and 8 s) or after what the+// answer's `Retry-After` asks. The page backend (lib/genpage-sdk.js) sends a throttled page write again after each answer — a page's change set is a `$batch` the client never re-sends — waiting what the service asked or its own schedule.+// And when those sends are not enough, the build (build-model-app.js) runs the phase again after a wait of its own. With an account in each layer, a service that kept asking for a minute would cost one page 24 sends and about twenty minutes+// of waiting in which nothing was said, and the wait the service asked for would be lost where the one layer hands over to the other.//-// So the waiting those two layers add is ONE budget — five minutes — shared by both: each asks `fits(ms)` before a wait, `spend`s it when it takes it, and stops, saying what the service asked, when it does not fit (`waitDoesNotFit`). The layers-// wait with seams of their own (the backend's `deps.sleep`, the build's `deps.sleep`), so this only COUNTS; a wait is counted whole when it is scheduled, however it ends. What a wait of more than a few seconds says is a line on the `warn` seam-// the caller gives, which the build wires to stderr: stdout carries the JSON result. The build makes the budget and hands it to every page write; a page write that is given none (the upload script's) makes one of its own for that write.+// So the waiting those layers do for a throttle is ONE budget — five minutes — shared by all of them: each asks `fits(ms)` before a wait, `spend`s it when it takes it, and stops, saying what the service asked, when it does not fit+// (`waitDoesNotFit`). The layers wait with seams of their own (the client's and the backend's `deps.sleep`, the build's `deps.sleep`), so this only COUNTS; a wait is counted whole when it is scheduled, however it ends. What a wait of more than a few+// seconds says is a line on the `warn` seam the caller gives, which the build wires to stderr: stdout carries the JSON result. The build makes the budget and hands it to the HTTP client of its SDK, to the page backend (which gives it to the client it+// makes) and to every page write; the upload script makes one for its run and hands it to its backend. A page write that is given none, by a backend that was handed none, makes one of its own for that write.//-// What it does NOT count is the HTTP client's own waiting. The production client (lib/sdk-http-client.js) re-sends a throttled read, publish, delete or column create on a schedule of its own — at most five re-sends, waiting 1, 2, 4, 8 and 8 s,-// or what the answer's `Retry-After` asks (up to a minute) — exactly as it did before this budget existed. Charging that to the run would halt a build that is throttled for a while and still succeeds today, so a run's total waiting is NOT bounded-// by this budget: it bounds what the layers above the client add, and each request keeps the bound it always had below it.+// The client's waits can overlap: it sends several requests at once, and a service that throttles them answers them alike, so they wake together. What a run waited is the time it spent waiting, not the sum of its requests' waits, so a wait that+// is PLACED on the clock (`spend(ms, at)`, `at` the moment it starts) adds only what runs past the end of the waits placed before it. The backend and the build wait one at a time, place nothing, and add whole.+//+// A throttled request that the client will not wait for, because the wait does not fit, is handed back as it came: the SDK reports it as the 429 it is, which says nothing of what the service asked or of why nothing more was sent. So the client+// says so here (`decline`), and the build, which owns the halt, reads it (`declined`). The line the client says is the fact alone (`refusedWait`), with no advice on what to run next: the client does not know what its caller did before the request —+// the upload script's publish comes after a create that has committed, where a run of the same command again would make a second page — so that is the caller's to say: the build's halt (`waitDoesNotFit`), whose run is idempotent, and the upload's+// result, which names the page that was saved.+//+// What is NOT drawn from it is a wait that is not for a throttle: the client keeps its own schedule for a 5xx (a customization lock, a SQL deadlock victim, a gateway), a reset connection and the re-send of a deadlock victim. And a script that+// gives its client no budget — every script but the build and the page upload — waits as it always did.// See https://learn.microsoft.com/power-apps/developer/data-platform/api-limits#retry-operations for what the service asks.const THROTTLE_BUDGET_MS = 5 * 60 * 1000;// A wait this short is not worth a line: the first waits of the schedule (1 s, 2 s, 4 s) and a short `Retry-After` pass in silence.@@ -24,21 +33,53 @@ const sizeOf = (ms) => (ms % 60000 === 0 ? `${ms / 60000} minute${ms === 60000 ?// `warn(message)` is the caller's line seam (optional); `totalMs` is for a caller that wants another size.function makeThrottleBudget({ totalMs = THROTTLE_BUDGET_MS, warn } = {}) {let spent = 0;- return {+ // The end, on the clock of the callers that place their waits, of the latest wait placed so far.+ let placedUntil = 0;+ // The waits that did not fit, as the HTTP client met them: how many, the longest the service asked for and the longest wait, and the longest wait already said.+ let declines = 0;+ let declinedAskMs = 0;+ let declinedWaitMs = 0;+ let saidWaitMs = 0;+ // What a wait of `ms` adds to what the run has waited. A wait that is placed (`at` is a moment) adds only what runs past the end of the waits placed before it — it may overlap them, and what is waited together is waited once; one that is not+ // placed is added whole.+ const addedBy = (ms, at) => (Number.isFinite(at) ? Math.max(0, at + ms - Math.max(placedUntil, at)) : ms);+ const budget = {totalMs,spentMs: () => spent,remainingMs: () => Math.max(0, totalMs - spent),- // Whether a wait of `ms` is within what is left — to the millisecond, so a wait that takes the last of the budget fits.- fits: (ms) => ms <= totalMs - spent,- // A value that is no wait (not a number, not positive) is none.- spend(ms) { if (Number.isFinite(ms) && ms > 0) spent += ms; },+ // Whether a wait of `ms` is within what is left — to the millisecond, so a wait that takes the last of the budget fits. `at` places it (see addedBy): it fits when what it would add does.+ fits: (ms, at) => addedBy(ms, at) <= totalMs - spent,+ // Takes a wait of `ms` out of the budget, and answers what it added. A value that is no wait (not a number, not positive) is none. `at`, the moment the wait starts, places it: it adds only what runs past the waits placed before it.+ spend(ms, at) {+ if (!(Number.isFinite(ms) && ms > 0)) return 0;+ const added = addedBy(ms, at);+ spent += added;+ if (Number.isFinite(at)) placedUntil = Math.max(placedUntil, at + ms);+ return added;+ },// Says `message` when the wait of `ms` is longer than a few seconds, and only then.announce(message, ms) { if (ms > QUIET_WAIT_MS && typeof warn === 'function') warn(message); },+ // A wait of `waitMs` that the HTTP client did not take, because it did not fit; `askedMs` is what the service asked, when it asked. It is said once for each wait longer than any said before: four requests that are refused together are one line.+ decline({ askedMs = 0, waitMs } = {}) {+ const finite = (ms) => (Number.isFinite(ms) && ms > 0 ? ms : 0);+ declines += 1;+ declinedAskMs = Math.max(declinedAskMs, finite(askedMs));+ declinedWaitMs = Math.max(declinedWaitMs, finite(waitMs));+ if (finite(waitMs) > saidWaitMs) {+ saidWaitMs = finite(waitMs);+ if (typeof warn === 'function') warn(refusedWait(budget, { askedMs: finite(askedMs), waitMs: finite(waitMs) }));+ }+ },+ // How many waits did not fit, and the longest the service asked and the longest wait among them: what the build reads to say that the budget stopped a request.+ declined: () => ({ count: declines, askedMs: declinedAskMs, waitMs: declinedWaitMs }),+ // How much of the budget is gone, in the words of the line that announces a wait.+ note: () => spentNote(budget),};+ return budget;}// What a run says about how much of the budget is gone, for the line that announces a wait: "47 s of the 5 minutes a run allows itself for waiting out a throttled service are spent". It is a "run" because the budget is-// the build's and the upload's alike (an upload that is given none makes one of its own for its write). It says what the run ALLOWS ITSELF, not what it has waited in all: the HTTP client's own waits are not drawn from it.+// the build's and the upload's alike (the upload script makes one for its run; a page write that is given none, by a backend that was handed none, makes one of its own for that write). It says what the run ALLOWS ITSELF for a throttle's waits: the waits that are not for a throttle are not drawn from it.function spentNote(budget) {return `${seconds(budget.spentMs())} of the ${sizeOf(budget.totalMs)} a run allows itself for waiting out a throttled service are spent`;}@@ -50,4 +91,12 @@ function waitDoesNotFit(budget, { askedMs = 0, waitMs }) {return `${lead} in what is left of the ${sizeOf(budget.totalMs)} a run allows itself for waiting out a throttled service (${seconds(budget.spentMs())} are spent). Nothing more is sent now: run the same command again later, and it continues from here.`;}-module.exports = { THROTTLE_BUDGET_MS, QUIET_WAIT_MS, makeThrottleBudget, waitDoesNotFit, spentNote };+// What the HTTP client says when it will not wait for a throttled request: the facts of `waitDoesNotFit` — what the service asked, how much of the budget is gone — and that the request was not sent again, and NOTHING of what to run next. A request the+// client refuses may follow a write that has committed (the upload's publish follows its create), where "run the same command again" would make a second page: the way on is for the caller that knows its state to give, and the client's line must+// not contradict it. `askedMs` and `waitMs` are as for `waitDoesNotFit`.+function refusedWait(budget, { askedMs = 0, waitMs }) {+ const lead = askedMs > 0 ? `the service asked to wait ${seconds(askedMs)} before this request is sent again, which does not fit` : `the next wait before this request is sent again, ${seconds(waitMs)}, does not fit`;+ return `${lead} in what is left of the ${sizeOf(budget.totalMs)} a run allows itself for waiting out a throttled service (${seconds(budget.spentMs())} are spent), so it was not sent again.`;+}++module.exports = { THROTTLE_BUDGET_MS, QUIET_WAIT_MS, makeThrottleBudget, waitDoesNotFit, refusedWait, spentNote };diff --git a/plugins/model-apps/scripts/lib/translation-labels.js b/plugins/model-apps/scripts/lib/translation-labels.jsnew file mode 100644index 000000000..b58af62a8--- /dev/null+++ b/plugins/model-apps/scripts/lib/translation-labels.js@@ -0,0 +1,433 @@+'use strict';+// The captions of a solution's forms, in EVERY provisioned language, from ONE translation export — what `--verify` reads a tab's or a section's caption from+// in a language the form's own read cannot show (lib/verify-spec.js, `labelProblem`).+//+// WHY AN EXPORT. The platform decides which languages' labels go into the FormXML a caller reads, and it returns fewer than the form stores: measured live, a+// form built and published with Spanish (3082) captions in an English-language (1033) organization keeps both languages, and its published FormXML —+// with or without an Accept-Language for the other language, unpublished or published — carries every label in 1033 alone. Neither does `RetrieveLocLabels` read+// them (a form's `formxml` "does not support localized labels": HTTP 400), nor any other column of the form row. A translation export is the one read that does:+//+// POST {env}/api/data/v9.2/solutions/Microsoft.Dynamics.CRM.ExportTranslation { "SolutionName": "<uniquename>" }+// → 200 { "@odata.context": "…#Microsoft.Dynamics.CRM.ExportTranslationResponse", "ExportTranslationFile": "<base64 of a zip>" }+//+// The action is BOUND to the `solutions` collection: the unbound `POST …/ExportTranslation` answers 404. It exports the PUBLISHED layer (a caption changed in a+// draft and not published is not in it, which is the layer `--verify` checks), for the tables of the solution — Microsoft Learn: even a solution that holds+// one form exports the labels of every form of its table — and Learn documents it for an unmanaged solution, which is what the build makes. It costs ONE request that took 7.5–11.2 s for a solution of+// one table (a 5 KB zip, 44 KB of XML) and grows with the solution, because it exports every label of it.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/exporttranslation+// https://learn.microsoft.com/en-us/power-apps/maker/data-platform/export-customized-entity-field-text-translation+//+// THE ARCHIVE holds `CrmTranslations.xml` and `[Content_Types].xml` (lib/zip-read.js reads it). The first is an Excel 2003 XML spreadsheet+// (https://learn.microsoft.com/en-us/previous-versions/office/developer/office-xp/aa140066(v=office.10)), shortened here to what matters:+//+// <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" …>+// <Worksheet ss:Name="Information">…</Worksheet> the organization, the base language, the solution — read by nobody here+// <Worksheet ss:Name="Display Strings">…</Worksheet>+// <Worksheet ss:Name="Localized Labels"><Table>+// <Row><Cell><Data ss:Type="String">Entity name</Data></Cell><Cell><Data ss:Type="String">Object ID</Data></Cell><Cell><Data ss:Type="String">Object Column Name</Data></Cell>+// <Cell><Data ss:Type="Number">1033</Data></Cell><Cell><Data ss:Type="Number">3082</Data></Cell></Row> ← the header: one column per language+// <Row><Cell><Data ss:Type="String">new_ticket</Data></Cell><Cell><Data ss:Type="String">11111111-2222-3333-4444-555555555555</Data></Cell>+// <Cell><Data ss:Type="String">displayname</Data></Cell><Cell><Data ss:Type="String">Tab One</Data></Cell><Cell><Data ss:Type="String">Pestana Uno</Data></Cell></Row>+// </Table></Worksheet>+// </Workbook>+//+// A tab's or a section's caption is a row of `Localized Labels` whose `Object ID` is the `id` the element has in the form's FormXML — not the form's id, and with no+// label id of its own — and whose `Object Column Name` is `displayname`. An empty cell is `<Data ss:Type="String"></Data>`: the row says the element has NO caption in+// that language. A form's own name is a row with the column `name`, keyed by the form's id; an attribute's, a view's and a field's caption on a form are rows of their+// own (`DisplayName`, `displayname` keyed by the cell's id). Only the rows of the column `displayname` are read, and they are looked up by (table, id).+//+// THE READ IS STRICT, because a pass is decided from it: the document must be one well-formed XML document of the plugin's strict reader (lib/strict-xml.js: no+// document type declaration, no entity but the predefined ones, nothing it would read differently from the SDK's parser), the workbook must be the platform's+// (its namespace, its sheet, its header), and a row, a cell or a type this does not understand makes the WHOLE export unreadable — never a skipped row, because the row+// skipped could be the one that was needed. What `--verify` does with an export it cannot read is leave the captions UNVERIFIED, where they were before it read exports.+//+// THE SHEET IS VALIDATED WHOLE, BEFORE ANYTHING IS READ FROM IT. The strict reader does not resolve namespaces — `ss:Row` is a name to it, not the `Row` of the+// spreadsheet namespace that it means to Excel — so a reader that picked out `Table`, `Row`, `Cell` and `Data` by name would pass over a row written `<ss:Row>`+// (a second, conflicting caption) or a sheet that declares another namespace, and settle a caption from what is left. So every element of `Localized Labels` is+// one of the platform's, by its name as written, in the place the platform puts it, with the attributes it writes — and the one namespace declaration in the sheet+// is the one the platform writes (Excel's, on WorksheetOptions). The platform writes the sheet that way (measured: no prefix on any element, `ss:` on every+// attribute, the `ss` prefix and the default namespace bound once, on the root), and a sheet written any other way is not one this reads. The worksheets are found+// the same way: any element whose name ends in `Worksheet`, with or without a prefix and wherever it is, must be a plain `<Worksheet>` child of the root that declares+// no namespace, and no prefix but `ss` may name the spreadsheet namespace.+//+// THE COST IS BOUNDED BEFORE IT IS PAID. The strict reader gives each element it answers the names of its ancestors, so a document of a few hundred kilobytes that+// nests deep, or under ancestors with long names, would cost gigabytes: such a document is refused while it is read — by its depth, by the length of a name, and by the+// number of elements answered — not after, when the process may already have run out of memory.+const { readXmlElements, XML_PREDEFINED } = require('./strict-xml.js');+const { readZipEntry } = require('./zip-read.js');++const WORKBOOK_ENTRY = 'CrmTranslations.xml';+const LABELS_SHEET = 'Localized Labels';+const CAPTION_COLUMN = 'displayname';+const SPREADSHEET_NAMESPACE = 'urn:schemas-microsoft-com:office:spreadsheet';+const HEADER = ['Entity name', 'Object ID', 'Object Column Name'];+const EXPORT_ACTION = '/solutions/Microsoft.Dynamics.CRM.ExportTranslation';+const EXPORT_PATH = /\/solutions\/Microsoft\.Dynamics\.CRM\.ExportTranslation$/;+// An LCID is at most 65535 (app-spec.js MAX_LCID); a header with more language columns than this is not the platform's.+const MAX_LANGUAGE_COLUMNS = 512;+// What one read may cost. Measured on a made-up workbook of 100,000 caption rows (41 MB of XML): 4.5 s and about 630 MB of memory, because the strict reader holds an+// object for every row, cell and cell text of the sheet. So the workbook is read up to 32 MiB of XML (some 75,000 rows, which no app's solution comes near), and an export+// that is larger is left unread — its captions stay unverified, with that said — rather than risk the memory of the process that is running the build.+const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024;+const MAX_WORKBOOK_BYTES = 32 * 1024 * 1024;+// Cell attributes of a spreadsheet that make a cell something other than its own text.+const UNSUPPORTED_CELL_ATTRIBUTES = ['ss:MergeAcross', 'ss:MergeDown', 'ss:ArrayRange', 'ss:Formula'];+const GUID = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;+const EXCEL_NAMESPACE = 'urn:schemas-microsoft-com:office:excel';++// The shape of the `Localized Labels` sheet, as the platform writes it (measured on every export the lane captured): for each element, where it is (the names of its+// ancestors in the sheet) and the attributes it may have. `ss:Index` on a cell is the spreadsheet's own way to leave cells out (forward only, see cellsOf); the+// merge and formula attributes are named so that a cell that has one is refused for that, with its name. Nothing else is in the sheet, and nothing else is read.+const SHEET_SHAPE = new Map([+ ['Worksheet', { at: '', attributes: ['ss:Name', 'ss:Id', 'ss:Protected'] }],+ ['Table', { at: 'Worksheet', attributes: [] }],+ ['Column', { at: 'Worksheet/Table', attributes: ['ss:AutoFitWidth', 'ss:Width', 'ss:Span'] }],+ ['Row', { at: 'Worksheet/Table', attributes: ['ss:AutoFitHeight'] }],+ ['Cell', { at: 'Worksheet/Table/Row', attributes: ['ss:StyleID', 'ss:Index', ...UNSUPPORTED_CELL_ATTRIBUTES] }],+ ['Data', { at: 'Worksheet/Table/Row/Cell', attributes: ['ss:Type'] }],+ // The sheet's options, in Excel's namespace (declared on the element itself): flags, none of them read, each with no attribute and at most a word of text.+ ['WorksheetOptions', { at: 'Worksheet', attributes: ['xmlns'] }],+ ...['Unsynced', 'Selected', 'ProtectObjects', 'ProtectScenarios', 'AllowFormatCells', 'AllowSizeCols', 'AllowSizeRows', 'AllowInsertCols', 'AllowInsertRows', 'AllowDeleteCols',+ 'AllowDeleteRows', 'AllowSort', 'AllowFilter', 'AllowUsePivotTables'].map((name) => [name, { at: 'Worksheet/WorksheetOptions', attributes: [] }]),+].map(([name, shape]) => [name, { ...shape, attributes: new Set(shape.attributes) }]));+// The elements of the sheet that hold elements and white space only: text, a comment or a CDATA section directly inside one is not something this reads past.+const HOLDS_ELEMENTS_ONLY = new Set(['Worksheet', 'Table', 'Column', 'Row', 'Cell', 'WorksheetOptions']);+// The attributes a worksheet element may have, in the whole workbook: what the platform writes on its three sheets. Its name is `ss:Name`, and no other attribute+// can give it one.+const WORKSHEET_ATTRIBUTES = SHEET_SHAPE.get('Worksheet').attributes;++// Bounds of the read, each checked WHILE the strict reader reads, so that a hostile workbook costs no more than they allow (see the header). The platform's workbook+// nests 6 deep (Workbook/Worksheet/Table/Row/Cell/Data), and its sheet 5 (the same, from the Worksheet) — the sheet's bound is one more, so that an element inside a+// cell's Data is refused as the markup in a cell it is; its longest element name is 19 characters; it has 3 worksheets; and a sheet at the byte limit holds about+// 1.1 million elements (a row of five short cells is some 330 bytes and 11 elements). Measured: a sheet of 1.6 million empty rows (9 MB) is refused at the element+// budget after 2 s and 530 MB of heap — about what a legitimate 29 MB workbook of 70,000 rows costs to read (410 MB) — where 32 MB of such rows would take some 2 GB.+const MAX_WORKBOOK_DEPTH = 16;+const MAX_SHEET_DEPTH = 6;+const MAX_NAME_LENGTH = 64;+const MAX_WORKSHEETS = 64;+const MAX_SHEET_ELEMENTS = 1500000;++class Unreadable extends Error {}+const refuse = (message) => { throw new Unreadable(message); };++// A GUID as FormXML and the export both write them — with or without braces, in either case — as the one form the lookup is made by; null for anything else.+function guidOf(value) {+ if (typeof value !== 'string') return null;+ const bare = value.trim().replace(/^\{(.*)\}$/, '$1').toLowerCase();+ return GUID.test(bare) ? bare : null;+}+const keyOf = (entity, id) => (typeof entity === 'string' && entity !== '' && id ? `${entity.toLowerCase()}|${id}` : undefined);++// The text of a <Data> element — `<Data ss:Type="String">Tab One</Data>`, or `<Data ss:Type="String"/>` — whose place in `sheet` the strict reader gave (`spans`).+// The strict reader has checked every reference in it is a predefined entity or a character reference to a character XML allows, so they are decoded here and nothing+// else is: markup in a cell (a child element, a CDATA section, a comment) is not text this reads. Line ends are read as an XML parser reads them (a CR LF and a lone CR+// are a line feed, and ` ` stays a carriage return), so a caption compares as the SDK's own FormXML parser gives it.+function dataText(sheet, data) {+ const type = data.attrs['ss:Type'];+ if (type === undefined) refuse('a Data element has no ss:Type');+ if (type !== 'String' && type !== 'Number') refuse(`a cell has the type '${type}', and only String and Number cells are read`);+ const whole = sheet.slice(data.start, data.end);+ let quote = '';+ let close = -1;+ for (let i = 1; i < whole.length; i += 1) {+ const c = whole[i];+ if (quote) {+ if (c === quote) quote = '';+ } else if (c === '"' || c === '\'') {+ quote = c;+ } else if (c === '>') {+ close = i;+ break;+ }+ }+ if (close < 0) refuse('a Data element is not closed');+ if (whole[close - 1] === '/') return '';+ const inner = whole.slice(close + 1, whole.lastIndexOf('</'));+ if (inner.includes('<')) refuse('there is markup inside a cell');+ return inner.replace(/\r\n?/g, '\n').replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|(lt|gt|amp|quot|apos));/g, (ref, hex, dec, name) => (name+ ? XML_PREDEFINED[name]+ : String.fromCodePoint(parseInt(hex !== undefined ? hex : dec, hex !== undefined ? 16 : 10))));+}++// The cells of a row, by column: `{ text, type }`, the type of the cell's Data (`String` or `Number`) or null for a cell with none. A cell may say where it is+// (`ss:Index`, 1-based, forward only) and leave the ones before it out; a cell left out, or with no Data, is empty. A column past `limit` is a row with more cells than+// the header, which is refused; so is a cell that is merged or holds a formula.+function cellsOf(sheet, row, number, limit) {+ const cells = [];+ let column = 0;+ for (const cell of row.cells) {+ for (const name of UNSUPPORTED_CELL_ATTRIBUTES) if (cell.attrs[name] !== undefined) refuse(`row ${number} has a cell that is merged or holds a formula (${name})`);+ const index = cell.attrs['ss:Index'];+ if (index !== undefined) {+ if (!/^[1-9][0-9]{0,5}$/.test(index)) refuse(`row ${number} has an ss:Index that is not a column number ('${index}')`);+ if (Number(index) - 1 < column) refuse(`row ${number} has an ss:Index that goes back to a column the row has used already`);+ column = Number(index) - 1;+ }+ if (column >= limit) refuse(`row ${number} has more cells than the header names columns`);+ cells[column] = cell.data ? { text: dataText(sheet, cell.data), type: cell.data.attrs['ss:Type'] } : { text: '', type: null };+ column += 1;+ }+ return Array.from(cells, (cell) => cell || { text: '', type: null });+}++// The rows of the sheet, each with its cells and their Data elements, from EVERY element of the sheet, in document order (the strict reader has answered them all,+// and refused any name SHEET_SHAPE does not have) — once each one is found where the platform puts it, with only the attributes the platform writes on it, in the+// platform's order: one Table, its Columns before its Rows, then at most one WorksheetOptions, in Excel's namespace. An element is only ever the child of the last one+// opened at the place its path names, so a Cell belongs to the last Row and a Data to the last Cell.+function rowsOf(elements) {+ const rows = [];+ let row = null;+ let cell = null;+ let tables = 0;+ let options = 0;+ for (const element of elements) {+ const shape = SHEET_SHAPE.get(element.name);+ if (element.path !== shape.at) refuse(`a ${element.name} is not where the spreadsheet puts one (found in ${element.path || 'the root'})`);+ for (const attribute of Object.keys(element.attrs)) {+ if (!shape.attributes.has(attribute)) refuse(`a ${element.name} has the attribute ${attribute}, which the platform's sheet does not have`);+ }+ if (element.name === 'Table') {+ tables += 1;+ if (tables > 1) refuse('the worksheet has more than one Table');+ } else if (element.name === 'WorksheetOptions') {+ options += 1;+ if (options > 1 || tables === 0) refuse('the worksheet\'s WorksheetOptions are not one element after its Table');+ if (element.attrs.xmlns !== EXCEL_NAMESPACE) refuse(`the worksheet's WorksheetOptions are not in Excel's namespace (${EXCEL_NAMESPACE})`);+ } else if (element.name === 'Column') {+ if (rows.length > 0) refuse('a Column comes after a Row (a table\'s columns come before its rows)');+ } else if (element.name === 'Row') {+ row = { cells: [] };+ rows.push(row);+ cell = null;+ } else if (element.name === 'Cell') {+ cell = { attrs: element.attrs, data: null };+ row.cells.push(cell);+ } else if (element.name === 'Data') {+ if (cell.data) refuse('a cell has more than one Data element');+ cell.data = element;+ }+ }+ if (tables === 0) refuse('the worksheet has no Table');+ return rows;+}++// The language columns of the header row: the three fixed names, then one LCID for each language the environment has provisioned.+function languagesOf(cells) {+ if (cells.length < HEADER.length || HEADER.some((name, i) => cells[i] !== name)) refuse(`the header of '${LABELS_SHEET}' is not ${HEADER.join(', ')} and a column for each language`);+ const languages = [];+ for (const text of cells.slice(HEADER.length)) {+ const lcid = /^[1-9][0-9]{0,4}$/.test(text) ? Number(text) : 0;+ if (lcid < 1 || lcid > 65535) refuse(`the header of '${LABELS_SHEET}' names a language that is not an LCID ('${text}')`);+ if (languages.includes(lcid)) refuse(`the header of '${LABELS_SHEET}' names language ${lcid} twice`);+ languages.push(lcid);+ }+ if (languages.length === 0) refuse(`the header of '${LABELS_SHEET}' names no language`);+ return languages;+}++/**+ * Reads the text of a CrmTranslations.xml and answers where the caption of a tab or a section is, by the table and the id the element has in its form's FormXML.+ *+ * parseTranslationWorkbook(xml)+ * → { ok: true, languages: [1033, 3082], lookup(entity, id) }+ * → { ok: false, detail } the workbook is not one this reads with certainty — nothing is answered from it+ *+ * `lookup` answers `{ found: false }` (no caption row for that table and id), `{ found: true, ambiguous: true }` (more than one: the export cannot say which is the+ * form's) or `{ found: true, ambiguous: false, texts: Map<lcid, text> }`, a text for every language column, `''` where the cell is empty.+ *+ * @param {string} xml+ */+function parseTranslationWorkbook(xml) {+ try {+ // The whole document, for its root and its worksheets: every element whose name ends in `Worksheet`, prefixed or not and wherever it is, is answered, so that+ // a sheet the spreadsheet would see is never one this passes over. While it reads, no element name may be long and no element deep (see the header): only these+ // few elements are kept, but each carries the names of its ancestors.+ let workbooks = 0;+ let worksheets = 0;+ const workbookPart = (name) => {+ if (name.length > MAX_NAME_LENGTH) refuse(`it has an element whose name is longer than ${MAX_NAME_LENGTH} characters`);+ if (name === 'Workbook') {+ workbooks += 1;+ if (workbooks > 1) refuse('it has more than one Workbook element');+ return true;+ }+ if (name !== 'Worksheet' && !name.endsWith(':Worksheet')) return false;+ worksheets += 1;+ if (worksheets > MAX_WORKSHEETS) refuse(`it has more than ${MAX_WORKSHEETS} worksheets`);+ return true;+ };+ const whole = readXmlElements(xml, workbookPart, { spans: true, maxDepth: MAX_WORKBOOK_DEPTH });+ if (!whole.ok) refuse(`it is not one XML document the plugin reads (${whole.detail})`);+ const roots = whole.elements.filter((e) => e.name === 'Workbook');+ if (roots.length !== 1 || roots[0].path !== '' || roots[0].attrs.xmlns !== SPREADSHEET_NAMESPACE || roots[0].attrs['xmlns:ss'] !== SPREADSHEET_NAMESPACE) {+ refuse(`it is not a spreadsheet workbook of the namespace the platform writes (${SPREADSHEET_NAMESPACE}, with ss: for it)`);+ }+ // A second prefix for the spreadsheet namespace would make `x:Name` a sheet's name and `x:Row` a row as much as `ss:Name` and `Row` are.+ for (const [attribute, value] of Object.entries(roots[0].attrs)) {+ if (attribute.startsWith('xmlns:') && attribute !== 'xmlns:ss' && value === SPREADSHEET_NAMESPACE) refuse(`it names the spreadsheet namespace with a prefix other than ss: (${attribute})`);+ }+ const sheets = whole.elements.filter((e) => e.name !== 'Workbook');+ for (const sheet of sheets) {+ // A worksheet that declares a namespace, or is written with a prefix, is either not a spreadsheet's worksheet at all or one under another name: never read.+ if (sheet.name !== 'Worksheet' || sheet.path !== 'Workbook') refuse(`it has a worksheet that is not where the spreadsheet puts one (<${sheet.name}> in ${sheet.path || 'the root'})`);+ for (const attribute of Object.keys(sheet.attrs)) {+ if (!WORKSHEET_ATTRIBUTES.has(attribute)) refuse(`it has a worksheet with the attribute ${attribute}, which the platform's worksheets do not have`);+ }+ if (sheet.attrs['ss:Name'] === undefined) refuse('it has a worksheet with no ss:Name');+ }+ const labelSheets = sheets.filter((e) => e.attrs['ss:Name'] === LABELS_SHEET);+ if (labelSheets.length === 0) refuse(`it has no worksheet named '${LABELS_SHEET}'`);+ // Excel tells sheet names apart without regard to case: a sheet named this one in other letters is the same sheet to it.+ if (sheets.filter((e) => e.attrs['ss:Name'].toLowerCase() === LABELS_SHEET.toLowerCase()).length > 1) refuse(`it has more than one worksheet named '${LABELS_SHEET}'`);++ // The sheet is read on its own, from the text of its element: the strict reader answers elements of the whole document, and this keeps the elements of the other+ // sheets (which can be far larger) out of memory. A fragment that is one well-formed element reads like a document. EVERY element of it is answered, and any+ // name the platform's sheet does not have ends the read at once: it is not skipped, and nothing under it is kept.+ let answered = 0;+ const sheetPart = (name) => {+ if (!SHEET_SHAPE.has(name)) {+ refuse(`the worksheet '${LABELS_SHEET}' has an element <${name.slice(0, MAX_NAME_LENGTH)}>, which the platform's sheet does not have (markup inside a cell, or an element of another kind or namespace)`);+ }+ answered += 1;+ if (answered > MAX_SHEET_ELEMENTS) refuse(`the worksheet '${LABELS_SHEET}' has more than ${MAX_SHEET_ELEMENTS} elements`);+ return true;+ };+ const sheet = xml.slice(labelSheets[0].start, labelSheets[0].end);+ const parts = readXmlElements(sheet, sheetPart, { spans: true, maxDepth: MAX_SHEET_DEPTH, elementOnly: (name) => HOLDS_ELEMENTS_ONLY.has(name) });+ if (!parts.ok) refuse(`the worksheet '${LABELS_SHEET}' is not read (${parts.detail})`);+ const rows = rowsOf(parts.elements);+ if (rows.length === 0) refuse(`the worksheet '${LABELS_SHEET}' has no header row`);+ const header = cellsOf(sheet, rows[0], 1, MAX_LANGUAGE_COLUMNS + HEADER.length);+ // The header's names are text; a language is an LCID, which the platform writes as a Number (and which reads the same as text).+ header.forEach((cell, column) => {+ if (cell.type === 'Number' && column < HEADER.length) refuse(`the header of '${LABELS_SHEET}' has a Number where it names a column (${HEADER[column]})`);+ });+ const languages = languagesOf(header.map((cell) => cell.text));++ const captions = new Map();+ const ambiguous = new Set();+ for (let i = 1; i < rows.length; i += 1) {+ const number = i + 1;+ const row = cellsOf(sheet, rows[i], number, HEADER.length + languages.length);+ // A caption is text: a Number cell would be read by its digits as written ("1.50", "1E3"), which is not what a form shows, and the platform writes none.+ if (row.some((cell) => cell.type === 'Number')) refuse(`row ${number} has a Number cell, and the cells of a row are text (String)`);+ const cells = row.map((cell) => cell.text);+ if (cells.length === 0) continue;+ if (cells.length < HEADER.length) refuse(`row ${number} has fewer than the three cells (${HEADER.join(', ')}) that say what a row is about`);+ if (cells[2] !== CAPTION_COLUMN) continue;+ // A row whose Object ID is no GUID cannot be the caption of an element that has one.+ const key = keyOf(cells[0], guidOf(cells[1]));+ if (key === undefined) continue;+ if (captions.has(key)) {+ ambiguous.add(key);+ continue;+ }+ captions.set(key, new Map(languages.map((lcid, column) => [lcid, cells[HEADER.length + column] || ''])));+ }+ const lookup = (entity, id) => {+ const key = keyOf(entity, guidOf(id));+ if (key === undefined) return { found: false };+ if (ambiguous.has(key)) return { found: true, ambiguous: true };+ const texts = captions.get(key);+ return texts ? { found: true, ambiguous: false, texts } : { found: false };+ };+ return { ok: true, languages, lookup };+ } catch (err) {+ if (err instanceof Unreadable) return { ok: false, detail: err.message };+ throw err;+ }+}++/**+ * Whether one caption — `text`, in `lcid`, of the tab or section `id` of a form of `entity` — is what the export holds.+ *+ * { state: 'same' } the export has this text+ * { state: 'different', have, others: [{ lcid, text }] } it has `have` (an empty string: no caption in that language), and these in other languages+ * { state: 'unsettled', why } the export cannot say: no such column, no id to look up, no row, or more than one+ *+ * `what` names the element in a reason ("tab 'tab_main'").+ * @param {{ languages: number[], lookup: Function }} exported what `readTranslationLabels` answered+ */+function settleCaption(exported, { entity, id, lcid, text, what = 'the tab or section' }) {+ if (!exported.languages.includes(lcid)) return { state: 'unsettled', why: `the export has no column for language ${lcid}` };+ if (guidOf(id) === null) return { state: 'unsettled', why: 'the form\'s FormXML gives a tab or section no id to look it up by' };+ const hit = exported.lookup(entity, id);+ const named = `${what} (id ${guidOf(id)}, table ${entity})`;+ if (!hit.found) return { state: 'unsettled', why: `the export has no caption row for ${named}` };+ if (hit.ambiguous) return { state: 'unsettled', why: `the export has more than one caption row for ${named}` };+ const have = hit.texts.get(lcid);+ if (have === text) return { state: 'same' };+ return { state: 'different', have, others: [...hit.texts].filter(([other, otherText]) => other !== lcid && otherText !== '').map(([other, otherText]) => ({ lcid: other, text: otherText })) };+}++// A message is what an error says, and only its first 300 characters: a platform answer can be a page of text.+const said = (err) => String((err && err.message) || err).slice(0, 300);++/**+ * Asks the platform for the translation export of a solution and reads the workbook out of it. Never throws: whatever goes wrong — no client, a request that fails, an+ * answer that is an error or not an export, an archive or a workbook that is not read with certainty — is `{ ok: false, reason }`, which `--verify` reports as the reason+ * a caption stays unverified.+ *+ * readTranslationLabels(sdk.dataverse, 'Contoso_Tickets') → { ok: true, languages, lookup } | { ok: false, reason }+ *+ * @param {{ post: Function }} client the SDK's Dataverse client: `post(path, body)` resolves `{ status, headers, body }` and does not throw on a non-2xx+ * @param {string} solutionUniqueName+ */+async function readTranslationLabels(client, solutionUniqueName) {+ try {+ const name = typeof solutionUniqueName === 'string' ? solutionUniqueName.trim() : '';+ if (!name) return { ok: false, reason: 'there is no solution name to export the translations of' };+ if (!client || typeof client.post !== 'function') return { ok: false, reason: 'the SDK has no Dataverse client that can post a translation export request' };+ let answer;+ try {+ answer = await client.post(EXPORT_ACTION, { SolutionName: name });+ } catch (err) {+ return { ok: false, reason: `the request failed: ${said(err)}` };+ }+ if (!answer || typeof answer !== 'object') return { ok: false, reason: 'the platform gave no answer' };+ if (!(answer.status >= 200 && answer.status < 300)) {+ const message = answer.body && answer.body.error && answer.body.error.message;+ return { ok: false, reason: `HTTP ${answer.status}${typeof message === 'string' && message ? `: ${message.slice(0, 300)}` : ''}` };+ }+ const file = answer.body && answer.body.ExportTranslationFile;+ if (typeof file !== 'string' || file === '') return { ok: false, reason: 'the answer holds no ExportTranslationFile' };+ if (file.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(file)) return { ok: false, reason: 'ExportTranslationFile is not base64' };+ let bytes;+ try {+ bytes = readZipEntry(Buffer.from(file, 'base64'), WORKBOOK_ENTRY, { maxArchiveBytes: MAX_ARCHIVE_BYTES, maxEntryBytes: MAX_WORKBOOK_BYTES });+ } catch (err) {+ return { ok: false, reason: `the archive of the export is not readable: ${said(err)}` };+ }+ let xml;+ try {+ xml = new TextDecoder('utf-8', { fatal: true }).decode(bytes);+ } catch {+ return { ok: false, reason: 'the workbook of the export is not valid UTF-8' };+ }+ // The bytes were read as UTF-8, so a document that says it is in another encoding is not the one that was read.+ const declared = /^\s*<\?xml\b[^?]*?\bencoding\s*=\s*["']([^"']+)["']/i.exec(xml.slice(0, 300));+ if (declared && !/^utf-8$/i.test(declared[1])) return { ok: false, reason: `the workbook of the export declares the encoding ${declared[1]}, and only UTF-8 is read` };+ const workbook = parseTranslationWorkbook(xml);+ if (!workbook.ok) return { ok: false, reason: `the workbook of the export is not readable: ${workbook.detail}` };+ return { ok: true, languages: workbook.languages, lookup: workbook.lookup };+ } catch (err) {+ return { ok: false, reason: `the export could not be read: ${said(err)}` };+ }+}++/**+ * Whether a request is the ExportTranslation of a solution — `sendOnce` for the plugin's HTTP client (lib/sdk-http-client.js), which otherwise sends a request again on a+ * throttled or unavailable answer and on a timeout. That is right for most requests and wrong for this one: it is a long action (the export of a large solution outlives the+ * client's five-minute wait, and a re-send then starts a SECOND export of the same solution beside the first, which is still running), and the answer to a failure is+ * `--verify` leaving the captions unverified, which costs nothing to repeat by running it again.+ */+function isTranslationExport(method, url) {+ if (String(method).toUpperCase() !== 'POST' || typeof url !== 'string') return false;+ try {+ return EXPORT_PATH.test(new URL(url).pathname);+ } catch {+ return false;+ }+}++module.exports = { parseTranslationWorkbook, readTranslationLabels, settleCaption, isTranslationExport, WORKBOOK_ENTRY, LABELS_SHEET, CAPTION_COLUMN };diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex 4b5c7a9e8..6a9931825 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -13,7 +13,7 @@ const { sitemapEntityTables } = require('./app-spec.js');// liveNavEntries in sitemap-pages.js so the form-identity scan and the navigation reader cannot drift.const { decodeXmlEntities, liveNavEntries, XML_TAG, XML_ATTR } = require('./sitemap-pages.js');const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS, generatedTabName, generatedSectionName, formColumnsOf, formLayoutNames, subgridRelationshipName, normalizeLanguageCode, isLocalizedLabelMap } = require('./app-spec.js');-const { sameRelationship, describeRelationship } = require('./relationship-metadata.js');+const { sameRelationship, compareRelationship, describeRelationship, describeIncomplete } = require('./relationship-metadata.js');const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef, dashboardsInSolution, findDashboardsByName, findPinnedDashboard } = require('./sdk-build.js');const { DASHBOARD_LAUNCHER_URL, isDashboardLauncherUrl, subAreaTargetKey, specSubAreaTargetKey, specSubAreas, chromeByTargetKey, keepsLiveValue } = require('./sitemap-merge.js');// Recorded on an icon check the build's keep rule satisfies (keepsLiveValue, sitemap-merge.js).@@ -24,6 +24,7 @@ const { declaredPrivileges, compareRolePrivileges } = require('./role-privilegesconst { resolveSurfaces } = require('./surface-resolver.js');const { selectSummaryTables } = require('./ai-candidates.js');const { isVisualizationUnsupported, mapLimit, resolveLanguageCode } = require('./entity-provision.js');+const { settleCaption } = require('./translation-labels.js');const { sectionGridWidth, mergeFieldOptions, fieldOptionsMap, normalizeFieldEntry, compileFormIntent, isNonFieldControl, formFieldLogicals, declaredSectionByField } = require('./artifact-intent.js');// The fields an explicit layout prunes, as the destructive gate and the build's prune pass both name them.const { formRemovals } = require('./op-diff.js');@@ -659,9 +660,14 @@ async function verifySpec(spec, read, opts = {}) {add('relationship', schema, true);continue;}+ // A relationship is verified only when the answer states its whole identity (compareRelationship). One that leaves a part out+ // is neither verified nor shown to be another relationship, so the check FAILS and says what the answer lacked. It is not listed+ // `unverified`: that list leaves `ok` and the exit status as they were, and a relationship nobody identified must not read as a pass.+ const unproven = (verdict) => `exists, but ${describeIncomplete(verdict.missing)}, so verify cannot prove it is the declared ${describeRelationship(declared)}`;const nameHit = detailed.find(named);if (nameHit) {- add('relationship', schema, false, `exists as ${describeRelationship(nameHit)}`);+ const verdict = compareRelationship(declared, nameHit);+ add('relationship', schema, false, verdict.state === 'incomplete' ? unproven(verdict) : `exists as ${describeRelationship(nameHit)}`);continue;}// The typed collection on this side cannot see a holder of the other type (a 1:N is not in@@ -676,7 +682,9 @@ async function verifySpec(spec, read, opts = {}) {continue;}if (holder && holder.found === true) {- if (sameRelationship(declared, holder.holder)) { add('relationship', schema, true); continue; }+ const verdict = compareRelationship(declared, holder.holder);+ if (verdict.state === 'same') { add('relationship', schema, true); continue; }+ if (verdict.state === 'incomplete') { add('relationship', schema, false, unproven(verdict)); continue; }const declaredKind = r.type === 'ManyToMany' ? 'N:N' : '1:N';add('relationship', schema, false, `${schema} exists as ${describeRelationship(holder.holder)}, not as the declared ${declaredKind}`);continue;@@ -723,7 +731,7 @@ async function verifySpec(spec, read, opts = {}) {// Read once per pass, and only when a form authors a string label.//// A language that is known is not always one the form's READ can show (labelProblem says why): a label compared in a language no label of the- // form is in is listed `unverified` too, whichever way the language was learnt.+ // form is in is listed `unverified` too, whichever way the language was learnt — unless the translation export of the app's solution (below) can settle it.let authoringLanguageP;const authoringLanguage = () => authoringLanguageP || (authoringLanguageP = (async () => {let fromOrganization = false;@@ -736,6 +744,25 @@ async function verifySpec(spec, read, opts = {}) {});return lcid ? { lcid, fromOrganization } : { reason };})());+ // The translation export of the app's solution: the one read that carries a tab's and a section's caption in EVERY provisioned language, where the form's own read carries the+ // languages the platform chooses to show (labelProblem). It is a request that takes seconds (7.5–11.2 s measured, for a solution of one table, and more as the solution grows),+ // so it is made only when some caption needs it — the settling step of the form loop, below, is the one place that asks — and once for the whole pass: every form's task awaits the same+ // promise. `reason` is why there is no export; a reader that cannot ask for one (`translationLabels` is optional, like the other reads) is treated as no export at all, with no reason+ // to give, so the captions are listed exactly as they were before an export was read.+ const solutionName = spec.solution && spec.solution.uniqueName;+ const canReadTranslations = typeof read.translationLabels === 'function' && typeof solutionName === 'string' && solutionName !== '';+ const translations = once(async () => {+ let answer;+ try {+ answer = await read.translationLabels(solutionName);+ } catch (e) {+ return { ok: false, reason: (e && e.message) || String(e) };+ }+ if (!answer || typeof answer !== 'object') return { ok: false, reason: 'the reader gave no answer' };+ if (answer.ok === false) return { ok: false, reason: typeof answer.reason === 'string' && answer.reason !== '' ? answer.reason : 'no reason was given' };+ if (answer.ok !== true || !Array.isArray(answer.languages) || typeof answer.lookup !== 'function') return { ok: false, reason: 'the reader\'s answer is not an export' };+ return answer;+ });{plan.each(spec.forms || [], async ({ add, unverified }, forms) => {for (const f of forms) {@@ -862,7 +889,9 @@ async function verifySpec(spec, read, opts = {}) {// that some label does carry is compared exactly as above, strictly — a stale caption in it fails. `carriedLanguages` is empty only for a form// that publishes no label at all, which names no language to be missing from: what such a form lacks is a caption, and is a mismatch as ever// (the read measured live carried every label of the form, in the base language).- // Translations are not read another way (a translation export, RetrieveLocLabels): what a caller's FormXML does not carry is not verified.+ // RetrieveLocLabels cannot read them either (a form's `formxml` "does not support localized labels": HTTP 400). A translation export can — it carries every provisioned+ // language, the published layer, one row per tab or section keyed by the id the element has in the FormXML — so the captions a read cannot show are looked up there+ // (the settling step below, which asks for the export once per pass and only when there is such a caption), and only the ones the export cannot settle stay `unverified`.const unverifiedLabels = [];const unshownLabels = new Map();let comparedInOrganizationLanguage;@@ -872,12 +901,11 @@ async function verifySpec(spec, read, opts = {}) {const have = (container && container.labels) || [];for (const [lcid, text] of declaredLabels(authored, known)) {if (carriedLanguages.length && !carriedLanguages.includes(lcid)) {- if (!unshownLabels.has(lcid)) unshownLabels.set(lcid, { whats: [], string: false });- const held = unshownLabels.get(lcid);- held.whats.push(what);- // A string label is compared in the language verify is told, so a read that carries others is something a maker can act on by telling it- // one of them; a map names its languages itself, and there is nothing to tell.- if (typeof authored === 'string') held.string = true;+ if (!unshownLabels.has(lcid)) unshownLabels.set(lcid, { items: [] });+ // Each caption is kept with the id of the deployed tab or section it was compared against and the text the spec declares: all a translation export needs to settle it.+ // A string label is compared in the language verify is told, so a read that carries others is something a maker can act on by telling it one of them;+ // a map names its languages itself, and there is nothing to tell.+ unshownLabels.get(lcid).items.push({ what, id: container && container.id, text, string: typeof authored === 'string' });continue;}if (have.some((l) => l.lcid === lcid && l.text === text)) continue;@@ -1144,6 +1172,38 @@ async function verifySpec(spec, read, opts = {}) {});orderProblem(tabOrder, 'the tabs');+ // The captions the form's read cannot show (`unshownLabels`) are looked up in the translation export of the app's solution — by the id of the tab or section each was compared+ // against, in the language the spec declares it in — and judged like any other: the same text is right, and anything else is a mismatch (an empty cell is a caption that is not+ // there). What the export cannot say stays in `unshownLabels`, with the reason, to be listed `unverified` as it was before an export was read; `held.note` is what the entry+ // says of the export then — that it could not be read, or what it could not settle. A mismatch is a problem of THIS form, so this runs before its check is reported.+ if (unshownLabels.size && canReadTranslations) {+ const exported = await translations();+ for (const [lcid, held] of unshownLabels) {+ const whys = [];+ held.items = held.items.filter((item) => {+ if (!exported.ok) return true;+ const settled = settleCaption(exported, { entity, id: item.id, lcid, text: item.text, what: item.what });+ if (settled.state === 'same') return false;+ if (settled.state === 'unsettled') {+ if (!whys.includes(settled.why)) whys.push(settled.why);+ return true;+ }+ const declared = `the spec declares label: ${JSON.stringify(item.text)} in language ${lcid}`;+ const others = settled.others.map((other) => `${JSON.stringify(other.text)} in ${other.lcid}`).join(', ');+ const source = `the translation export of solution '${solutionName}'`;+ const absent = `the form read does not carry language ${lcid}`;+ problems.push(settled.have === ''+ ? `${item.what} is deployed with no label in language ${lcid} (${source} has none${others ? `, only ${others}` : ''}; ${absent}), ${declared}`+ : `${item.what} is deployed with label ${JSON.stringify(settled.have)} in language ${lcid} (${source} shows it; ${absent}), ${declared}`);+ // A string label held to the language the organization has is held to a guess when the build was run in another: the detail below says what to give verify.+ if (item.string && labelLanguage && labelLanguage.fromOrganization) comparedInOrganizationLanguage = lcid;+ return false;+ });+ if (held.items.length === 0) unshownLabels.delete(lcid);+ else held.note = exported.ok ? { whys } : { failed: exported.reason };+ }+ }+add('form-topology', `${entity}.${name}`, problems.length === 0,problems.length ? `deployed layout does not match the authored one — ${problems.slice(0, 6).join('; ')}${problems.length > 6 ? `; +${problems.length - 6} more` : ''}${comparedInOrganizationLanguage === undefined ? '' : ` — the labels were compared in the organization's base language (${comparedInOrganizationLanguage}), because verify was told no other: if the build was run with --language-code, give verify the same flag (or pin "languageCode" in the spec)`}` : '');@@ -1157,13 +1217,20 @@ async function verifySpec(spec, read, opts = {}) {// label's language is the one verify was told, so the maker may also tell it another the read carries — and where it was not told but inferred from// the organization, the flag that gives it the build's own is what most likely settles it.for (const [lcid, held] of unshownLabels) {- const n = held.whats.length;- const inferred = held.string && labelLanguage && labelLanguage.fromOrganization+ const whats = held.items.map((item) => item.what);+ const n = whats.length;+ const string = held.items.some((item) => item.string);+ const inferred = string && labelLanguage && labelLanguage.fromOrganization? ` (verify used the organization's base language, because it was told no other: if the build was run with --language-code, give verify the same flag, or pin "languageCode" in the spec)`: '';- unverified.push(`form-labels:${entity}.${name} (${n === 1 ? 'the label' : 'the labels'} of ${held.whats.slice(0, 6).join(', ')}${n > 6 ? `, +${n - 6} more` : ''} in language ${lcid} ${n === 1 ? 'was' : 'were'} not compared: `+ // What the translation export, asked for these captions, could not do about them: be read at all, or settle them.+ const exportNote = !held.note ? '' : held.note.failed !== undefined+ ? `A translation export of solution '${solutionName}' could not be read (${held.note.failed}). `+ : `A translation export of solution '${solutionName}' was read, but it cannot settle ${n === 1 ? 'it' : 'them'}: ${held.note.whys.join('; ')}. `;+ unverified.push(`form-labels:${entity}.${name} (${n === 1 ? 'the label' : 'the labels'} of ${whats.slice(0, 6).join(', ')}${n > 6 ? `, +${n - 6} more` : ''} in language ${lcid} ${n === 1 ? 'was' : 'were'} not compared: `+ `the environment's form read returns labels only in ${carriedLanguages.join(', ')}, so labels written in ${lcid} cannot be read back from it. `- + `Check ${n === 1 ? 'it' : 'them'} in Power Apps with that language${held.string ? `, or verify in a language the read carries${inferred}` : ''})`);+ + exportNote+ + `Check ${n === 1 ? 'it' : 'them'} in Power Apps with that language${string ? `, or verify in a language the read carries${inferred}` : ''})`);}placedGridChecks({tab: (i) => matchedTabs[i],@@ -2590,7 +2657,8 @@ function authorsStringLabel(f) {// a section's is, and the build flags it (artifact-intent.js findFieldOuterCells), so verify must see it.// `languages` is every language a label of the form is in — a tab's, a section's, a field's, a header cell's alike — as the LCIDs the labels name,// ascending: `<label description="Overview" languagecode="1033" />` adds 1033, and a label that names no language adds none. It is what the READ-// carries of the form (see labelProblem, which is where it matters).+// carries of the form (see labelProblem, which is where it matters). A tab and a section also carry their `id`, when the FormXML gives them one: the key a translation+// export has their captions by.//// Written as a depth scanner rather than nested non-greedy regexes: tabs contain columns contain// sections contain rows contain cells, and a non-greedy `<section>[\s\S]*?</section>` stops at the@@ -2619,6 +2687,9 @@ function parseFormTopology(xml) {const v = String(attr(raw, name) === undefined ? '' : attr(raw, name)).trim().toLowerCase();return v === 'true' || v === '1' ? true : (v === 'false' || v === '0' ? false : undefined);};+ // The `id` of a tab or a section as the FormXML writes it (`<tab id="0a0a0a0a-…" name="tab_one" …>`), kept only when the element has one. It is what a translation+ // export keys the element's captions by (lib/translation-labels.js), so the captions a read of this form cannot show can be found there.+ const idOf = (raw) => { const id = attr(raw, 'id'); return id === undefined ? {} : { id }; };let m;while ((m = re.exec(s)) !== null) {const closing = m[1] === '/';@@ -2635,14 +2706,14 @@ function parseFormTopology(xml) {continue;}if (isPart(tag)) { part = selfClosing ? null : tag; continue; }- if (tag === 'tab') { tab = { name: attr(raw, 'name'), label: undefined, expanded: flag(raw, 'expanded'), visible: flag(raw, 'visible'), columns: [] }; tabs.push(tab); if (selfClosing) tab = null; }+ if (tag === 'tab') { tab = { name: attr(raw, 'name'), ...idOf(raw), label: undefined, expanded: flag(raw, 'expanded'), visible: flag(raw, 'visible'), columns: [] }; tabs.push(tab); if (selfClosing) tab = null; }else if (tag === 'column' && tab) { column = { width: attr(raw, 'width'), sections: [] }; tab.columns.push(column); if (selfClosing) column = null; }else if (tag === 'section' && column) {const ratio = attr(raw, 'columns');// `columns` is a width RATIO string, not a count: "11" is two equal columns, "1111" is four.// ABSENT means the width is UNKNOWN — left undefined so the occupancy check skips rather than// assuming a 1-column grid and inventing an overflow that is not there.- section = { name: attr(raw, 'name'), label: undefined, columns: ratio ? String(ratio).length : undefined, visible: flag(raw, 'visible'), showLabel: flag(raw, 'showlabel'), rows: [], fields: [] };+ section = { name: attr(raw, 'name'), ...idOf(raw), label: undefined, columns: ratio ? String(ratio).length : undefined, visible: flag(raw, 'visible'), showLabel: flag(raw, 'showlabel'), rows: [], fields: [] };column.sections.push(section);if (selfClosing) section = null;}diff --git a/plugins/model-apps/scripts/lib/zip-read.js b/plugins/model-apps/scripts/lib/zip-read.jsnew file mode 100644index 000000000..d6607500f--- /dev/null+++ b/plugins/model-apps/scripts/lib/zip-read.js@@ -0,0 +1,248 @@+'use strict';+// A strict reader of ONE entry of a ZIP archive held in memory — what `--verify` needs to open a translation export (lib/translation-labels.js), and no more.+//+// WHY ITS OWN READER. The plugin has no dependency to read an archive with (every script runs as it is installed, with Node's own modules), and the export is+// read by a program that decides, from what it finds, whether a form's captions are right. A reader that is lenient — takes the data's place from a header+// that disagrees with another, inflates past the size the archive declares, skips the checksum — can turn a damaged answer into a pass. So an archive is read+// when every number in it agrees with every other, and is refused, with the reason, in every other case: a refusal costs `--verify` a caption it can only list+// as unverified, which is where it was before it read exports at all.+//+// WHAT IT READS: the layout every ZIP writer produces (https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)+//+// [local header 0x04034b50 · name · extra][data] … [central header 0x02014b50 · name · extra · comment] … [end record 0x06054b50 · comment]+//+// The end record, found from the END of the file (the archive's comment may be anything up to 65,535 bytes, so the record is the last one whose comment length+// reaches the end of the file exactly), points at the central directory, which lists every entry with the place of its local header; the local header says again+// where its data starts. Both headers are read, because they are written by one program and disagree only when the archive is damaged or hand-made.+// - The platform's own export, measured: two deflated entries, flags 0x0002 (the compressor's "maximum" hint, not a data descriptor), version needed 20 —+// and an extra field of 28 bytes on each LOCAL header and none on the central one. So the data is found from the LOCAL header's own name and extra lengths, never+// from the central directory's. Its entries lie end to end from the first byte, the central directory follows the last one at once, and the end record follows+// the central directory at once: every byte of it belongs to an entry, the directory or the end record.+// - A data descriptor (flag bit 3) is accepted when it is there: the local header's checksum and sizes may then be zero, and the descriptor that follows the data —+// `0x08074b50` and the checksum and both sizes, or (the older form the format also allows) those three alone — must hold the central directory's numbers.+//+// THE LAYOUT IS CHECKED, for every entry and not only the one asked for: a deflate stream ends where it ends, whatever follows it, so an entry whose declared size runs+// four bytes into the next entry's header still inflates, to the right size and checksum. What says where an entry ends is therefore the layout as a whole — the+// entries, in the order of their places, must be every byte before the central directory, one after the other, each the local header, the data and its descriptor —+// and the deflate stream of the entry read must take up exactly the data the archive gives it.+//+// WHAT IT REFUSES, all of it as a `ZipReadError`: a file with no end record (or text after it), an archive in several parts, ZIP64 (the sizes and offsets of an+// export of this kind fit 32 bits, and a reader that half-understands ZIP64 can accept a file it has misread), a central directory that is outside the file, cut+// short, not the size of its entries or not followed by the end record at once, an entry that is encrypted, one that is neither stored nor deflated, a name that is+// in the archive twice, a local header that is missing or says something other than the central one, data that runs into the central directory, an entry that starts+// inside another or after bytes that belong to none, a data descriptor that the flags announce and that is not there or not the central directory's, data that does+// not inflate, a deflate stream that ends before its data does, data that is not the size the archive declares, and data whose CRC-32 is not the one declared.+// Inflating never goes past the declared size, so a small archive cannot be made to fill memory.+const zlib = require('node:zlib');++const LOCAL_FILE_HEADER = 0x04034b50;+const CENTRAL_DIRECTORY_HEADER = 0x02014b50;+const END_OF_CENTRAL_DIRECTORY = 0x06054b50;+// The optional signature of a data descriptor (APPNOTE 4.3.9.3: "commonly adopted", not required — so a descriptor without it is read as well).+const DATA_DESCRIPTOR = 0x08074b50;+// The ZIP64 end-of-central-directory locator, which sits right before the end record of a ZIP64 archive (20 bytes).+const ZIP64_END_LOCATOR = 0x07064b50;+const END_RECORD_SIZE = 22;+const MAX_COMMENT_BYTES = 0xffff;++// Guards against an unexpectedly large answer, not limits of the service: the archive is held, and so is what it inflates to. A translation workbook of an app's+// solution is some tens of kilobytes, and one that is megabytes is a very large solution; these leave room for that and stop short of the memory a string can hold.+const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;+const MAX_ENTRY_BYTES = 128 * 1024 * 1024;++// General-purpose flag bits: 0 = encrypted, 3 = the sizes and CRC follow the data, 6 = strong encryption, 11 = the name is UTF-8.+const FLAG_ENCRYPTED = 0x0001;+const FLAG_DATA_DESCRIPTOR = 0x0008;+const FLAG_STRONG_ENCRYPTION = 0x0040;+const FLAG_UTF8_NAME = 0x0800;++class ZipReadError extends Error {+ constructor(message) {+ super(message);+ this.name = 'ZipReadError';+ }+}+const refuse = (message) => { throw new ZipReadError(message); };++// CRC-32 as the ZIP format has it (reflected, polynomial 0xEDB88320, https://www.w3.org/TR/png/#D-CRCAppendix). A table, because the check runs over the whole+// of an entry; `zlib.crc32` is Node 22.2 and later, and the plugin runs on Node 20 as well.+const CRC_TABLE = (() => {+ const table = new Uint32Array(256);+ for (let n = 0; n < 256; n += 1) {+ let c = n;+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;+ table[n] = c >>> 0;+ }+ return table;+})();+function crc32(bytes) {+ let crc = 0xFFFFFFFF;+ for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 0xFF] ^ (crc >>> 8);+ return (crc ^ 0xFFFFFFFF) >>> 0;+}++// Where the end record is: the last one in the file whose comment ends the file.+function findEndRecord(archive) {+ const last = archive.length - END_RECORD_SIZE;+ for (let at = last; at >= Math.max(0, last - MAX_COMMENT_BYTES); at -= 1) {+ if (archive.readUInt32LE(at) === END_OF_CENTRAL_DIRECTORY && at + END_RECORD_SIZE + archive.readUInt16LE(at + 20) === archive.length) return at;+ }+ return refuse('the archive has no end-of-central-directory record');+}++// Every entry the central directory lists, each with the fields the data is read by. The numbers are the archive's and are not trusted: every read is bounded.+function readCentralDirectory(archive) {+ const end = findEndRecord(archive);+ const disk = archive.readUInt16LE(end + 4);+ const directoryDisk = archive.readUInt16LE(end + 6);+ const onThisDisk = archive.readUInt16LE(end + 8);+ const total = archive.readUInt16LE(end + 10);+ const size = archive.readUInt32LE(end + 12);+ const offset = archive.readUInt32LE(end + 16);+ if ((end >= 20 && archive.readUInt32LE(end - 20) === ZIP64_END_LOCATOR) || onThisDisk === 0xffff || total === 0xffff || size === 0xffffffff || offset === 0xffffffff) {+ refuse('a ZIP64 archive is not read');+ }+ if (disk !== 0 || directoryDisk !== 0 || onThisDisk !== total) refuse('an archive that spans more than one disk is not read');+ const directoryEnd = offset + size;+ if (directoryEnd > end) refuse('the central directory lies outside the archive');+ if (directoryEnd < end) refuse(`${end - directoryEnd} bytes between the central directory and the end record belong to neither`);+ const entries = [];+ let at = offset;+ for (let i = 0; i < total; i += 1) {+ if (at + 46 > directoryEnd) refuse('an entry of the central directory is cut short');+ if (archive.readUInt32LE(at) !== CENTRAL_DIRECTORY_HEADER) refuse('an entry of the central directory has a signature that is not 0x02014b50');+ const flags = archive.readUInt16LE(at + 8);+ const nameLength = archive.readUInt16LE(at + 28);+ const next = at + 46 + nameLength + archive.readUInt16LE(at + 30) + archive.readUInt16LE(at + 32);+ if (next > directoryEnd) refuse('an entry of the central directory runs past the central directory');+ const entry = {+ flags,+ method: archive.readUInt16LE(at + 10),+ crc: archive.readUInt32LE(at + 16),+ compressedSize: archive.readUInt32LE(at + 20),+ uncompressedSize: archive.readUInt32LE(at + 24),+ startDisk: archive.readUInt16LE(at + 34),+ localHeaderOffset: archive.readUInt32LE(at + 42),+ nameBytes: archive.subarray(at + 46, at + 46 + nameLength),+ };+ if (entry.compressedSize === 0xffffffff || entry.uncompressedSize === 0xffffffff || entry.localHeaderOffset === 0xffffffff) refuse('a ZIP64 entry is not read');+ if (entry.startDisk !== 0) refuse('an entry that starts on another disk is not read');+ // A name is UTF-8 when its flag says so, and otherwise the code page the archive was written in: what the names of an export use is ASCII, which latin1 reads as is.+ entry.name = entry.nameBytes.toString(flags & FLAG_UTF8_NAME ? 'utf8' : 'latin1');+ entries.push(entry);+ at = next;+ }+ if (at !== directoryEnd) refuse('the central directory is not the size its entries make');+ return { entries, directoryStart: offset };+}++// The size of the data descriptor at `at`, which the flags of `entry` say follows its data: 16 bytes with the signature, 12 without — and its numbers must be the+// central directory's. The bytes there are read as either form only up to `limit`, the start of the central directory.+function descriptorSize(archive, entry, at, limit) {+ const holdsTheNumbers = (p) => p + 12 <= limit+ && archive.readUInt32LE(p) === entry.crc && archive.readUInt32LE(p + 4) === entry.compressedSize && archive.readUInt32LE(p + 8) === entry.uncompressedSize;+ if (at + 16 <= limit && archive.readUInt32LE(at) === DATA_DESCRIPTOR && holdsTheNumbers(at + 4)) return 16;+ if (holdsTheNumbers(at)) return 12;+ return refuse(`the entry '${entry.name}' says a data descriptor follows its data and none does (neither the signature 0x08074b50 with the central directory's checksum and sizes, nor those alone)`);+}++// Where the local header of `entry` puts its data, and where the entry ends (after its data descriptor, if it has one) — once that header is found to say what the+// central directory says.+function placeOf(archive, entry, directoryStart) {+ const name = entry.name;+ const at = entry.localHeaderOffset;+ if (at + 30 > directoryStart) refuse(`the local header of '${name}' lies outside the data of the archive`);+ if (archive.readUInt32LE(at) !== LOCAL_FILE_HEADER) refuse(`the local header of '${name}' has a signature that is not 0x04034b50`);+ const nameStart = at + 30;+ const nameLength = archive.readUInt16LE(at + 26);+ const dataStart = nameStart + nameLength + archive.readUInt16LE(at + 28);+ const dataEnd = dataStart + entry.compressedSize;+ if (dataEnd > directoryStart) refuse(`the data of '${name}' runs past the central directory`);+ const descriptor = (entry.flags & FLAG_DATA_DESCRIPTOR) !== 0;+ // With a data descriptor the local header may hold zeros where the checksum and sizes go (a writer that streams does not know them yet), or the numbers themselves.+ const agrees = (offset, value) => archive.readUInt32LE(at + offset) === value || (descriptor && archive.readUInt32LE(at + offset) === 0);+ const disagrees = archive.readUInt16LE(at + 6) !== entry.flags+ || archive.readUInt16LE(at + 8) !== entry.method+ || !archive.subarray(nameStart, nameStart + nameLength).equals(entry.nameBytes)+ || !agrees(14, entry.crc) || !agrees(18, entry.compressedSize) || !agrees(22, entry.uncompressedSize);+ if (disagrees) refuse(`the local header of '${name}' does not agree with the central directory`);+ return { entry, start: at, dataStart, dataEnd, end: descriptor ? dataEnd + descriptorSize(archive, entry, dataEnd, directoryStart) : dataEnd };+}++// The places of every entry, checked to be what the platform writes: the entries, in the order of their places (which need not be the central directory's order),+// are every byte from the start of the archive to the central directory, one after the other. Nothing is hidden between them, and no entry's declared data reaches+// into another — which a deflate stream would not notice (see the header).+function layoutOf(archive, entries, directoryStart) {+ const places = entries.map((entry) => placeOf(archive, entry, directoryStart)).sort((a, b) => a.start - b.start);+ let previous = null;+ let cursor = 0;+ for (const place of places) {+ const name = place.entry.name;+ if (place.start < cursor) refuse(`the entry '${name}' starts inside the data of the entry before it ('${previous.entry.name}')`);+ if (place.start > cursor) {+ refuse(previous+ ? `${place.start - cursor} bytes between the entries '${previous.entry.name}' and '${name}' belong to no entry`+ : `${place.start} bytes of the archive before the entry '${name}' belong to no entry`);+ }+ previous = place;+ cursor = place.end;+ }+ if (cursor !== directoryStart) refuse(`${directoryStart - cursor} bytes between the last entry and the central directory belong to no entry`);+ return new Map(places.map((place) => [place.entry, place]));+}++// What a deflate stream is, when it inflates: the bytes it was made from, and how many bytes of `stored` the stream took up. zlib stops at the end of the stream and+// leaves what follows unread; `engine.bytesWritten` counts the bytes it took (measured on Node 20.20 and 22.13: a 42-byte stream followed by 0, 1, 4 or 100 other bytes+// reports 42 every time), so a stream that ends before the data does is told from one that fills it. https://nodejs.org/api/zlib.html#zlibbyteswritten+function inflateWhole(stored, maxOutputLength) {+ const { buffer, engine } = zlib.inflateRawSync(stored, { maxOutputLength, info: true });+ return { data: buffer, consumed: engine.bytesWritten };+}++function entryData(archive, place) {+ const { entry } = place;+ const name = entry.name;+ const stored = archive.subarray(place.dataStart, place.dataEnd);+ let data = stored;+ if (entry.method === 8) {+ let inflated;+ try {+ // One byte more than the declared size, so that data that inflates to more is told from data that inflates to exactly that: nothing larger is ever built.+ inflated = inflateWhole(stored, Math.max(1, entry.uncompressedSize + 1));+ } catch (err) {+ if (err && err.code === 'ERR_BUFFER_TOO_LARGE') refuse(`the entry '${name}' inflates to more than the ${entry.uncompressedSize} bytes the archive says`);+ return refuse(`the entry '${name}' did not inflate (${(err && err.message) || err})`);+ }+ if (inflated.consumed !== stored.length) refuse(`the deflate data of '${name}' ends ${stored.length - inflated.consumed} bytes before the end of the data the archive gives it`);+ data = inflated.data;+ }+ if (data.length !== entry.uncompressedSize) refuse(`the entry '${name}' is not the size the archive says (${data.length} bytes, not ${entry.uncompressedSize})`);+ if (crc32(data) !== entry.crc) refuse(`the entry '${name}' failed its CRC-32 check`);+ return data;+}++/**+ * The bytes of the entry named `name` of `archive`.+ * @param {Buffer} archive the whole archive+ * @param {string} name the entry's name, as the archive spells it+ * @param {{ maxArchiveBytes?: number, maxEntryBytes?: number }} [limits]+ * @returns {Buffer}+ * @throws {ZipReadError} when the archive is not one this reads with certainty, or has no such entry, or has two+ */+function readZipEntry(archive, name, { maxArchiveBytes = MAX_ARCHIVE_BYTES, maxEntryBytes = MAX_ENTRY_BYTES } = {}) {+ if (!Buffer.isBuffer(archive)) refuse('the archive is not a Buffer');+ if (archive.length > maxArchiveBytes) refuse(`the archive is larger than ${maxArchiveBytes} bytes`);+ if (archive.length < END_RECORD_SIZE) refuse('the archive has no end-of-central-directory record');+ const { entries, directoryStart } = readCentralDirectory(archive);+ const named = entries.filter((entry) => entry.name === name);+ if (named.length === 0) refuse(`the archive has no entry named '${name}'`);+ if (named.length > 1) refuse(`the entry '${name}' is in the archive twice`);+ const [entry] = named;+ // What the entry asked for must be before its place is looked at: an entry that cannot be read is refused as that, whatever the layout says.+ if (entry.flags & (FLAG_ENCRYPTED | FLAG_STRONG_ENCRYPTION)) refuse(`the entry '${name}' is encrypted`);+ if (entry.method !== 0 && entry.method !== 8) refuse(`the entry '${name}' uses compression method ${entry.method}, and only stored and deflated entries are read`);+ if (entry.uncompressedSize > maxEntryBytes) refuse(`the entry '${name}' is larger than ${maxEntryBytes} bytes`);+ return entryData(archive, layoutOf(archive, entries, directoryStart).get(entry));+}++module.exports = { readZipEntry, ZipReadError, crc32, MAX_ARCHIVE_BYTES, MAX_ENTRY_BYTES };diff --git a/plugins/model-apps/scripts/lint-app-spec.js b/plugins/model-apps/scripts/lint-app-spec.jsindex 01e160789..e3fd43883 100644--- a/plugins/model-apps/scripts/lint-app-spec.js+++ b/plugins/model-apps/scripts/lint-app-spec.js@@ -195,13 +195,13 @@ function main() {: `app spec has ${report.warnings.length} warning(s) and --strict was set; see stdout JSON\n`);}- // Set the code and RETURN rather than process.exit(). Node's stdout is asynchronous when it is a- // TTY on Windows, and process.exit() tears the process down without draining it — so an- // interactive Windows run of a large report could lose its tail. MEASURED: a 5 MB write over a- // PIPE survives process.exit() intact on Windows, so a `--json | jq` CI consumer was never at- // risk; this is the interactive case and the idiomatic pattern, not a fix for a reproduced bug.- // The non-JSON usage-error paths still exit through emitResult's process.exit() — deliberately- // out of scope here, since that is shared behaviour across every CLI in this directory.+ // Set the code and RETURN rather than process.exit(). Node writes to a pipe asynchronously on Linux+ // and macOS (and to a TTY on Windows), and process.exit() tears the process down without draining+ // it — so a `--json | jq` consumer there could lose the tail of a large report. MEASURED: a 5 MB+ // write over a PIPE survives process.exit() intact on Windows, where a pipe on stdout is+ // synchronous — which is why a Windows run never showed it. The non-JSON usage-error paths exit+ // through emitResult, which makes its writes blocking before it exits (lib/output-redaction.js+ // makeWritesBlocking), so they are whole too.// https://nodejs.org/api/process.html#a-note-on-process-ioprocess.exitCode = failed ? 1 : 0;return;diff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.jsindex a0829f033..a28889b24 100644--- a/plugins/model-apps/scripts/list-connections.js+++ b/plugins/model-apps/scripts/list-connections.js@@ -41,6 +41,7 @@ const {} = require('./lib/dataverse-auth');const { sdkFirst, connectivity } = require('./lib/sdk-first.js');const { PAC_READ_TIMEOUT_MS, PAC_BANNER, LINE_BREAK, LEFTOVER_ADVICE, pacErrorText, stopClaim } = require('./lib/pac-fallback.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');function normalizeHeader(header) {return String(header).toLowerCase().replace(/[^a-z0-9]/g, '');@@ -461,6 +462,7 @@ async function main() {// and report a missing envUrl — naming the symptom instead of the typo that caused it.const flagError = validateFlags(argv, { known: [] });if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/list-custom-apis.js b/plugins/model-apps/scripts/list-custom-apis.jsindex aa745dd9b..07f497bef 100644--- a/plugins/model-apps/scripts/list-custom-apis.js+++ b/plugins/model-apps/scripts/list-custom-apis.js@@ -32,6 +32,7 @@ const {} = require('./lib/dataverse-auth');const { exitIfCustomApiDisabled } = require('./lib/feature-flags');const { odataLit } = require('./lib/odata');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// customapi.bindingtype is a Dataverse option set. Only the value→meaning mapping matters here;// a page invokes a record-bound API via boundTo, so we surface Entity as bound and Global as unbound.@@ -129,6 +130,7 @@ async function main() {const USAGE = 'Usage: node list-custom-apis.js <envUrl> [--entities <logicalName1,logicalName2>]';const flagError = validateFlags(argv, { known: ['entities'], needValue: ['entities'] });if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/list-languages.js b/plugins/model-apps/scripts/list-languages.jsindex dea7cedf4..1ea71fe82 100644--- a/plugins/model-apps/scripts/list-languages.js+++ b/plugins/model-apps/scripts/list-languages.js@@ -42,6 +42,7 @@const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');const { describeEnvironmentLanguages } = require('./lib/lcid-cultures.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = 'Usage: node scripts/list-languages.js --env <envUrl>';@@ -60,6 +61,7 @@ async function main() {const { flags } = parseArgs(argv);const flagError = validateFlags(argv, { known: ['env'], needValue: ['env'] });if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -71,6 +73,7 @@ async function main() {try {env = requireDataverseOrigin(flags.env);} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${err.message}\n${USAGE}\n`);process.exit(1);}@@ -89,6 +92,8 @@ async function main() {emitResult(false, { ok: false, error: String((failure && failure.message) || failure), ...(code ? { code } : {}) }, { ascii: true });return;}+ // The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);for (const lcid of languages.unmapped) {process.stderr.write(`⚠ LCID ${lcid} has no culture code in this plugin's table, so its code and text direction are unknown (reported as null, not guessed).\n`);}@@ -99,6 +104,7 @@ module.exports = { readLanguages };if (require.main === module) {main().catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Error: ${err.message}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/list-tables.js b/plugins/model-apps/scripts/list-tables.jsindex 03a59510d..28ae46ad4 100644--- a/plugins/model-apps/scripts/list-tables.js+++ b/plugins/model-apps/scripts/list-tables.js@@ -49,6 +49,7 @@const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = 'Usage: node scripts/list-tables.js --env <envUrl> [--search "<term>[,<term>...]"] [--exact] [--type custom|standard|all]';const TABLE_TYPES = ['custom', 'standard', 'all'];@@ -155,6 +156,7 @@ async function readTables(env, args = {}, httpClient) {}function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${message}\n${USAGE}\n`);process.exit(1);}@@ -200,6 +202,7 @@ module.exports = { readTables, searchTerms };if (require.main === module) {main().catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Error: ${err.message}\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/preview-app.js b/plugins/model-apps/scripts/preview-app.jsindex 0ec1c3521..4addca331 100644--- a/plugins/model-apps/scripts/preview-app.js+++ b/plugins/model-apps/scripts/preview-app.js@@ -10,6 +10,7 @@ const path = require('node:path');const { renderAppPreview } = require('./lib/app-preview.js');const { parseArgs, validateFlags, readJsonArg } = require('./lib/dataverse-auth.js');const { migrateAppSpec } = require('./lib/app-spec.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');function main() {const argv = process.argv.slice(2);@@ -17,6 +18,7 @@ function main() {const USAGE = 'Usage: node scripts/preview-app.js --spec @<app-folder>/app-spec.json';const flagError = validateFlags(argv, { known: ['spec'], needValue: ['spec'] });if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/preview-form.js b/plugins/model-apps/scripts/preview-form.jsindex f2d74fb4c..35186523d 100644--- a/plugins/model-apps/scripts/preview-form.js+++ b/plugins/model-apps/scripts/preview-form.js@@ -9,6 +9,7 @@ const path = require('node:path');const { renderForms } = require('./lib/form-preview.js');const { parseArgs, validateFlags, readJsonArg } = require('./lib/dataverse-auth.js');const { migrateAppSpec, validateAppSpec } = require('./lib/app-spec.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');function main() {const argv = process.argv.slice(2);@@ -16,6 +17,7 @@ function main() {const USAGE = 'Usage: node scripts/preview-form.js --spec @<app-folder>/app-spec.json [--entity <schemaName>]';const flagError = validateFlags(argv, { known: ['spec', 'entity'], needValue: ['spec', 'entity'] });if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -30,6 +32,7 @@ function main() {if (!validation.ok) {// Validate before rendering because the wireframe renderer intentionally assumes the App Spec// contract (for example forms[].entity); a clear validation error is better than a TypeError.+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Invalid App Spec:\n${validation.errors.map((e) => ` - ${e}`).join('\n')}\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/promote-intent-pages.js b/plugins/model-apps/scripts/promote-intent-pages.jsindex ef5a19b2a..7db16a92f 100644--- a/plugins/model-apps/scripts/promote-intent-pages.js+++ b/plugins/model-apps/scripts/promote-intent-pages.js@@ -19,6 +19,7 @@const fs = require('node:fs');const path = require('node:path');const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const { migrateAppSpec } = require('./lib/app-spec.js');const { pageKey, pageFile } = require('./lib/page-plan.js');const { navReferencedKeys, navMalformedRefs, navTargetParity, strayPageRefs, describePageRefLocations, pageRefAdvice, frontierNote, PAGEREF_RULE } = require('./lib/pageref-resolver.js');@@ -75,6 +76,7 @@ function main() {needValue: ['spec', 'working-dir'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -97,10 +99,12 @@ function main() {originalText = fs.readFileSync(specPath, 'utf8');raw = JSON.parse(originalText);} catch (e) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`cannot read app spec at ${specPath}: ${e.message}\n`);process.exit(3);}if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`app spec at ${specPath} is not a JSON object\n`);process.exit(3);}@@ -133,7 +137,10 @@ function main() {const failed = results.filter((r) => r.problems.length);if (failed.length) {// Fail-closed: the spec on disk is untouched, so the caller can regenerate just the bad pages- // and re-run this command.+ // and re-run this command. Every failed page's diagnostics go out on both streams and the process+ // exits right after, so the writes are made blocking first: on Linux and macOS a pipe would+ // otherwise take only what fits at once (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify({ ok: false, promoted: [], failed }, null, 2) + '\n');process.stderr.write(`promotion aborted — ${failed.length} of ${results.length} page(s) failed validation; app-spec.json was NOT modified\n`@@ -176,6 +183,7 @@ function main() {fs.renameSync(tmp, specPath);} catch (e) {try { fs.unlinkSync(tmp); } catch { /* nothing to clean up */ }+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`failed to write ${specPath}: ${e.message}\n`);process.exit(3);}diff --git a/plugins/model-apps/scripts/provision-entities.js b/plugins/model-apps/scripts/provision-entities.jsindex 592ed6504..6bde71799 100644--- a/plugins/model-apps/scripts/provision-entities.js+++ b/plugins/model-apps/scripts/provision-entities.js@@ -13,6 +13,7 @@ const { quickCreateEnabledFor, normalizeLanguageCode, askedPrimaryNameLength, keconst { createAzHttpClient } = require('./lib/sdk-http-client.js');const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, readProvisionedLanguages } = require('./lib/dataverse-auth.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// Construct the SDK against the vendored bundle + an az-token HttpClient. Two clients:// sdk — carries solutionUniqueName (metadata + record writes auto-join the@@ -131,7 +132,8 @@ function buildPlan(input, opts) {}// Then the alternate keys over a name column whose length is set: the apply makes such a key once that length is right// (keyWaitsForNameLength, which depends on what the key's label is sent as and not on the language), where a table it creates has it.- // computeTotal counts them with the other keys.+ // A key labelled in several languages that the environment made the name column too long to fit beside is made there too, which only the+ // environment can say, so the plan lists it with its table and the apply makes it after the length step. computeTotal counts them with the other keys.for (const e of input.entities || []) {for (const k of e.alternateKeys || []) {if (keyWaitsForNameLength(e, k)) plan.push(`alt key ${e.schemaName}.${k.schemaName}`);@@ -319,6 +321,7 @@ async function main() {needValue: ['env', 'input', 'language-code', 'languageCode'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -338,6 +341,7 @@ async function main() {if (rawLang !== undefined) {languageCode = normalizeLanguageCode(rawLang);if (languageCode === null) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ --language-code / --languageCode must be digits only, a positive integer LCID up to 65535 (got '${rawLang}')\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/provision-solution.js b/plugins/model-apps/scripts/provision-solution.jsindex c55407531..34be9e2ac 100644--- a/plugins/model-apps/scripts/provision-solution.js+++ b/plugins/model-apps/scripts/provision-solution.js@@ -20,6 +20,7 @@ const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth')const { createAzHttpClient } = require('./lib/sdk-http-client');const { odataLit } = require('./lib/odata.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');/*** Finds the publisher to use for the solution:@@ -140,6 +141,7 @@ async function main() {needValue: ['description', 'version', 'publisher'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/model-apps/scripts/run-tests.js b/plugins/model-apps/scripts/run-tests.jsindex 11426d5bd..e2b6e2209 100644--- a/plugins/model-apps/scripts/run-tests.js+++ b/plugins/model-apps/scripts/run-tests.js@@ -19,6 +19,7 @@ const { spawnResultSync, withPathFirst } = require('./lib/process-runner.js');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// Node-20 bin dir for the SDK Jest suite (its canvas native module is built for the Node-20 ABI).// Portable: set NODE20_BIN=<dir-containing-node20> or pass nothing to skip the SDK suite.@@ -169,6 +170,10 @@ function main(argv) {process.stdout.write(`\n=== plugin node:test (${files.length} files) ===\n`);const plugin = runPluginSuite(files, { cwd: pluginRoot });results.push({ name: 'plugin node:test', ok: plugin.status === 0 });+ // What follows is this process's own report, and `process.exit(main())` follows it at once: blocking writes put it in the+ // pipe whole (lib/output-redaction.js makeWritesBlocking). Made again before the summary, because the SDK suite's children+ // share these streams, and a child that dies before Node restores the pipe's flags can leave it non-blocking.+ makeWritesBlocking(process.stdout, process.stderr);if (plugin.left.length) {process.stdout.write(`\n${plugin.left.length} file(s) or folder(s) left in the suite's temporary folder:\n`);for (const name of plugin.left.slice(0, 50)) process.stdout.write(` ${name}\n`);@@ -201,6 +206,7 @@ function main(argv) {}// Summary.+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write('\n=== regression summary ===\n');const { lines, exitCode } = summarize(results);for (const l of lines) process.stdout.write(`${l}\n`);diff --git a/plugins/model-apps/scripts/smoke-eval.js b/plugins/model-apps/scripts/smoke-eval.jsindex 30f678d96..3c5358ddc 100644--- a/plugins/model-apps/scripts/smoke-eval.js+++ b/plugins/model-apps/scripts/smoke-eval.js@@ -12,6 +12,7 @@ const os = require('node:os');const fs = require('node:fs');const path = require('node:path');const { spawnSync } = require('node:child_process');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// A minimal 1x1 transparent PNG (base64) for the nav-icon web resource.const PNG_1x1 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';@@ -166,6 +167,10 @@ function dvGet(env, apiPath) {}async function main(env, prefix) {+ // This run forwards each step's output (spawnSync, which leaves this process's event loop idle meanwhile) and ends in the+ // caller's `process.exit`: a write a pipe could not take at once would wait for a loop turn that never comes. So every write+ // is blocking from the start (lib/output-redaction.js makeWritesBlocking) — a maintainer's run, read to its end.+ makeWritesBlocking(process.stdout, process.stderr);const spec = buildSmokeSpec(prefix);const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-eval-'));const specPath = path.join(dir, 'app-spec.json');diff --git a/plugins/model-apps/scripts/solution-settings.js b/plugins/model-apps/scripts/solution-settings.jsindex 03b95de37..0952b56be 100644--- a/plugins/model-apps/scripts/solution-settings.js+++ b/plugins/model-apps/scripts/solution-settings.js@@ -43,14 +43,22 @@// first one did. The first answer is the SDK's, with its status and code. When it does not say how the import ended (no answer, 401, 408, any 5xx) the failure says// the import was sent once and names its job, and the job's log is read once for the platform's own reason (never failing the report if it cannot be read).//-// The one exception is an ImportSolution the platform REFUSED TO START: HTTP 429 with a customization-lock Dataverse error code whose documented text says the operation "Cannot start" — "Cannot start the requested-// operation … because there is another … running at this moment" (for 0x8004F063: "Cannot start another … because there is a previous … running") — (LOCK_REFUSAL_CODES: 0x8004F061, 0x8004F062, 0x8004F063, 0x8004F064,-// 0x8004F067): a publish, or another import, holds the environment's customization lock. Such an import is-// sent again, under a NEW job id, but only after `GET importjobs(<id>)` for the id the refused send carried answers 404, which proves it never started: at most five sends in all, after 10, 20, 40 and 60 s, or-// the platform's Retry-After when that asks for longer — waited WHOLE, in either of its forms — and inside one budget of five minutes of elapsed time from the first refusal to the last send (IMPORT_RETRY_BUDGET_MS:-// the waits and the proof reads together; the time an accepted import takes is not in it). A wait that does not fit in what is left of the budget ends the retry there: the platform's refusal is the failure, with-// the sends so far, and the import is never sent early to make it fit. Any other answer — another status, another kind of 429, the generic solution-concurrency code 0x80071151 (whose documented text says an-// operation FAILED), a gateway's 5xx, no answer, a job that exists or a read that fails — is the first and the last send, as above. See `sendImport`.+// The one exception is an ImportSolution the platform REFUSED TO START: a publish, or another import, holds the environment's customization lock. Such an import is sent again, under a NEW job id, when the refused+// send's import job proves that nothing of the package was applied. Two answers are refusals to start, each with its own proof:+// - HTTP 429 with a customization-lock Dataverse error code whose documented text says the operation "Cannot start" — "Cannot start the requested operation … because there is another … running at this moment"+// (for 0x8004F063: "Cannot start another … because there is a previous … running") — (LOCK_REFUSAL_CODES: 0x8004F061, 0x8004F062, 0x8004F063, 0x8004F064, 0x8004F067). Its proof is `GET importjobs(<id>)`+// for the id the refused send carried answering 404 — which proves it never started — read after the wait;+// - HTTP 429 with the generic solution-concurrency code 0x80071151 (SolutionConcurrencyFailure) and a message that begins "Cannot start": what the platform was measured to answer an import that meets another+// import or a publish. The code alone does not say that nothing started — its documented text says an installation or removal FAILED — so the refused send's job is read ONCE and AT ONCE (the row is final+// when the answer arrives), and the rule of lib/import-job-proof.js decides: the job does not exist (404), or it is finished and its log — read as one XML document, strictly — says that the import failed+// with that error (`errorcode="-2147020463"`, `succeeded="failure"`) with the solution manifest and every component unprocessed (only the package's own checks processed). A job that is still running, one+// that failed after it began, a log that is not exactly that, or a read that fails is NOT proof: the import is sent once, and the failure says why, and to look up the import job before importing again.+// At most five sends in all, after 10, 20, 40 and 60 s, or the platform's Retry-After when that asks for longer — waited WHOLE, in either of its forms — and inside one budget of five minutes of elapsed time from+// the first refusal to the last send (IMPORT_RETRY_BUDGET_MS: the waits and the proof reads together; the time an accepted import takes is not in it). A wait that does not fit in what is left of the budget ends the+// retry there: the platform's refusal is the failure, with the sends so far, and the import is never sent early to make it fit. The budget is asked again when a wait is over, for either refusal — a timer can+// resume later than it was asked to — so a wait that ENDED past the five minutes ends the retry too, before the send. The fifth send's refusal is the sends running out and its job is not read: for a lock code+// the failure says what it always said, and for 0x80071151 — whose job alone could show that nothing was applied — it says what to look up before the import is run again, never to run it again outright.+// Any other answer — another status, another kind of 429, 0x80071151 with any other words, a gateway's 5xx, no answer, a job that exists or a read that fails — is the first and the last send, as above. See `sendImport`.//// What the output holds of the settings file: entry NAMES, and what the sanitizer lets through of a text that quotes a value — which is less than every value, as follows. The file is read from// and written to disk only, and every text another party wrote — the SDK's, the platform's, pac's, a job log's — goes through `sanitizer`, WHOLE, before it is shown. What it does with a value depends@@ -89,8 +97,9 @@// template { "ok": true, "source": "sdk", "out": "<absolute path>", "environmentVariables": 2, "connectionReferences": 1 }// import { "ok": true, "source": "sdk", "importJobId": "<guid>", "applied": { "environmentVariables": ["new_Url"], "connectionReferences": ["new_Dataverse"] } }// and, when the platform refused the import (another operation held its lock) and it was sent again: the same, with `importJobId` the job of the send that ran, "importAttempts": <sends>, and-// "importRefusals": [ { "importJobId": "<guid>", "status": 429, "code": "0x8004F064", "waitedMs": 10000 } ] — each refused send and the wait the run made after it. A first send that is taken-// prints none of these two.+// "importRefusals": [ { "importJobId": "<guid>", "status": 429, "code": "0x8004F064", "waitedMs": 10000 } ] — each refused send and the wait the run made after it; a refusal with 0x80071151 also says+// how its job proved that nothing was applied — "proof": "job-absent" (the job does not exist) or "proof": "job-refused-before-any-component" (its log says the import was refused at the lock before it+// processed anything). A first send that is taken prints none of these two.// and, when pac answered because the SDK refused, "source": "pac" and "fallback": { "code": "<the SDK's code>", "message": "…" } — the SDK's own words, so// the "Nothing was imported" in one is about the SDK's attempt, which stopped before any request; pac then did the work;// "warnings": [...] when something the run made could not be cleaned up: the SDK could not delete the staged copy of the package it made, or `template` could not remove the temporary name its@@ -101,15 +110,19 @@// Exit codes: 0 done; 1 usage error (stderr names the flag, stdout stays empty) or a failure — stdout then holds// { "ok": false, "error": "<message>", "code": "<the SDK's or the PAC step's code>" [, "status": <HTTP status of the answer>] [, "fallback": { … }, "importJobId": "<guid>"]// [, "importAttempts": <sends>, "importRefusals": [ … ] — when the import was sent again after a refusal, the same two fields as on success; the failure is then the platform's own refusal or the-// failure of the last send, with the count added — and, when the sends ran out, or the retry ended because the wait the platform asked for did not fit in its five minutes, a sentence of the plugin's own-// that says which] [, "warnings": [...]] } and stderr the message. `warnings` is the same cleanup note as on success: a failed run that staged a copy and could not delete it says so.+// failure of the last send, with the count added — and, when the sends ran out on a refusal, or the retry ended because the wait the platform asked for did not fit in its five minutes (or a wait ended+// after them), or because the job of a refusal with 0x80071151 did not prove that nothing was applied (and what to do then: look up the import job before importing again), a sentence of the plugin's+// own that says which — when the sends ran out on a refusal with 0x80071151, what the job of that last send must show before the import is run again]+// [, "warnings": [...]] } and stderr the message. `warnings` is the same cleanup note as on success: a failed run that staged a copy and could not delete it says so.const crypto = require('node:crypto');const fs = require('node:fs');const path = require('node:path');const { setTimeout: delay } = require('node:timers/promises');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const { parseArgs, validateFlags, emitResult, requireDataverseOrigin, makeRequest, webApiUrl, getAuthToken } = require('./lib/dataverse-auth.js');const { createAzHttpClient, retryAfterMs, scrub, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH } = require('./lib/sdk-http-client.js');const { sdkFirst } = require('./lib/sdk-first.js');+const { proveRefusedImport, PROOF_LOG } = require('./lib/import-job-proof.js');const { runPac } = require('./lib/pac-fallback.js');const { assertPlainFileTarget, assertSafeOutputDir, writeFileSafe, removeTreeWithRetry } = require('./lib/safe-fs.js');const { makeTempWorkspace, pruneWorkspaceParents } = require('./lib/temp-workspace.js');@@ -153,11 +166,13 @@ const LONG_ACTION = /\/(ExportSolution|StageSolution|ImportSolution)$/;// 0x8004F063 CustomizationLockEx_BothKnownSame "Cannot start another [{0}] because there is a previous [{1}] running at this moment. Use Solution History for more details."// 0x8004F064 CustomizationLockEx_BothKnownDifferent "Cannot start the requested operation [{0}] because there is another [{1}] running at this moment. Use Solution History for more details."// 0x8004F067 CustomizationLockEx_BlockingUnknown "Cannot start the requested operation [{0}] because there is a customization running at this moment. Use Solution History for more details."-// Left out on purpose — those answers are sent once, and reported as every answer to an import was before this retry existed:+// Left out of the list on purpose — an answer with one of these is sent once, and reported as every answer to an import was before this retry existed — the first of them with ONE exception (concurrencyRefusalOf):// 0x80071151 SolutionConcurrencyFailure "The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later." An operation that-// failed is not one the platform says it refused to start. Answers that begin "Cannot start the requested operation" and end with that sentence have been seen with this code; this list follows what-// the reference documents for a code, not what a few answers suggest about it. Measured on a Public-cloud environment: an import that met another import or a publish was-// refused with this code and those words, and its import job existed by then (read back with its progress at 37.5%), so importJobIsAbsent could not have proved it either.+// failed is not one the platform says it refused to start, so the code alone sends nothing again. Measured on a Public-cloud environment, though, this is the code an import that meets another import+// or a publish is refused with, and its message begins "Cannot start another [Import] because there is a previous [Import] running at this moment" (a publish: "Cannot start the requested operation+// [Import] because there is another [Publish] running"): an answer with this code AND those words is looked into — the refused send's job is read once, at once, and sent again when it proves that+// nothing was applied (lib/import-job-proof.js has the rule and the measurements: a job that never existed, or one whose log says the import was refused at the lock before it processed anything).+// The words alone prove nothing; the job does. Any other words under this code are sent once.// 0x80071154 ConcurrentOperationFailure "The current {0} operation failed due to another concurrent operation running at the same time": an operation that failed had started.// 0x8004F077, 0x80090412 (the customization lock of other services) and the service protection limits 0x80072321, 0x80072322, 0x80072326: a 429 of another kind, with another remedy.// A code in this list says the import was refused; it is the job that proves it (importJobIsAbsent), because a refusal is what the platform SAYS and a gateway can say a good deal.@@ -168,9 +183,13 @@ const IMPORT_MAX_SENDS = 5;const IMPORT_RESEND_WAITS_MS = Object.freeze([10 * 1000, 20 * 1000, 40 * 1000, 60 * 1000]);// And one budget of elapsed time for the whole retry: from the moment the first refusal arrives to the moment the last send leaves — every wait and every read of a refused send's job in between — not a// second more than five minutes. Before each wait the run asks whether it fits in what is left; when it does not (a `Retry-After` of ten minutes, say) the retry ENDS there and the platform's refusal is the-// failure — the import is never sent early to make it fit. What is not in the budget is the time an import that the platform ACCEPTED takes: it runs for as long as it runs (ACTION_TIMEOUT_MS), and a send the+// failure — the import is never sent early to make it fit. And it asks again when the wait is over, before the send: what a timer is asked for is the least it takes (a busy machine, a laptop that was suspended+// resumes it later), so a wait that fitted can still end past the five minutes, and a send then is one the budget does not allow. What is not in the budget is the time an import that the platform ACCEPTED+// takes: it runs for as long as it runs (ACTION_TIMEOUT_MS), and a send the// platform refuses is answered in moments. A publish of all customizations, the usual holder of the lock, is over in a minute or two; an import that holds it can run much longer, and the run then ends as it-// always did, with the platform's refusal.+// always did, with the platform's refusal. The same sends, waits and budget serve both kinds of refusal (a lock code, and 0x80071151 with its job read at once): they are one lock, and the measured holders are+// short — a publish of six tables took 3–12 s, an import of a package of six tables 48–127 s — against the 130 s the four waits add up to; the budget is never the limit of the default schedule, only of a+// `Retry-After`. At most four reads of a refused send's job are made for the retry, one for each refusal that is not the last.const IMPORT_RETRY_BUDGET_MS = 5 * 60 * 1000;const REDACTED = '<redacted>';@@ -702,12 +721,18 @@ const COMPOSED_MESSAGE = new WeakSet();// (importJobIsAbsent) and the log of a failed one (readImportJobFailure) — are made through it, over the same seams as the import's own client (`http`: getToken, request, sleep, now).const readOnceClient = (env, http = {}) => createAzHttpClient(env, { ...http, sendOnce: () => true });+// The Dataverse error code of the generic solution-concurrency failure (`SolutionConcurrencyFailure`). It is what the platform was MEASURED to answer an import that meets another import or a publish — never one of+// LOCK_REFUSAL_CODES — with "Cannot start …" words; see concurrencyRefusalOf for why the words matter and lib/import-job-proof.js for what decides.+const CONCURRENCY_REFUSAL_CODE = '0x80071151';+// How the message of such a refusal begins: "Cannot start another [Import] because there is a previous [Import] running at this moment. …", or "Cannot start the requested operation [Import] because there is+// another [Publish] running …". The documented text of the code alone ("The solution installation or removal failed due to …") does not begin so.+const CANNOT_START = /^\s*Cannot start\b/i;+/**- * The platform's refusal to START an import, from a raw transport answer: `{ status: 429, code }` — the code spelled as the error reference spells it — when the answer is HTTP 429 and its Dataverse- * error body (`{ "error": { "code": "0x80071151", "message": "…" } }`) carries one of LOCK_REFUSAL_CODES, in either case of its hex digits; else null. Anything that does not say so — another status,- * another code, a body that is not JSON or has no `error.code` text, the lock's English words under another code — is not a refusal to start, and the import is not sent again.+ * The Dataverse error of a raw transport answer that is an HTTP 429 — `{ "error": { "code": "0x80071151", "message": "…" } }` — as `{ code, message }`, each the text the body gives or null when it gives+ * none; null for any other answer (another status, a body that is not JSON, a transport failure).*/-function lockRefusalOf(res) {+function errorOf429(res) {if (!res || res.error || res.statusCode !== 429) return null;let body = res.body;try {@@ -715,11 +740,34 @@ function lockRefusalOf(res) {} catch {return null;}- const code = body && body.error && typeof body.error.code === 'string' ? body.error.code : null;- const known = code === null ? undefined : LOCK_REFUSAL_CODES.find((candidate) => candidate.toLowerCase() === code.toLowerCase());+ const error = body && body.error;+ return { code: error && typeof error.code === 'string' ? error.code : null, message: error && typeof error.message === 'string' ? error.message : null };+}++/**+ * The platform's refusal to START an import, from a raw transport answer: `{ status: 429, code }` — the code spelled as the error reference spells it — when the answer is HTTP 429 and its Dataverse+ * error body (`{ "error": { "code": "0x8004F064", "message": "…" } }`) carries one of LOCK_REFUSAL_CODES, in either case of its hex digits; else null. Anything that does not say so — another status,+ * another code, a body that is not JSON or has no `error.code` text, the lock's English words under another code — is not a refusal to start, and the import is not sent again.+ */+function lockRefusalOf(res) {+ const error = errorOf429(res);+ const known = error && error.code !== null ? LOCK_REFUSAL_CODES.find((candidate) => candidate.toLowerCase() === error.code.toLowerCase()) : undefined;return known ? { status: 429, code: known } : null;}+/**+ * The other refusal that can be a refusal to start: `{ status: 429, code: '0x80071151' }` when the answer is HTTP 429, the code is SolutionConcurrencyFailure (in either case of its hex digits) AND the message+ * begins "Cannot start". The code alone says only that an installation or removal FAILED because another ran at the same time, which an operation that had started can say too, so the platform's own+ * words are required as well — but they are not what proves anything: the refused send's job does (readRefusedImportJob, lib/import-job-proof.js), and an answer whose words are another language's, or+ * whose message is missing, is sent once as every answer to an import was.+ */+function concurrencyRefusalOf(res) {+ const error = errorOf429(res);+ return error && error.code !== null && error.code.toLowerCase() === CONCURRENCY_REFUSAL_CODE && error.message !== null && CANNOT_START.test(error.message)+ ? { status: 429, code: CONCURRENCY_REFUSAL_CODE }+ : null;+}+// The job id an ImportSolution request carries, and the same request under another one. The body is the SDK's JSON text, and the package — a base64 string, up to ~170 MB — is nearly all of it, so the id is// found and swapped as TEXT: parsing that body and writing it again would hold it twice more in memory. Every other byte stays what it was. The key appears once — the package is base64, and every other// string in the body has its quotes escaped, so no text can spell `"ImportJobId":"` — and a body that has it any other number of times has no id, and so is never sent again.@@ -746,28 +794,71 @@ async function importJobIsAbsent(env, importJobId, http) {}/**- * Sends one ImportSolution request — and sends it AGAIN, under a NEW import job id, only while the platform's answer PROVES the import did not start. An import the platform may have accepted is- * never sent twice (a gateway answers 502, 504 or 401 for an import it accepted and is running: the rule of solutionHttpClient); what is sent again is the one answer that says the platform- * did not start it: its refusal because another operation holds the environment's customization lock (lockRefusalOf — the status and the Dataverse error code, not words), together with the- * import job the refused send carried not existing (importJobIsAbsent), read after the wait, so that it is the latest evidence before a second copy leaves. Then, for at most IMPORT_MAX_SENDS sends and- * inside IMPORT_RETRY_BUDGET_MS of elapsed time from the first refusal:- * wait the step of IMPORT_RESEND_WAITS_MS, or the platform's `Retry-After` when that asks for longer — WHOLE, uncapped → read the job → tell the listener → send again with a job id that was never used.- * A wait that does not fit in what is left of the budget ends the retry BEFORE it is waited, and so does a read of the job that leaves nothing of it: the refusal that was last answered is returned as it came- * and the import is not sent again — never early, to make it fit. `onStopped({ importJobId, waitMs, spentMs })` says so (`waitMs` is the wait that did not fit, or null when the budget ran out during the read).+ * What the job of a send refused with SolutionConcurrencyFailure proves — `{ proven: true, proof }` or `{ proven: false, why, reason }` (lib/import-job-proof.js has the rule, with what it rests on). One read, `sendOnce`,+ * of the three columns the rule looks at and no others: `progress` is the same for a running import and a refused one, and `solutionid` names a solution that was never made. A read that fails, answers+ * anything that is neither the job nor a 404, or gets no answer (a transport failure, no token) proves nothing: `answer` is then null.+ */+async function readRefusedImportJob(env, importJobId, http) {+ let answer = null;+ try {+ answer = await readOnceClient(env, http).get(webApiUrl(env, `importjobs(${importJobId})?$select=importjobid,completedon,data`));+ } catch {+ // No answer: the verdict says so.+ }+ return proveRefusedImport(answer);+}++/**+ * Sends one ImportSolution request — and sends it AGAIN, under a NEW import job id, only while the platform's answer PROVES the import did not apply anything. An import the platform may have accepted is+ * never sent twice (a gateway answers 502, 504 or 401 for an import it accepted and is running: the rule of solutionHttpClient); what is sent again is an answer that says the platform refused to+ * start it because another operation holds the environment's customization lock, in one of two forms:+ * - one of LOCK_REFUSAL_CODES (lockRefusalOf — the status and the Dataverse error code, not words), together with the import job the refused send carried not existing (importJobIsAbsent), read AFTER the wait, so+ * that it is the latest evidence before a second copy leaves;+ * - SolutionConcurrencyFailure with "Cannot start …" words (concurrencyRefusalOf), which is what the platform was measured to answer an import that meets another import or a publish. Its job is read ONCE and AT+ * ONCE (readRefusedImportJob) — the row of a refused send is final when the answer is in hand — and the rule of lib/import-job-proof.js decides: the job does not exist, or it is finished and its log says+ * the import failed with that error before it processed the solution or any component. A job that proves nothing ends the retry there (`onUnproven`), without a wait: the platform's refusal is the failure.+ * Then, for at most IMPORT_MAX_SENDS sends and inside IMPORT_RETRY_BUDGET_MS of elapsed time from the first refusal (the read of the job counts in it):+ * [read the job — SolutionConcurrencyFailure] → wait the step of IMPORT_RESEND_WAITS_MS, or the platform's `Retry-After` when that asks for longer — WHOLE, uncapped → [read the job — a lock code] →+ * tell the listener → send again with a job id that was never used.+ * A wait that does not fit in what is left of the budget ends the retry BEFORE it is waited; one that ENDS past the budget — a timer resumes later than it was asked to, on a busy machine or a laptop that was+ * suspended — ends it after the wait, before the send, for either refusal, and so does a read of the job that leaves nothing of it. The refusal that was last answered is returned as it came and the import is not+ * sent again — never early, to make it fit. `onStopped({ importJobId, waitMs, spentMs })` says so (`waitMs` is the wait that did not fit, or null when the budget ran out during the wait or the read after it).+ * `onUnproven({ importJobId, status, code, why, reason })` says that the job of a refusal with SolutionConcurrencyFailure proves nothing, and in what words. The refusal of the LAST send (the fifth) is not looked into: it is+ * the sends running out, and `onExhausted({ importJobId, status, code })` says which refusal that was — of either kind — so that the failure can end with the advice that fits it (exhaustedSentence): for+ * SolutionConcurrencyFailure nothing proves that this send applied nothing, whatever the four before it proved of their own jobs.* Whatever else answers — any other status, a 429 of another kind, a gateway's 5xx, no answer, a job that exists or cannot be read — is returned as it came, and the send is the last.* Returns `{ res, sent }`: the last answer, and the request that got it, whose job id is the one to look up.*/-async function sendImport(send, options, { env, http, sleep, onRefused, onStopped }) {+async function sendImport(send, options, { env, http, sleep, onRefused, onStopped, onUnproven, onExhausted }) {// The same clock reads the HTTP-date form of Retry-After, and the budget: a test moves both at once.const clock = http.now || Date.now;let sent = options;let firstRefusedAt = null;for (let sends = 1; ; sends += 1) {const res = await send({ ...sent, timeout: ACTION_TIMEOUT_MS });- const refusal = sends < IMPORT_MAX_SENDS ? lockRefusalOf(res) : null;+ const lockRefusal = lockRefusalOf(res);+ const concurrencyRefusal = lockRefusal ? null : concurrencyRefusalOf(res);+ const refusal = lockRefusal || concurrencyRefusal;const refusedId = refusal && importJobIdOf(sent.body);if (!refusedId) return { res, sent };+ if (sends === IMPORT_MAX_SENDS) {+ // The sends have run out, so this refusal is the failure and its job is not read (the reads are for the refusals that can still be sent again): nothing proves that this send applied nothing, whatever the+ // four before it proved of their own jobs. The listener is told which refusal it was, so that the failure ends with the advice that fits it (exhaustedSentence) — for SolutionConcurrencyFailure, never a+ // manual retry that nothing has shown to be safe.+ onExhausted({ importJobId: refusedId, status: refusal.status, code: refusal.code });+ return { res, sent };+ }if (firstRefusedAt === null) firstRefusedAt = clock();+ // The job of a refusal with SolutionConcurrencyFailure is read now, before the wait: it is the proof, and a job that proves nothing makes the wait pointless. Its row does not change while the run waits.+ let proof;+ if (concurrencyRefusal) {+ const verdict = await readRefusedImportJob(env, refusedId, http);+ if (!verdict.proven) {+ onUnproven({ importJobId: refusedId, status: refusal.status, code: refusal.code, why: verdict.why, reason: verdict.reason });+ return { res, sent };+ }+ proof = verdict.proof;+ }// `Infinity`: the client's own retries cap a Retry-After at a minute (RETRY_AFTER_CAP_MS) so that a throttled build is not stalled for minutes per attempt; here the platform's request is taken as it is, and// the budget below decides whether it can be waited. A cap would turn "wait 180 s" into a send after 60, which the platform has said it will refuse.const waitMs = Math.max(IMPORT_RESEND_WAITS_MS[sends - 1], retryAfterMs(res.headers, clock(), Infinity));@@ -777,15 +868,18 @@ async function sendImport(send, options, { env, http, sleep, onRefused, onStoppereturn { res, sent };}await sleep(waitMs);- if (!(await importJobIsAbsent(env, refusedId, http))) return { res, sent };- // The read took time too (its own timeout is a minute): the budget is for the whole retry, so a send is not made after it.+ if (lockRefusal && !(await importJobIsAbsent(env, refusedId, http))) return { res, sent };+ // The budget is asked again AFTER the wait, for either refusal: the length a wait was asked for is the least it takes — a delayed timer, a busy machine, a laptop that was suspended resumes it later — and the check+ // before the wait cannot know that. For a lock code the read of its job (its own timeout is a minute) has been made by now and took time too; for 0x80071151 the job was read before the wait and says nothing+ // of the time the wait took. A send is not made after the five minutes.const spentAfterMs = clock() - firstRefusedAt;if (spentAfterMs > IMPORT_RETRY_BUDGET_MS) {onStopped({ importJobId: refusedId, waitMs: null, spentMs: spentAfterMs });return { res, sent };}const nextImportJobId = crypto.randomUUID();- onRefused({ importJobId: refusedId, status: refusal.status, code: refusal.code, waitedMs: waitMs, nextImportJobId });+ // `proof` is told only for the refusals that were proven by their job's read AT ONCE; a lock code's is the 404 after the wait, as it always was.+ onRefused({ importJobId: refusedId, status: refusal.status, code: refusal.code, waitedMs: waitMs, nextImportJobId, ...(proof ? { proof } : {}) });sent = { ...sent, body: withImportJobId(sent.body, refusedId, nextImportJobId) };}}@@ -801,10 +895,14 @@ async function sendImport(send, options, { env, http, sleep, onRefused, onStoppe* variable is) are in it, and an import needs them to know what is a secret (secrecyOf). It only listens — the answer goes on to the SDK untouched.* `observe.sanitize(text, what)` is given the transport's own words in the error of a request that got no answer ("Request timed out", a socket error): they are another party's text, so they are* looked at where they are read, and the sentence the plugin puts around them is its own and is marked as composed (COMPOSED_MESSAGE) so that it is not looked at again.- * `observe.onImportRefused({ importJobId, status, code, waitedMs, nextImportJobId })` is what turns the one exception on, and the only caller that gives it is the import, which reports what it hears:- * an ImportSolution the platform REFUSED TO START — HTTP 429 with a lock code (LOCK_REFUSAL_CODES) — is sent again when the import job its refused send carried does not exist (sendImport), and the- * listener is told of each such send before it is made. Every other answer to ImportSolution, and every answer to the other two actions, is the first and the last send.+ * `observe.onImportRefused({ importJobId, status, code, waitedMs, nextImportJobId[, proof] })` is what turns the one exception on, and the only caller that gives it is the import, which reports what it hears:+ * an ImportSolution the platform REFUSED TO START — HTTP 429 with a lock code (LOCK_REFUSAL_CODES), or with SolutionConcurrencyFailure and "Cannot start …" words — is sent again when the import job its refused+ * send carried proves that nothing was applied (sendImport), and the listener is told of each such send before it is made — with `proof` (lib/import-job-proof.js: PROOF_ABSENT or PROOF_LOG) for the refusals+ * that were proven by the read of the job at once. Every other answer to ImportSolution, and every answer to the other two actions, is the first and the last send.* `observe.onImportRetryStopped({ importJobId, waitMs, spentMs })` is told when that retry ends for want of time, with the refusal it ends on (IMPORT_RETRY_BUDGET_MS, see sendImport).+ * `observe.onImportRetryUnproven({ importJobId, status, code, why, reason })` is told when it ends because the job of a refusal with SolutionConcurrencyFailure does not prove that nothing was applied.+ * `observe.onImportRetryExhausted({ importJobId, status, code })` is told when the sends run out on a refusal — the fifth send's, of either kind — whose job is not read: the failure then ends with the advice for that+ * kind (exhaustedSentence; for SolutionConcurrencyFailure, what the job must show before the import is run again).*/function solutionHttpClient(env, deps = {}, observe = {}) {const send = deps.request || makeRequest;@@ -816,7 +914,7 @@ function solutionHttpClient(env, deps = {}, observe = {}) {const action = LONG_ACTION.exec(new URL(options.url).pathname);if (!action) return send(options);const { res, sent } = action[1] === 'ImportSolution' && typeof observe.onImportRefused === 'function'- ? await sendImport(send, options, { env, http: deps, sleep, onRefused: observe.onImportRefused, onStopped: observe.onImportRetryStopped || (() => {}) })+ ? await sendImport(send, options, { env, http: deps, sleep, onRefused: observe.onImportRefused, onStopped: observe.onImportRetryStopped || (() => {}), onUnproven: observe.onImportRetryUnproven || (() => {}), onExhausted: observe.onImportRetryExhausted || (() => {}) }): { res: await send({ ...options, timeout: ACTION_TIMEOUT_MS }), sent: options };if (!res.error) {if (action[1] === 'StageSolution' && observe.onStageReply) observe.onStageReply(res.body);@@ -1272,23 +1370,53 @@ async function importFailure(err, { sanitize, settings, importJobId, env, deps,}}// The plugin's own sentences, appended after the platform's words were sanitized and, like the ones above, not looked at again: they hold counts, ids it minted and the code it matched — no value.- if (resent) failure.message += ` ${resendSentence(sends)}${original.statusCode === 429 && sends.refusals.length + 1 === IMPORT_MAX_SENDS ? ` It sends at most ${IMPORT_MAX_SENDS} times: run the import again when the other operation has finished.` : ''}`;+ if (resent) failure.message += ` ${resendSentence(sends)}`;+ if (sends && sends.exhausted) failure.message += ` ${exhaustedSentence(sends.exhausted)}`;if (sends && sends.stopped) failure.message += ` ${stoppedSentence(sends.stopped)}`;+ if (sends && sends.unproven) failure.message += ` ${unprovenSentence(sends.unproven)}`;return failure;}// What a run that sent its import again reports, in the output: how many sends it took (`importAttempts`), and each send that was refused and waited out (`importRefusals`) — the job it carried,-// the status and the code of the refusal, and how long the run waited before the next send. The last send is the output's own `importJobId`. Nothing but numbers, ids the plugin minted and the-// code it matched: no word of the platform's, so nothing in it needs the sanitizer.+// the status and the code of the refusal, how long the run waited before the next send and, for a refusal with SolutionConcurrencyFailure, how its job proved that nothing was applied (`proof`: PROOF_ABSENT+// or PROOF_LOG, see lib/import-job-proof.js). The last send is the output's own `importJobId`. Nothing but numbers, ids the plugin minted and the code it matched: no word of the platform's, so nothing in it+// needs the sanitizer.const resendReport = (sends) => (sends.refusals.length > 0 ? { importAttempts: sends.refusals.length + 1, importRefusals: sends.refusals } : {});const secondsOf = (ms) => `${Math.round(ms / 100) / 10} s`;-const resendSentence = (sends) => `ImportSolution was sent ${sends.refusals.length + 1} times. Each send before the last was refused before it started (HTTP 429, code ${[...new Set(sends.refusals.map((refusal) => refusal.code))].join(', ')}: another operation held the environment's customization lock) and the job it named did not exist (importjobs(<id>) answered 404). The run waited ${sends.refusals.map((refusal) => secondsOf(refusal.waitedMs)).join(', ')} before sending again.`;-// Why a retry that the platform's refusal asked for was not made: the wait it asks for does not fit in what is left of IMPORT_RETRY_BUDGET_MS (`waitMs`), or the time went on the read that proves the refused send did not-// start (`waitMs` null). Numbers only, like the sentences above.+// Why each send before the last was safe to repeat. A refusal whose job did not exist says what it always said. One whose job EXISTED — two imports that started together: the job is made once the lock is held+// for the first time and says, in its log, that the import failed with the concurrency error before it processed the solution or any component — says that, and a run that met both says both.+const LOG_SHOWED = 'held the log of an import that failed with that error before it processed the solution or any component';+const resendSentence = (sends) => {+ const codes = [...new Set(sends.refusals.map((refusal) => refusal.code))].join(', ');+ const waits = sends.refusals.map((refusal) => secondsOf(refusal.waitedMs)).join(', ');+ const total = sends.refusals.length + 1;+ if (!sends.refusals.some((refusal) => refusal.proof === PROOF_LOG)) {+ return `ImportSolution was sent ${total} times. Each send before the last was refused before it started (HTTP 429, code ${codes}: another operation held the environment's customization lock) and the job it named did not exist (importjobs(<id>) answered 404). The run waited ${waits} before sending again.`;+ }+ const alsoAbsent = sends.refusals.some((refusal) => refusal.proof !== PROOF_LOG);+ const shown = alsoAbsent ? `importjobs(<id>) answered 404, or ${LOG_SHOWED}` : `importjobs(<id>) ${LOG_SHOWED}`;+ return `ImportSolution was sent ${total} times. Each send before the last was refused at the environment's customization lock (HTTP 429, code ${codes}: another operation held it) before any of the package was applied, and its import job showed it: ${shown}. The run waited ${waits} before sending again.`;+};+// Why a retry that the platform's refusal asked for was not made: the wait it asks for does not fit in what is left of IMPORT_RETRY_BUDGET_MS (`waitMs`), or the time ran out during the wait itself (a timer that+// resumed late) or the read after it that proves a lock code's refused send did not start (`waitMs` null). Numbers only, like the sentences above. Its advice holds for both kinds of refusal: the job of a refusal with+// SolutionConcurrencyFailure is read and proven BEFORE the wait (one that proves nothing is unprovenSentence's), and for a lock code it is the advice the retry always gave.const RETRY_BUDGET_TEXT = `${IMPORT_RETRY_BUDGET_MS / 60000} minutes`;const stoppedSentence = ({ waitMs, spentMs }) => `ImportSolution was not sent again: ${waitMs === null? `the ${RETRY_BUDGET_TEXT} this run spends in all on sending it again were used up (${secondsOf(spentMs)}) before the next send`: `the next wait, ${secondsOf(waitMs)}, does not fit in what is left of the ${RETRY_BUDGET_TEXT} this run spends in all on sending it again (${secondsOf(spentMs)} are spent)`}. Run the import again when the other operation has finished.`;+// Why a refusal with SolutionConcurrencyFailure was not sent again: the platform refused it, but its job does not prove that the refused send applied nothing of the package (`reason`: lib/import-job-proof.js, fixed+// words and numbers only). The sentence says what to do — look at the job, and import again only when it shows nothing was imported — because the import may have started: sending it again would be a second copy.+const unprovenSentence = ({ importJobId, code, reason }) => `ImportSolution was not sent again: the platform refused it (HTTP 429, code ${code}: another operation held the environment's customization lock), but ${reason}, so it is not proven that the refused send applied nothing of the package. Look up import job ${importJobId} (importjobs(${importJobId}) in the Web API, or the solution history in Maker) and run the import again only when that shows nothing was imported and the other operation has finished.`;+// What a failure says when the sends ran out (IMPORT_MAX_SENDS) on a refusal — the fifth send's, whose job is not read, since the reads are for the refusals that can still be sent again, and the proofs of the sends+// before it are of other jobs. It depends on what the code says of that send:+// - a lock code: the documented text of those codes says the operation could not be STARTED, and this is the advice a retry that ran out of sends has always ended with;+// - SolutionConcurrencyFailure: its documented text says an installation FAILED, and only the job of the send could say that nothing was applied. Nothing looked at it, so the failure never says "run the import again"+// outright: it says what to look up, and by what rule — the one that decided every earlier send (lib/import-job-proof.js: the job does not exist, or it is finished and its log says the import failed with this error+// before it processed the solution or any component) — and that anything else means the import may be running or may have applied the package, which a second copy would repeat.+// A fifth answer of any other kind (another 429, the code with other words) is not a refusal the retry knows: it is told of nothing and is judged like a first send, with the platform's own words and no advice.+const exhaustedSentence = ({ importJobId, code }) => (code === CONCURRENCY_REFUSAL_CODE+ ? `The last send was refused too (code ${code}), but this run sends the import ${IMPORT_MAX_SENDS} times at most and did not look at its import job, so it is not proven that it applied nothing of the package. Look up import job ${importJobId} (importjobs(${importJobId}) in the Web API, or the solution history in Maker) and run the import again only when that job does not exist (a 404), or is finished and its log says the import failed with that error before it processed the solution or any component, and the other operation has finished. Anything else means that the import may be running or may have applied the package: do not run it again.`+ : `It sends at most ${IMPORT_MAX_SENDS} times: run the import again when the other operation has finished.`);// `text` with every access token in `tokens` taken out of it, whole and by each long part of it (the Dataverse client's own scrubber: lib/sdk-http-client.js).const scrubTokens = (text, tokens) => [...tokens].reduce((out, token) => scrub(out, token), String(text));@@ -1373,17 +1501,20 @@ async function runImport(asked, given = {}) {const { base64 } = inspectPackage(request.packagePath, { withBytes: true });const importJobId = deps.importJobId || crypto.randomUUID();// The import's sends, as the client tells of them (solutionHttpClient's `onImportRefused`): `jobId` is the job the last send carried — the first send's until a refusal is sent again. `stopped` is what it- // says when the retry ends for want of time (`onImportRetryStopped`): the refusal it ended on is then the failure, and the sentence that says why is added to it (importFailure).- const sends = { jobId: importJobId, refusals: [], stopped: null };- const onImportRefused = ({ importJobId: refused, status, code, waitedMs, nextImportJobId }) => {- sends.refusals.push({ importJobId: refused, status, code, waitedMs });+ // says when the retry ends for want of time (`onImportRetryStopped`), `unproven` what it says when it ends because the job of a refusal proves nothing (`onImportRetryUnproven`): the refusal it ended on+ // is then the failure, and the sentence that says why is added to it (importFailure) — and `exhausted` what it says when the sends run out on a refusal whose job was not read (`onImportRetryExhausted`).+ const sends = { jobId: importJobId, refusals: [], stopped: null, unproven: null, exhausted: null };+ const onImportRefused = ({ importJobId: refused, status, code, waitedMs, nextImportJobId, proof }) => {+ sends.refusals.push({ importJobId: refused, status, code, waitedMs, ...(proof ? { proof } : {}) });sends.jobId = nextImportJobId;};const onImportRetryStopped = (event) => { sends.stopped = event; };+ const onImportRetryUnproven = (event) => { sends.unproven = event; };+ const onImportRetryExhausted = (event) => { sends.exhausted = event; };try {const outcome = await (deps.sdkFirst || sdkFirst)(request.env, {refusal: (error) => importRefusal(error, settings),- httpClient: (env) => solutionHttpClient(env, deps.http, { onStageReply: (body) => recordStagedTypes(definitions, body), sanitize, onImportRefused, onImportRetryStopped }),+ httpClient: (env) => solutionHttpClient(env, deps.http, { onStageReply: (body) => recordStagedTypes(definitions, body), sanitize, onImportRefused, onImportRetryStopped, onImportRetryUnproven, onImportRetryExhausted }),fromSdk: (sdk) => sdk.importSolution({base64,// pac's defaults: --force-overwrite and --activate-plugins are off. Both are required by the SDK, which no longer defaults them.@@ -1446,6 +1577,7 @@ async function main() {guardOutput(tokens);const { request, error } = readRequest(process.argv.slice(2));if (error) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${error}\n${USAGE}\n`);process.exit(1);}@@ -1487,6 +1619,7 @@ module.exports = {pacOnlyFeatureMessages,solutionHttpClient,lockRefusalOf,+ concurrencyRefusalOf,LOCK_REFUSAL_CODES,IMPORT_MAX_SENDS,IMPORT_RESEND_WAITS_MS,@@ -1504,6 +1637,7 @@ module.exports = {if (require.main === module) {main().catch((err) => {// Only the kind of failure: the message of an unexpected one is not known to be free of what the settings file holds, and this runs where no sanitizer exists.+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`Error: solution-settings.js failed unexpectedly (${(err && err.name) || 'Error'}).\n`);process.exit(1);});diff --git a/plugins/model-apps/scripts/teardown-model-app.js b/plugins/model-apps/scripts/teardown-model-app.jsindex a4abf7653..631111aa1 100644--- a/plugins/model-apps/scripts/teardown-model-app.js+++ b/plugins/model-apps/scripts/teardown-model-app.js@@ -29,6 +29,7 @@ const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/datconst snapStore = require('./lib/apply-snapshot-store.js');const { checkPageOwnershipClearable } = require('./lib/page-ownership-records.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// Build an SDK client for teardown. Uses the same az-token HttpClient as build-model-app.js.async function makeSdk(env) {@@ -194,6 +195,7 @@ async function main() {needValue: ['env', 'spec', 'workspace'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -247,6 +249,8 @@ async function main() {beforeRename: () => requireDisposable(clearable.target),beforeRemove: requireDisposable,}) : clearable;+ // The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);if (cleared.ok) {process.stderr.write(`\ncleared workspace ${clearable.target}${cleared.leftover ? ` (${cleared.reason})` : ''}\n`);} else {diff --git a/plugins/model-apps/scripts/tests/agent-task-tracking.test.js b/plugins/model-apps/scripts/tests/agent-task-tracking.test.jsnew file mode 100644index 000000000..f0dd0710f--- /dev/null+++ b/plugins/model-apps/scripts/tests/agent-task-tracking.test.js@@ -0,0 +1,157 @@+'use strict';+// Task tracking is optional for an agent. A host that recognizes the `todo` alias has not thereby handed a subagent a+// task tool: a Copilot CLI session gave genpage-page-builder only view, create, edit and grep although its frontmatter+// declares TaskCreate, TaskUpdate and todo. An agent whose steps say "call TaskCreate" and nothing else has an+// instruction it can only skip or fake, and the model improvises. Agent files are prose to every other test, so the+// wording that says what to do without a task tool is pinned here.+// See references/agent-interaction-contract.md -> "A declared tool is not always a delivered one".+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const PLUGIN = path.join(__dirname, '..', '..');+const AGENTS = path.join(PLUGIN, 'agents');++// Line endings normalized, as in the other document tests: a Windows checkout turns them into CRLF.+const readDoc = (p) => fs.readFileSync(p, 'utf8').replace(/\r\n/g, '\n');+const squash = (s) => s.replace(/\s+/g, ' ');++// An agent's instructions: everything after its frontmatter, which names the tools in comments and in the list.+function instructionsOf(text) {+ const lines = text.split('\n');+ assert.equal(lines[0], '---', 'an agent file starts with its frontmatter');+ const end = lines.indexOf('---', 1);+ assert.ok(end > 0, 'the frontmatter is closed');+ return lines.slice(end + 1).join('\n');+}++// The sections of a document (a heading and what follows up to the next heading), each with its fenced code blocks+// taken out: a fence holds a template or an example, and a tool named inside one is not an instruction to use it.+// A heading-looking line inside a fence is not a heading either (the planner's plan template has several).+function sectionsOf(instructions) {+ const sections = [{ heading: '(start)', lines: [] }];+ let inFence = false;+ for (const line of instructions.split('\n')) {+ if (/^\s*```/.test(line)) {+ inFence = !inFence;+ continue;+ }+ if (inFence) continue;+ if (/^#{1,6}\s/.test(line)) sections.push({ heading: line.trim(), lines: [] });+ else sections[sections.length - 1].lines.push(line);+ }+ return sections.map((s) => ({ heading: s.heading, text: squash(s.lines.join('\n')) }));+}++// Headings of the sections that tell the reader to use a task tool without saying what to do with none. A section+// "tells" the reader when it names TaskCreate or TaskUpdate; it says what to do with none when it opens that case+// ("If you have a task tool") and closes it ("never say you created a task").+function unconditionalTaskToolSections(instructions) {+ return sectionsOf(instructions)+ .filter((s) => /\bTask(?:Create|Update)\b/.test(s.text))+ .filter((s) => !(/If you have a task tool/.test(s.text) && /never say you created a task/.test(s.text)))+ .map((s) => s.heading);+}++test('the check finds a step that uses a task tool with no alternative, and passes one that has it', () => {+ const unconditional = '## Step 4 — Create a Task\n\nCall `TaskCreate` for: "Generate page"\n\nMark it as in_progress immediately.\n';+ assert.deepEqual(unconditionalTaskToolSections(unconditional), ['## Step 4 — Create a Task']);++ const conditional = [+ '## Step 4 — Track the Page',+ '',+ '- **If you have a task tool** (`TaskCreate`/`TaskUpdate`): create the task.',+ '- **If you have none**: skip it and never say you created a task.',+ '',+ ].join('\n');+ assert.deepEqual(unconditionalTaskToolSections(conditional), []);++ // A tool named in a code fence is a template value, not an instruction; a section that names no tool is not judged.+ const fenced = '## Step 7\n\nReturn:\n\n```\nTask tool: [TaskCreate/TaskUpdate | todo]\n```\n\n## Other\n\nUse `todo` if you like.\n';+ assert.deepEqual(unconditionalTaskToolSections(fenced), []);++ // Both halves are needed: naming the tool and promising to skip it is not the same as saying when.+ const half = '## Step 4\n\nCall `TaskCreate`, and never say you created a task you did not.\n';+ assert.deepEqual(unconditionalTaskToolSections(half), ['## Step 4']);+});++const AGENT_FILES = fs.readdirSync(AGENTS).filter((f) => f.endsWith('.md')).sort();++test('every agent that tracks its work with a task tool says what to do when it has none', () => {+ const tracking = [];+ const offenders = [];+ for (const file of AGENT_FILES) {+ const instructions = instructionsOf(readDoc(path.join(AGENTS, file)));+ if (/\bTaskCreate\b/.test(instructions)) tracking.push(file);+ for (const heading of unconditionalTaskToolSections(instructions)) offenders.push(`${file}: ${heading}`);+ }+ assert.deepEqual(offenders, [], 'these steps name TaskCreate/TaskUpdate without saying what to do with no task tool');+ // The check had something to judge: a set of agents that stopped naming the tool would pass it for nothing.+ assert.ok(tracking.includes('genpage-page-builder.md'), `the page builder names the task tool (agents that do: ${tracking.join(', ')})`);+});++test('the page builder tracks its page with a task tool only if it has one, and in plain words when it has none', () => {+ const instructions = instructionsOf(readDoc(path.join(AGENTS, 'genpage-page-builder.md')));+ const step4 = sectionsOf(instructions).find((s) => /^## Step 4\b/.test(s.heading));+ assert.ok(step4, 'Step 4 is where it was');+ assert.match(step4.heading, /Track the Page/);++ // The tool case: unchanged behaviour where a task tool exists.+ assert.match(step4.text, /\*\*If you have a task tool\*\* \(`TaskCreate`\/`TaskUpdate` on Claude Code, `todo` where Copilot provides it\): create the task and mark it `in_progress`\./);+ // The case the Copilot CLI hit: nothing to call, nothing to search for, nothing to claim.+ assert.match(step4.text, /\*\*If you have none\*\*: do not search for one, do not call a tool you were not given, and never say you created a task\./);+ assert.match(step4.text, /Open your first message with `Task: Generate \[Page Name\] page — in progress` instead; Step 7 closes it\./);+ assert.match(step4.text, /check the tools you were actually given, once/);+ assert.match(step4.text, /Copilot CLI session gives this agent only its file and search tools/);++ assert.doesNotMatch(squash(instructions), /Call `TaskCreate` for:/, 'no unconditional call to TaskCreate is left');+ assert.doesNotMatch(squash(instructions), /Mark it as in_progress immediately/);+});++test('the page builder\'s result closes the task, says which tool tracked it, and keeps the lines the orchestrators read', () => {+ const instructions = readDoc(path.join(AGENTS, 'genpage-page-builder.md'));+ const step7 = instructions.split(/^## Step 7 — Return Result$/m)[1].split(/^## Critical Constraints$/m)[0];+ assert.match(squash(step7), /Close the task from Step 4 \(mark it complete if you have a task tool\)\./);+ const block = /```\n([\s\S]*?)\n```/.exec(step7);+ assert.ok(block, 'the result template is a code block');+ assert.deepEqual(block[1].split('\n'), [+ 'Page: [Page Name]',+ 'File: [working directory]/[filename].tsx',+ 'Status: Written',+ 'Task: Generate [Page Name] page — complete',+ 'Task tool: [TaskCreate/TaskUpdate | todo | none on this host]',+ ]);+});++test('the frontmatter still declares the task tool in both naming schemes, and says a declaration is not delivery', () => {+ const text = readDoc(path.join(AGENTS, 'genpage-page-builder.md'));+ const frontmatter = text.split('\n---\n')[0];+ const tools = frontmatter.split('\n').filter((l) => /^\s+- \S+$/.test(l)).map((l) => l.replace(/^\s+- /, ''));+ for (const name of ['TaskCreate', 'TaskUpdate', 'todo']) assert.ok(tools.includes(name), `${name} stays declared`);+ // The explanation lives in the frontmatter's own comment block, one `# ` per line.+ const comment = squash(frontmatter.split('\n').filter((l) => l.startsWith('#')).map((l) => l.replace(/^#\s?/, '')).join('\n'));+ assert.match(comment, /a Copilot CLI session gave this agent no task tool at all, so Steps 4 and 7 say what to do without one/);+});++test('the interaction contract explains that a declared tool is not always a delivered one', () => {+ const doc = squash(readDoc(path.join(PLUGIN, 'references', 'agent-interaction-contract.md')));+ // assert.ok with a message: a failed assert.match would print the whole document.+ const says = (re, what) => assert.ok(re.test(doc), `the contract must say ${what}`);+ says(/## A declared tool is not always a delivered one/, 'it has a section on a declared tool that is not delivered');+ says(/Declaring a capability in both schemes makes a host \*recognize\* it\. It does not make the host \*hand it to a subagent\*\./, 'that a declaration is recognized, not delivered');+ says(/So an agent never \*depends\* on a task tool\./, 'that an agent never depends on a task tool');+ says(/agent-task-tracking\.test\.js/, 'which test pins the wording');+});++// The page builder's result now says which tool tracked its task. The /genpage orchestrator already sends a worker+// that reports missing file or process tools to the inline fallback; a worker with no task tool must not be read as+// one of those, or a page that was written would be written again.+test('the genpage orchestrator does not treat a worker without a task tool as a failed worker', () => {+ const skill = squash(readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md')));+ assert.match(skill, /A `Task tool: none on this host` line in a worker's result is not a report of that kind: task tracking is optional for a worker \(`references\/agent-interaction-contract\.md`\), and the page is judged by its file and this gate\./);+ // It sits in the paragraph that defines the inline fallback, so "that kind" is the missing-tool report just before it.+ const at = skill.indexOf('A `Task tool: none on this host` line');+ assert.match(skill.slice(Math.max(0, at - 500), at), /If a worker reported missing declared file\/process tools, produced no file/);+ assert.match(skill.slice(Math.max(0, at - 500), at), /This is the same inline fallback path for missing and invalid worker output\.\s*$/);+});diff --git a/plugins/model-apps/scripts/tests/app-access.test.js b/plugins/model-apps/scripts/tests/app-access.test.jsnew file mode 100644index 000000000..5a8ee5f5d--- /dev/null+++ b/plugins/model-apps/scripts/tests/app-access.test.js@@ -0,0 +1,183 @@+'use strict';+// lib/app-access.js: what an App Spec says about two different questions the plugin used to answer as one — who can open the APP (the roles+// associated with it) and who can use the TABLES the spec introduces (the privileges personas[] and roleGrants[] give). Pure: the lint and the design+// document both read the spec through it, so they cannot disagree about which tables nothing grants or which marks say an app already exists.+const { test } = require('node:test');+const assert = require('node:assert/strict');+const access = require('../lib/app-access.js');+const { extensionSpec, newAppSpec, grant, persona } = require('./helpers/app-access-specs.js');++const { existingAppMarkers, introducedTables, tablePrivileges, uncoveredTables } = access;+const GUID = '11111111-2222-3333-4444-555555555555';++test('the marks of an existing app are the three a download writes — the app\u2019s unique name, a page id, a dashboard id — in a fixed order', () => {+ assert.deepEqual(existingAppMarkers(newAppSpec()), []);+ assert.deepEqual(existingAppMarkers(extensionSpec()), ['app.uniqueName']);+ const all = extensionSpec();+ all.dashboards = [{ name: 'Overview', dashboardId: GUID, tiles: [] }];+ all.pages = [{ key: 'home', name: 'Home', pageId: GUID }, { key: 'detail', name: 'Detail', pageId: GUID }];+ assert.deepEqual(existingAppMarkers(all), ['app.uniqueName', 'pages[].pageId', 'dashboards[].dashboardId'], 'each named once, whatever the count');+});++test('a mark counts only when it holds a value: a blank or non-string one is the shape of a spec still being typed', () => {+ const s = newAppSpec();+ s.app.uniqueName = ' ';+ s.pages = [{ key: 'a', name: 'A', pageId: '' }, { key: 'b', name: 'B', pageId: 42 }, null, 'x'];+ s.dashboards = [{ name: 'D', dashboardId: null }, null];+ assert.deepEqual(existingAppMarkers(s), []);+ for (const bad of [null, undefined, 'x', 7, [], { app: 'x' }, { pages: 'x', dashboards: {} }]) assert.deepEqual(existingAppMarkers(bad), []);+});++test('the tables a spec introduces are its entities that are not marked existing, named as written', () => {+ const s = extensionSpec({ newTables: ['Contoso_Baseline', 'contoso_risk'] });+ assert.deepEqual(introducedTables(s), ['Contoso_Baseline', 'contoso_risk']);+ s.entities.push(null, 'x', {}, { schemaName: ' ' }, { schemaName: 5 }, { schemaName: 'contoso_kept', existing: true });+ assert.deepEqual(introducedTables(s), ['Contoso_Baseline', 'contoso_risk']);+ for (const bad of [null, undefined, {}, { entities: {} }, { entities: 'x' }]) assert.deepEqual(introducedTables(bad), []);+});++test('privileges are read from persona jobs, persona additionalPrivileges and roleGrants[], by logical name', () => {+ const s = newAppSpec({ tables: ['contoso_ticket', 'contoso_note'] });+ s.personas = [persona(' Agent ', [{ entity: 'Contoso_Ticket', access: ['read', 'write'], scope: 'businessUnit' }], { additionalPrivileges: [{ entity: 'contoso_note', access: ['read'] }] })];+ s.roleGrants = [grant('Contoso PM - Viewer', 'contoso_note', ['read'], 'organization'), grant(GUID, 'contoso_ticket', ['append'])];+ const map = tablePrivileges(s);+ assert.deepEqual([...map.keys()].sort(), ['contoso_note', 'contoso_ticket']);+ assert.deepEqual(map.get('contoso_ticket'), [+ { via: 'persona', role: 'Agent', access: ['read', 'write'], scope: 'businessUnit' },+ { via: 'roleGrant', role: GUID, access: ['append'], scope: 'organization' },+ ]);+ assert.deepEqual(map.get('contoso_note'), [+ { via: 'persona', role: 'Agent', access: ['read'], scope: 'user' },+ { via: 'roleGrant', role: 'Contoso PM - Viewer', access: ['read'], scope: 'organization' },+ ]);+});++test('a privilege that grants nothing — no access, no table, not an object — is not a source', () => {+ const s = extensionSpec();+ s.personas = [{ persona: 'P', jobs: [{ name: 'j', privileges: [null, 'x', { entity: 'contoso_baseline' }, { entity: 'contoso_baseline', access: [] }, { entity: 5, access: ['read'] }, { access: ['read'] }] }], additionalPrivileges: 'x' }];+ s.roleGrants = [null, 'x', {}, { role: 'R' }, { role: 'R', privileges: 'x' }, { role: 'R', privileges: [{ entity: 'contoso_baseline', access: [] }] }];+ assert.equal(tablePrivileges(s).size, 0);+ assert.deepEqual(uncoveredTables(s), ['contoso_baseline']);+ assert.equal(tablePrivileges({ roleGrants: {} }).size, 0);+ assert.equal(tablePrivileges(null).size, 0);+});++test('an uncovered table is an introduced one that no source names, in the order the spec lists them', () => {+ const s = extensionSpec({ newTables: ['contoso_b', 'contoso_a', 'contoso_c'] });+ s.roleGrants = [grant('R', 'CONTOSO_A')];+ assert.deepEqual(uncoveredTables(s), ['contoso_b', 'contoso_c']);+ s.roleGrants.push({ role: 'S', privileges: [{ entity: 'contoso_b', access: ['read'] }, { entity: 'contoso_c', access: ['read'] }] });+ assert.deepEqual(uncoveredTables(s), []);+ assert.deepEqual(uncoveredTables(extensionSpec({ newTables: [] })), []);+});++test('the sentences the lint and the document share say the same thing in both', () => {+ const lint = require('../lib/spec-lint.js').lintAppSpec(extensionSpec());+ const gap = require('../write-app-spec-doc.js').designGaps(extensionSpec()).find((g) => /no access declared/.test(g));+ const flagged = lint.warnings.find((w) => /no access declared/.test(w));+ assert.ok(flagged && gap, 'both flag the table');+ assert.equal(gap, flagged, 'in the same words');+});++// --- the personas' share of who can open the app ------------------------------------------------------------------------------------------++const { personaAppAccess, appAccessModel, appAccessCondition } = access;+const ID_1 = '00000000-0000-4000-8000-000000000001';+const ID_2 = '00000000-0000-4000-8000-000000000002';+const ID_3 = '00000000-0000-4000-8000-000000000003';+const roleRows = (...rows) => ({ state: 'read', appUnique: 'contoso_pm', roles: rows.map(([roleId, name]) => ({ roleId, name, managed: false })) });++test('a persona gets the app unless its appAccess is false — the build\u2019s own rule — and is named by its trimmed name, once', () => {+ const s = newAppSpec();+ s.personas = [+ persona(' Agent ', []), persona('Planner', [], { appAccess: true }), persona('Reader', [], { appAccess: false }),+ persona('agent', []), persona('Odd', [], { appAccess: 'false' }),+ null, 'x', { persona: ' ' }, { jobs: [] },+ ];+ assert.deepEqual(personaAppAccess(s), { gets: ['Agent', 'Planner', 'Odd'], optedOut: ['Reader'] }, 'only a boolean false opts out, as in sdk-build.js: persona.appAccess !== false');+ for (const bad of [null, undefined, 'x', {}, { personas: {} }, { personas: 'x' }]) assert.deepEqual(personaAppAccess(bad), { gets: [], optedOut: [] });+});++test('the sentence on who can open the app says what a build does for the personas, and what it leaves, whether the spec has personas or not', () => {+ const marked = (spec) => { spec.app.uniqueName = 'contoso_support'; return spec; };+ const withPersonas = (...personas) => { const spec = newAppSpec(); spec.personas = personas; return spec; };+ // No personas: nothing is said of them.+ assert.match(appAccessCondition(newAppSpec()), /^If the app is new, it is associated with the System Administrator role only/);+ assert.doesNotMatch(appAccessCondition(newAppSpec()), /persona `/);+ // Personas that get the app, those that opt out, both: what a build does for them, then what it does for every other role.+ const gets = appAccessCondition(withPersonas(persona('Agent', [])));+ assert.match(gets, /^A build associates the app with the role of persona `Agent`\. Beyond that, a new app is associated with the System Administrator role only, and an existing app keeps the roles it has\.$/);+ assert.doesNotMatch(gets, /personas\[\] does that/, 'it has one');+ const out = appAccessCondition(withPersonas(persona('Reader', [], { appAccess: false })));+ assert.match(out, /^No persona gets the app: a build removes the app from the role of persona `Reader` \(`appAccess: false`\) if it has it\./);+ const both = appAccessCondition(withPersonas(persona('Agent', []), persona('Planner', []), persona('Reader', [], { appAccess: false })));+ assert.match(both, /^A build associates the app with the roles of personas `Agent` and `Planner`, and removes it from the role of persona `Reader` \(`appAccess: false`\) if it has it\./);+ // An app that carries a download's marks: the roles are left as they are, but for the personas'.+ assert.match(appAccessCondition(marked(withPersonas(persona('Agent', [])))), /A build associates the app with the role of persona `Agent`\. It carries app\.uniqueName, which a download writes, so it most likely edits an app that already exists — and a build changes the roles associated with an existing app only for its personas: who else can open the app is decided by the environment, not by this spec\.$/);+ assert.match(appAccessCondition(marked(newAppSpec())), /and a build leaves the roles associated with an existing app as they are: who can open the app is decided by the environment, not by this spec\.$/);+});++test('without an answer from the environment — or one that is not one — the model says so, and still says who gets the app', () => {+ const s = newAppSpec();+ s.personas = [persona('Agent', []), persona('Reader', [], { appAccess: false })];+ for (const answer of [undefined, null, 'x', 7, [], {}, { state: 'nonsense' }]) {+ assert.deepEqual(appAccessModel(s, answer), { state: 'unread', personas: { gets: ['Agent'], optedOut: ['Reader'] } }, JSON.stringify(answer));+ }+ assert.deepEqual(appAccessModel(s, { state: 'absent', appUnique: 'x' }), { state: 'absent', appUnique: 'x', personas: { gets: ['Agent'], optedOut: ['Reader'] } });+ assert.deepEqual(appAccessModel(s, { state: 'unreadable', appUnique: 'x', reason: 'HTTP 403' }), { state: 'unreadable', appUnique: 'x', reason: 'HTTP 403', personas: { gets: ['Agent'], optedOut: ['Reader'] } });+ assert.equal(appAccessModel(s, { state: 'unreadable' }).reason, 'unknown');+});++// --- which associated role a grant or a persona is --------------------------------------------------------------------------------------++test('a role a grant names by its id is that role; a role it names only by name is a candidate — never a certain match, and every candidate is listed', () => {+ const spec = extensionSpec();+ spec.roleGrants = [+ grant(ID_1, 'contoso_baseline'),+ { ...grant('Viewer', 'contoso_baseline'), businessUnitId: '11111111-1111-4111-8111-111111111111' },+ ];+ const model = appAccessModel(spec, roleRows([ID_1, 'Project Manager'], [ID_2, 'Viewer'], [ID_3, 'viewer'], ['00000000-0000-4000-8000-000000000004', 'Auditor']));+ assert.equal(model.state, 'read');+ assert.deepEqual(model.roles.map((r) => [r.name, r.sources]), [+ ['Project Manager', [{ kind: 'roleGrant', label: ID_1, by: 'id', certain: true }]],+ ['Viewer', [{ kind: 'roleGrant', label: 'Viewer', by: 'name', certain: false }]],+ ['viewer', [{ kind: 'roleGrant', label: 'Viewer', by: 'name', certain: false }]],+ ['Auditor', []],+ ]);+ assert.deepEqual(model.grants, [+ { label: ID_1, by: 'id', status: 'associated', candidates: [{ roleId: ID_1, name: 'Project Manager' }] },+ { label: 'Viewer', by: 'name', status: 'maybe', candidates: [{ roleId: ID_2, name: 'Viewer' }, { roleId: ID_3, name: 'viewer' }] },+ ]);+});++test('a grant by id never matches a role by its name, and a grant by name never matches by id: a role of that name in another business unit is not that role', () => {+ const spec = extensionSpec();+ spec.roleGrants = [grant(ID_1, 'contoso_baseline')];+ const model = appAccessModel(spec, roleRows([ID_2, 'Viewer']));+ assert.deepEqual(model.roles[0].sources, []);+ assert.deepEqual(model.grants, [{ label: ID_1, by: 'id', status: 'not-associated', candidates: [] }]);+ const byName = extensionSpec();+ byName.roleGrants = [grant('Auditor', 'contoso_baseline')];+ assert.deepEqual(appAccessModel(byName, roleRows([ID_2, 'Viewer'])).grants, [{ label: 'Auditor', by: 'name', status: 'not-associated', candidates: [] }]);+ assert.deepEqual(appAccessModel(byName, roleRows([ID_2, 'Auditor'])).grants.map((g) => g.status), ['maybe'], 'the id is no way to tell that grant\u2019s role from this one');+});++test('a persona is matched to an associated role by name only, so it is never a certain match, and what the build does to it follows the persona\u2019s appAccess', () => {+ const spec = newAppSpec();+ spec.personas = [persona('Agent', []), persona('Reader', [], { appAccess: false })];+ const model = appAccessModel(spec, roleRows([ID_1, 'AGENT'], [ID_2, 'reader'], [ID_3, 'Other']));+ assert.deepEqual(model.roles.map((r) => r.sources), [+ [{ kind: 'persona', label: 'Agent', getsApp: true, certain: false }],+ [{ kind: 'persona', label: 'Reader', getsApp: false, certain: false }],+ [],+ ]);+});++test('an answer that lists a role with no usable id is no answer: the model says it was not read, never that there are no roles', () => {+ for (const roles of ['x', [null], [{}], [{ name: 'Viewer' }], [{ roleId: 5, name: 'Viewer' }], [{ roleId: ID_1, name: 'Viewer' }, null]]) {+ const model = appAccessModel(extensionSpec(), { state: 'read', appUnique: 'contoso_pm', roles });+ assert.equal(model.state, 'unreadable', JSON.stringify(roles));+ assert.match(model.reason, /list of roles|names no role/, JSON.stringify(roles));+ }+ assert.deepEqual(appAccessModel(extensionSpec(), { state: 'read', appUnique: 'contoso_pm', roles: [] }).roles, [], 'a list with nothing in it is the one answer that says there are none');+});diff --git a/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.jsindex a166aa4d4..33ffa68b8 100644--- a/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js@@ -181,8 +181,7 @@ test('REAL BUNDLE: an app with none has no key, refuses an update, and gets it Aassert.strictEqual(res.saved, true, JSON.stringify(res.error && res.error.message));const header = headerWrites(writes);assert.strictEqual(header.length, 1, 'one header write');- assert.strictEqual(header[0].body.aiappdescription, WANT);- assert.strictEqual(header[0].body.description, 'Tickets', 'the tile description rides through unchanged');+ assert.deepStrictEqual(header[0].body, { aiappdescription: WANT }, 'the routing description alone: the tile description the row already holds is not sent again');});test('REAL BUNDLE: a different value is updated in place and written', async () => {@@ -244,7 +243,7 @@ test('REAL BUNDLE: over another writer\u2019s UNPUBLISHED header change, the heaconst header = headerWrites(writes).filter((w) => w.verb === 'patch');assert.deepStrictEqual(header.map((w) => w.ifMatch), ['W/"5"'], 'the row token, never the content token');assert.strictEqual(state.ai, WANT);- assert.strictEqual(header[0].body.description, 'Saved in Maker, not published', 'the other writer\u2019s change rides through');+ assert.deepStrictEqual(header[0].body, { aiappdescription: WANT }, 'the other writer\u2019s unpublished description is not sent again: the routing description is written alone');});test('REAL BUNDLE: a header row moved after the fetch is a concurrent edit: refused, the generic halt, and the copy kept', async () => {diff --git a/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.jsindex 7e247d1f6..f5a55ea3b 100644--- a/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.js@@ -5,9 +5,9 @@// ONE push that already writes the sitemap writes it too. That leans on SDK behaviour the plugin's own unit tests can only stub:// 1. a fetched app carries `name` and `description` (the adapter reads `description` as '' when the row has none), so// `updateElement('/name')` and `updateElement('/description')` have a path to write;-// 2. the push PATCHes the appmodule header — `name` and `description`, plus `aiappdescription` only when the artifact says-// something about it — only when the artifact holds one of them differently from the row, conditioned on the row's token-// the fetch read; an equal header is never written, so a rebuild that changes nothing PATCHes no appmodule;+// 2. the push PATCHes only the appmodule header texts the artifact holds differently from the row — `name`, `description`, and `aiappdescription` only when+// the artifact says something about it — in one request conditioned on the row's token the fetch read; an equal header is never written, so a rebuild+// that changes nothing PATCHes no appmodule;// 3. the header PATCH carries no `webresourceid`: an app's icon is written at create and cannot be changed by a push, even// when the artifact is given one — which is why the build REPORTS an icon the spec names that the app does not have, and// does not pretend to apply it;@@ -15,14 +15,15 @@// having modified nothing), and it writes the header only when the artifact holds one that differs from the row's — so the// build puts the fetched text back, which makes the next push a sitemap-only push, and reports the edit as not applied// (an explicitly authored routing description cannot be set aside this way, and halts);-// 5. a header whose name or description is not plain text (a text per language) is never sent: the PATCH always carries BOTH texts, so-// while either is not plain the build makes no header edit at all — the other text's, nor a routing description — and reports each as-// not applied (the tests at the end of this file). That whole-header hold is the chosen policy, not a stopgap: the SDK has no partial-// header write, so the one field that changed cannot be sent alone (the pin below fails if a re-vendored bundle makes the PATCH partial);-// 6. the hold is on the workspace copy, and the SDK decides for itself whether the header is written: when its OWN comparison read of the-// header fails (503, 403, a thrown error, an empty 200) it writes the copy's header as it is. So the client every SDK is made with refuses a-// PATCH of an app module row whose name or description is not a string (lib/app-header-text.js): nothing that is not plain text reaches the-// wire, the push fails with APP_HEADER_NOT_PLAIN_TEXT before the navigation is written, and a re-run finishes (the last tests of this file).+// 5. a header whose name or description is not plain text (a text per language) is never sent, and the one text does not hold the other back. The SDK+// writes only the texts that changed, and neither compares nor writes a text REMOVED from the copy (`removeElement('app', id, '/name')`). So the build+// edits the plain text beside a localized one on its own — the localized text keeps every translation — and takes the text that is not plain off the+// copy right before the push (pushAppHeader), which is the one place that pushes a copy. Only that text's OWN edit is held back, with a warning, and the+// routing description is applied as usual (the tests at the end of this file);+// 6. the SDK decides for itself whether the header is written: when its OWN comparison read of the header fails (503, 403, a thrown error, an empty 200)+// it writes every text the copy holds. A text taken off the copy is not on it, so it is not written even then. And the client every SDK is made with+// still refuses a PATCH of an app module row whose name or description is not a string (lib/app-header-text.js), for a copy the build did not clean:+// nothing that is not plain text reaches the wire, and the push fails with APP_HEADER_NOT_PLAIN_TEXT before the navigation is written (the last tests of this file).// A re-vendor could change any of them with every plugin test still green, so each is pinned here against the real bundle over a// fake Dataverse, the way app-ai-description-real-bundle.test.js pins the routing description.const test = require('node:test');@@ -128,13 +129,14 @@ const spec = (app = {}) => ({});const headerWrites = (writes) => writes.filter((w) => w.verb === 'patch' && /\/appmodules\(/.test(w.url));const sitemapWrites = (writes) => writes.filter((w) => w.verb === 'patch' && /\/sitemaps\(/.test(w.url));-// What a rebuild of an existing app does: edit the fetched copy, rewrite its sitemap, push once. `changed` is what the header edit-// answered (applyAppHeader: { changed, routing, replaced }).+// What a rebuild of an existing app does: edit the fetched copy, rewrite its sitemap, push once — through pushAppHeader, the one place the build pushes a+// copy, so that a text of the header that is not plain is taken off the copy as it is in a build. `changed` is what the header edit answered (applyAppHeader:+// { changed, routing, replaced, held }).async function rebuild(sdk, s, apply = applyAppHeader) {await sdk.fetchArtifact('app', APP_ID);const changed = await apply(sdk, s, APP_ID);await sdk.updateElement('app', APP_ID, '/siteMap', appDef(s, { forms: {}, views: {}, charts: {} }).siteMap);- const pushed = await sdk.pushArtifact('app', APP_ID);+ const pushed = await pushAppHeader(sdk, APP_ID, s.app.name, changed);return { changed, pushed };}@@ -200,7 +202,7 @@ test('REAL BUNDLE: the text and the routing description are written together byassert.strictEqual(changed.routing, true);const header = headerWrites(writes);assert.strictEqual(header.length, 1);- assert.deepStrictEqual(header[0].body, { name: 'Probe', description: 'Track tickets.', aiappdescription: ROUTING });+ assert.deepStrictEqual(header[0].body, { description: 'Track tickets.', aiappdescription: ROUTING }, 'the texts that changed, and not the name the spec leaves as it is');});test('REAL BUNDLE: the routing description\'s own helper still decides on its own, unchanged by the text edits', async () => {@@ -345,70 +347,137 @@ test('REAL BUNDLE: a localized header with a changed name is left alone as well,}});-// WHY a header is held WHOLE — the chosen policy, and the SDK is the reason. The SDK writes the artifact's `name` AND `description` in every-// header PATCH — whichever of them an edit changed, and for an edit of the routing description alone — because it writes the copy, not the edit,-// and it has no partial header write: the row token that conditions the PATCH is private to it, and a PATCH of the plugin's own would need a-// freshly read one (a blind overwrite). So a text that is not plain beside an edit of its sibling would be sent with it: a map in a String column,-// or a scalar over a text that carries translations. This is the fact the build's hold (applyAppHeader) rests on; if a re-vendored bundle sends-// only what changed, this fails, and the hold can be narrowed to the one field. Writing only the changed field with this SDK needs a new SDK-// operation: a follow-up, not something the plugin can do around it.-test('REAL BUNDLE: a header PATCH always carries the name AND the description — an edit of one sends the other, and a routing edit sends both', async () => {+// WHAT the SDK writes of the header: only the texts that CHANGED. It used to write the artifact's `name` AND `description` in every header PATCH — whichever of+// them an edit changed, and for an edit of the routing description alone — because it wrote the copy, not the edit. Since cds-maker-sdk 9a0c9f03 it writes the fields+// that differ from the row it has just read, in one request still conditioned on the row's token (and every field the copy holds when that read cannot be made).+// An edit of one text therefore does not send the other. Pinned here: the plugin's build leans on it to write one text of a header whose other text it must not send.+test('REAL BUNDLE: a header PATCH carries only the texts that changed — an edit of one does not send the other, and a routing edit sends neither', async () => {const text = await freshSdk();await rebuild(text.sdk, spec({ description: 'Changed' }));- assert.deepStrictEqual(headerWrites(text.writes).map((w) => w.body), [{ name: 'Probe', description: 'Changed' }], 'the name the spec did not change rides along');+ assert.deepStrictEqual(headerWrites(text.writes).map((w) => w.body), [{ description: 'Changed' }], 'the name the spec did not change is not sent');const name = await freshSdk();await rebuild(name.sdk, spec({ name: 'Help Desk' }));- assert.deepStrictEqual(headerWrites(name.writes).map((w) => w.body), [{ name: 'Help Desk', description: 'Tickets' }], 'and so does the description');+ assert.deepStrictEqual(headerWrites(name.writes).map((w) => w.body), [{ name: 'Help Desk' }], 'and neither is the description');const routing = await freshSdk();await rebuild(routing.sdk, spec({ aiDescription: ROUTING }));- assert.deepStrictEqual(headerWrites(routing.writes).map((w) => w.body), [{ name: 'Probe', description: 'Tickets', aiappdescription: ROUTING }], 'a routing edit sends both texts');+ assert.deepStrictEqual(headerWrites(routing.writes).map((w) => w.body), [{ aiappdescription: ROUTING }], 'a routing edit sends neither text');});-// A header text that is not plain — a text per language (a map keyed by LCID), a list, a number — is never sent, as a map or as a scalar. The-// adapter hands back one string per column for a real app, so this is a safety net for a shape the SDK may return, served here by the fake;-// what it must guarantee is the same in every case: an edit that would put the text on the wire is held back and reported, and the push that-// follows is the navigation alone.+// A header text that is not plain — a text per language (a map keyed by LCID), a list, a number — is never sent, as a map or as a scalar. The adapter hands+// back one string per column for a real app, so this is a safety net for a shape the SDK may return, served here by the fake. What it must guarantee is the same+// in every case: the text is neither edited nor sent, and its own edit — only that — is held back and reported. The other text and the routing description are+// applied as usual and written alone (the SDK sends only what changed), with the navigation.const localizedText = (english, french) => ({ 1033: english, 1036: french });+// [what, the header the environment holds, the spec's app, the header PATCH bodies the build sends, the text its edits replaced, the warnings it gives]const HELD_CASES = [['a localized name beside a changed description', { name: localizedText('Probe', 'Sonde') }, { description: 'Changed' },- [/^app "Probe": its description was not applied: the app's name is localized \(2 languages: 1033, 1036\), and the app's name and description are written in one request, so changing its description would send the name too — a rebuild never sends a text that is not plain\. Change it in Power Apps\.$/]],+ [{ description: 'Changed' }], { description: 'Tickets' }, []],['a localized description beside a changed name', { description: localizedText('Tickets', 'Billets') }, { name: 'Help Desk' },- [/^app "Help Desk": its name was not applied: the app's description is localized \(2 languages: 1033, 1036\), and the app's name and description are written in one request, so changing its name would send the description too — a rebuild never sends a text that is not plain\. Change it in Power Apps\.$/]],+ [{ name: 'Help Desk' }], { name: 'Probe' }, []],['a localized description beside a changed name and a changed description', { description: localizedText('Tickets', 'Billets') }, { name: 'Help Desk', description: 'Changed' },- [/^app "Help Desk": its name was not applied: the app's description is localized/, /^app "Help Desk": its description was not applied: it is localized \(2 languages: 1033, 1036\)/]],+ [{ name: 'Help Desk' }], { name: 'Probe' },+ [/^app "Help Desk": its description was not applied: it is localized \(2 languages: 1033, 1036\), and a rebuild does not replace a localized text — it cannot tell which language the spec's text is for, nor that the other translations would be kept\. Change it in Power Apps\.$/]],['two localized texts beside a routing description', { name: localizedText('Probe', 'Sonde'), description: localizedText('Tickets', 'Billets') }, { aiDescription: ROUTING },- [/^app "Probe": its routing description \(app\.aiDescription\) was not applied: the app's name is localized \(2 languages: 1033, 1036\) and its description is localized \(2 languages: 1033, 1036\), and the app's name, description and routing description are written in one request, so changing it would send both too — a rebuild never sends a text that is not plain\. Change it in Power Apps\.$/]],+ [{ aiappdescription: ROUTING }], {}, []],['a localized name beside a routing description', { name: localizedText('Probe', 'Sonde') }, { aiDescription: ROUTING },- [/^app "Probe": its routing description \(app\.aiDescription\) was not applied: the app's name is localized/]],+ [{ aiappdescription: ROUTING }], {}, []],['a list for the name beside a changed description', { name: ['Probe'] }, { description: 'Changed' },- [/^app "Probe": its description was not applied: the app's name could not be read as plain text \(it came back as a list\), and the app's name and description are written in one request/,- /^app "Probe": its name was not applied: the app's name could not be read as plain text \(it came back as a list\), so a rebuild does not replace it/]],+ [{ description: 'Changed' }], { description: 'Tickets' },+ [/^app "Probe": its name was not applied: the app's name could not be read as plain text \(it came back as a list\), so a rebuild does not replace it\. Change it in Power Apps\.$/]],['a number for the description beside a changed name', { description: 7 }, { name: 'Help Desk' },- [/^app "Help Desk": its name was not applied: the app's description could not be read as plain text \(it came back as a number\), and the app's name and description are written in one request/,- /^app "Help Desk": its description was not applied: the app's description could not be read as plain text \(it came back as a number\), so a rebuild does not replace it/]],+ [{ name: 'Help Desk' }], { name: 'Probe' },+ [/^app "Help Desk": its description was not applied: the app's description could not be read as plain text \(it came back as a number\), so a rebuild does not replace it\. Change it in Power Apps\.$/]],];-for (const [what, initial, app, expected] of HELD_CASES) {- test(`REAL BUNDLE: ${what} — no text is sent for the edit, the navigation still is, and the build says what it left`, async () => {+for (const [what, initial, app, bodies, replaced, expected] of HELD_CASES) {+ test(`REAL BUNDLE: ${what} — what changed is written alone, the text that is not plain is never sent, and the build says what it left`, async () => {const { sdk, writes, state } = await freshSdk(initial);- const fetched = JSON.parse(JSON.stringify(await sdk.fetchArtifact('app', APP_ID)));+ await sdk.fetchArtifact('app', APP_ID);const warnings = [];const s = spec(app);const header = await applyAppHeader(sdk, s, APP_ID, { warn: (m) => warnings.push(m) });await sdk.updateElement('app', APP_ID, '/siteMap', appDef(s, { forms: {}, views: {}, charts: {} }).siteMap);const pushed = await pushAppHeader(sdk, APP_ID, 'Probe', header, undefined, (m) => warnings.push(m));assert.strictEqual(pushed.saved, true, JSON.stringify(pushed.error && pushed.error.message));- assert.deepStrictEqual([header.changed, header.routing, header.replaced], [false, false, {}], 'nothing of the header was edited');- assert.deepStrictEqual(headerWrites(writes), [], 'no PATCH of the appmodule at all');+ assert.deepStrictEqual(header.replaced, replaced, 'the text its edits replaced');+ assert.deepStrictEqual(headerWrites(writes).map((w) => w.body), bodies, 'one PATCH, of what changed alone');assert.deepStrictEqual(state.refused, [], 'and nothing a String column cannot take was ever sent');+ for (const [key, value] of Object.entries(initial)) assert.deepStrictEqual(state[key], value, `the environment still holds the maker's ${key}, every translation of it`);assert.strictEqual(sitemapWrites(writes).length, 1, 'the navigation is written, as it always is');- const held = await sdk.getArtifact('app', APP_ID);- assert.deepStrictEqual([held.name, held.description], [fetched.name, fetched.description], 'the copy still holds the header exactly as it was fetched');assert.strictEqual(warnings.length, expected.length, JSON.stringify(warnings));for (const re of expected) assert.ok(warnings.some((w) => re.test(w)), `${re} in ${JSON.stringify(warnings)}`);});}+// The two cases that decide the policy, named for what they pin: the plain text beside a localized one is written on its own, whichever it is, and the localized one keeps+// every translation (the environment's row is read back after the push).+test('REAL BUNDLE: a localized name with a changed plain description — only the description is written, and the name\'s translations are untouched', async () => {+ const name = localizedText('Probe', 'Sonde');+ const { sdk, writes, state } = await freshSdk({ name });+ const built = await runSdkBuild(spec({ uniqueName: APP_UNIQUE, description: 'Track tickets.' }), { sdk, apply: true, publish: true, genpage: fakeGenpage(), workspaceDir: workspaceDir(), env: 'https://contoso.crm.dynamics.com', phases: ['app-shell', 'publish'] });+ assert.strictEqual(built.ok, true);+ assert.deepStrictEqual(headerWrites(writes).map((w) => [w.body, w.ifMatch]), [[{ description: 'Track tickets.' }, 'W/"1"']], 'the description alone, conditioned on the row token the fetch read');+ assert.deepStrictEqual([state.name, state.description], [name, 'Track tickets.'], 'the row holds the new description and the name\'s translations');+});++test('REAL BUNDLE: a localized description with a changed plain name — only the name is written, and the description\'s translations are untouched', async () => {+ const description = localizedText('Tickets', 'Billets');+ const { sdk, writes, state } = await freshSdk({ description });+ const built = await runSdkBuild(spec({ uniqueName: APP_UNIQUE, name: 'Help Desk' }), { sdk, apply: true, publish: true, genpage: fakeGenpage(), workspaceDir: workspaceDir(), env: 'https://contoso.crm.dynamics.com', phases: ['app-shell', 'publish'] });+ assert.strictEqual(built.ok, true);+ assert.deepStrictEqual(headerWrites(writes).map((w) => [w.body, w.ifMatch]), [[{ name: 'Help Desk' }, 'W/"1"']]);+ assert.deepStrictEqual([state.name, state.description], ['Help Desk', description]);+});++// What the build leans on to keep a text off the wire: a text REMOVED from the copy is neither compared nor written, the copy is clean once the push has saved,+// and a plain fetch brings the maker's text back (the next run starts from the environment's header, not from a copy without one).+test('REAL BUNDLE: the text taken off the copy is not written, the copy is clean after the push, and a plain fetch brings the maker\'s text back', async () => {+ const name = localizedText('Probe', 'Sonde');+ const { sdk, writes } = await freshSdk({ name });+ const { pushed } = await rebuild(sdk, spec({ description: 'Changed' }));+ assert.strictEqual(pushed.saved, true);+ const afterPush = await sdk.getArtifact('app', APP_ID);+ assert.strictEqual(afterPush.name, undefined, 'the copy no longer holds the name the build kept off the wire');+ assert.strictEqual(afterPush.description, 'Changed');+ assert.strictEqual((await sdk.listArtifacts('app')).find((a) => a.id === APP_ID).isDirty, false, 'a push that saved leaves the copy clean: nothing is left for the next run to refuse');+ assert.deepStrictEqual(headerWrites(writes).map((w) => w.body), [{ description: 'Changed' }]);+ assert.deepStrictEqual((await sdk.fetchArtifact('app', APP_ID)).name, name, 'and the next run\'s fetch reads the environment\'s name again, translations included');+});++// The edit of a text is applied to the copy, and a text that is not plain is taken off it only when a push follows: the header edit alone leaves the copy as the fetch read it,+// so a run that does not push (the routing description of a page-backed app, say) leaves no edit behind for the next run to refuse (refuseUnpushedAppCopy).+test('REAL BUNDLE: applying a header over a text that is not plain changes nothing on the copy but the edits: it is taken off only by the push', async () => {+ const name = localizedText('Probe', 'Sonde');+ const { sdk } = await freshSdk({ name });+ await sdk.fetchArtifact('app', APP_ID);+ const header = await applyAppHeader(sdk, spec(), APP_ID, { warn: () => assert.fail('nothing to say: the spec asks for nothing the header does not already hold') });+ assert.deepStrictEqual([header.changed, header.routing, header.replaced], [false, false, {}]);+ assert.deepStrictEqual(header.held.map(({ key }) => key), ['name'], 'the text that has to stay off the wire');+ assert.deepStrictEqual((await sdk.getArtifact('app', APP_ID)).name, name, 'still on the copy');+ assert.strictEqual((await sdk.listArtifacts('app')).find((a) => a.id === APP_ID).isDirty, false, 'and the copy is clean');+});++// A never-published app takes no write to its header until it is published: the SDK throws before it writes the navigation, the build puts the edited text back, and the same+// copy then saves the navigation. The text taken off the copy stays off it for that second push, and is never in either request.+test('REAL BUNDLE: a never-published app over a localized name — the description edit is not applied and put back, the name is in neither push, and the navigation is written', async () => {+ const name = localizedText('Probe', 'Sonde');+ const { sdk, writes, state } = await freshSdk({ name, headerStatus: 400 });+ const s = spec({ description: 'Track tickets.' });+ await sdk.fetchArtifact('app', APP_ID);+ const warnings = [];+ const header = await applyAppHeader(sdk, s, APP_ID, { warn: (m) => warnings.push(m) });+ await sdk.updateElement('app', APP_ID, '/siteMap', appDef(s, { forms: {}, views: {}, charts: {} }).siteMap);+ const pushed = await pushAppHeader(sdk, APP_ID, 'Probe', header, undefined, (m) => warnings.push(m));+ assert.strictEqual(pushed.saved, true, JSON.stringify(pushed.error && pushed.error.message));+ assert.deepStrictEqual(headerWrites(writes).map((w) => w.body), [{ description: 'Track tickets.' }], 'the one refused header PATCH carried the description alone, never the name');+ assert.strictEqual(sitemapWrites(writes).length, 1, 'and the push without it wrote the navigation');+ assert.strictEqual(warnings.length, 1, JSON.stringify(warnings));+ assert.match(warnings[0], /^app "Probe": its description was not applied: the app was never published; publish it in Power Apps and re-run\./);+ assert.deepStrictEqual([state.name, state.description], [name, 'Tickets'], 'the environment is as it was');+ const held = await sdk.getArtifact('app', APP_ID);+ assert.deepStrictEqual([held.name, held.description], [undefined, 'Tickets'], 'the description is put back, and the name stays off the copy');+});+test('REAL BUNDLE: a header text that is not plain, beside edits that need nothing from it, stays silent and writes nothing', async () => {// The spec says nothing new: its name is one of the localized name\u2019s own entries and it sets no description.const { sdk, writes } = await freshSdk({ name: localizedText('Probe', 'Sonde'), description: localizedText('Tickets', 'Billets') });@@ -420,9 +489,9 @@ test('REAL BUNDLE: a header text that is not plain, beside edits that need nothiassert.deepStrictEqual(headerWrites(writes), []);});-test('REAL BUNDLE: a transport that refuses a non-string name or description is never asked to — the build\'s push is the navigation alone', async () => {+test('REAL BUNDLE: a transport that refuses a non-string name or description is never asked to — the build\'s push is the description and the navigation', async () => {// The consequence the guard prevents, with a fake that refuses what a String column cannot take: the header PATCH answers 400, and the SDK- // throws before it writes the navigation, so one text of the header would have stopped the app step. Held back, there is no such request.+ // throws before it writes the navigation, so one text of the header would have stopped the app step. Taken off the copy, it is not in the request.const { sdk, writes, state } = await freshSdk({ name: localizedText('Probe', 'Sonde') });const warnings = [];await sdk.fetchArtifact('app', APP_ID);@@ -432,16 +501,19 @@ test('REAL BUNDLE: a transport that refuses a non-string name or description isconst pushed = requireSuccessfulPush(await pushAppHeader(sdk, APP_ID, 'Probe', header), 'app Probe');assert.strictEqual(pushed.saved, true);assert.deepStrictEqual(state.refused, []);+ assert.deepStrictEqual(headerWrites(writes).map((w) => w.body), [{ description: 'Changed' }]);assert.strictEqual(sitemapWrites(writes).length, 1);assert.match(sitemapWrites(writes)[0].body.sitemapxml, /Entity="new_torder"/, 'the navigation the run built is what was written');});-// The whole app step, through runSdkBuild, over the same fake: the build goes on past a header it will not edit — to the navigation, the-// publish of the app and, with the pages phase, the finalizer that is then the app's only writer.-test('REAL BUNDLE: a complete rebuild over a header that is not plain text finishes — navigation written, app published, nothing sent for the header (with and without the pages phase)', async () => {- for (const [what, initial, app, wanted] of [- ['a localized name beside a changed description', { name: localizedText('Probe', 'Sonde') }, { description: 'Changed' }, /^app "Probe": its description was not applied: the app's name is localized/],- ['a localized description beside a routing description', { description: localizedText('Tickets', 'Billets') }, { aiDescription: ROUTING }, /^app "Probe": its routing description \(app\.aiDescription\) was not applied: the app's description is localized/],+// The whole app step, through runSdkBuild, over the same fake: the build goes on past a text it will not edit — the other text and the routing description are+// written alone, then the navigation, the publish of the app and, with the pages phase, the finalizer that is then the app's only writer.+test('REAL BUNDLE: a complete rebuild over a header that is not plain text finishes — what changed written alone, navigation written, app published (with and without the pages phase)', async () => {+ for (const [what, initial, app, bodies] of [+ ['a localized name beside a changed description', { name: localizedText('Probe', 'Sonde') }, { description: 'Changed' }, [{ description: 'Changed' }]],+ ['a localized description beside a routing description', { description: localizedText('Tickets', 'Billets') }, { aiDescription: ROUTING }, [{ aiappdescription: ROUTING }]],+ // Both texts off the copy: the SDK is supplied none of them, and the routing description is what its one PATCH carries.+ ['two localized texts beside a routing description', { name: localizedText('Probe', 'Sonde'), description: localizedText('Tickets', 'Billets') }, { aiDescription: ROUTING }, [{ aiappdescription: ROUTING }]],]) {for (const pages of [false, true]) {const { sdk, writes, state } = await freshSdk(initial);@@ -450,12 +522,13 @@ test('REAL BUNDLE: a complete rebuild over a header that is not plain text finisphases: pages ? ['app-shell', 'pages', 'publish'] : ['app-shell', 'publish'], warn: (m) => warnings.push(m) });const label = `${what}${pages ? ', with the pages phase' : ''}`;assert.strictEqual(built.ok, true, label);- assert.deepStrictEqual(headerWrites(writes), [], `${label}: no header PATCH`);+ assert.deepStrictEqual(headerWrites(writes).map((w) => w.body), bodies, `${label}: one header PATCH, of what changed alone`);assert.deepStrictEqual(state.refused, [], label);+ for (const [key, value] of Object.entries(initial)) assert.deepStrictEqual(state[key], value, `${label}: the maker's ${key} is as it was`);assert.strictEqual(sitemapWrites(writes).length, 1, `${label}: the navigation is written once`);const published = writes.filter((w) => /\/PublishXml/.test(w.url) && /<appmodule>/.test((w.body || {}).ParameterXml || ''));assert.ok(published.length > 0 && writes.indexOf(published[0]) > writes.indexOf(sitemapWrites(writes)[0]), `${label}: the app is published after its navigation`);- assert.strictEqual(warnings.filter((w) => wanted.test(w)).length, 1, `${label}: ${JSON.stringify(warnings)}`);+ assert.deepStrictEqual(warnings.filter((w) => /was not applied/.test(w)), [], `${label}: nothing was left unapplied`);}}// The neighbour: the same rebuild of a plain header writes it, as before.@@ -465,13 +538,13 @@ test('REAL BUNDLE: a complete rebuild over a header that is not plain text finisassert.deepStrictEqual(headerWrites(writes).map((w) => w.body), [{ name: 'Help Desk', description: 'Changed' }]);});-// --- the SDK's OWN comparison read fails: the client is the last line of defence ----------------------------------------------------------------------------+// --- the SDK's OWN comparison read fails: a text taken off the copy is not written, and the client is the last line of defence ------------------------------------//-// Everything above holds the header on the workspace COPY. But the SDK's push of an app decides for itself whether the header is written: it reads the header and compares it with the-// copy's, and its "write needed" flag starts true and only a 2xx answer sets it — so a read that cannot be made (HTTP 503 or 403, a transport that throws) leaves the flag true, and a 200 with no row-// is compared with an empty header, which differs: the header is written from the copy as it is, a text that is not plain included, even when the build edited nothing at all. Pinned here with a fault in the fake server. The client the SDK is made-// with (lib/app-header-text.js, wired in lib/maker-sdk.js, the one way a script makes an SDK) refuses that PATCH before any byte is sent: the push fails with the typed error, and since the-// SDK writes the header first, it wrote nothing of its navigation either.+// The SDK's push of an app decides for itself whether the header is written: it reads the header and compares it with the copy's, and when that read cannot be made (HTTP 503 or 403, a transport that+// throws, a 200 with no row) it writes EVERY text the copy holds. So the build takes the text that is not plain off the copy right before the push (pushAppHeader): a text that is not on the copy is not written+// even then, and the build goes on. Pinned here with a fault in the fake server. For a copy the build did not clean — the page backend's push of the app, say — the client the SDK is made with+// (lib/app-header-text.js, wired in lib/maker-sdk.js, the one way a script makes an SDK) is the last line of defence: it refuses a PATCH that carries such a text before any byte is sent, the push fails with the+// typed error, and since the SDK writes the header first, it wrote nothing of its navigation either.// Fails that read once, inside a push of an app: `kind` is an HTTP status ('503', '403'), 'throw' (the transport throws) or 'empty' (HTTP 200 with no row). Armed only inside the push of an// app: the build's own reads of the app select the same columns and must answer — its recovery reads the app again.@@ -497,95 +570,88 @@ function workspaceDir() {const COMPARISON_FAULTS = [['HTTP 503', '503'], ['HTTP 403', '403'], ['a thrown error', 'throw'], ['an empty HTTP 200', 'empty']];const PROTECTED_NAMES = [- ['a localized name', localizedText('Probe', 'Sonde'), /the app's name is localized \(2 languages: 1033, 1036\)\. Nothing was sent/],- ['an array-valued name', ['Probe'], /the app's name could not be read as plain text \(it came back as a list\)\. Nothing was sent/],+ ['a localized name', localizedText('Probe', 'Sonde'), /the app's name is localized \(2 languages: 1033, 1036\)\. Nothing was sent/, null],+ // The spec's name is not one of a list's entries, so the name's own edit is held back and reported (a localized name that holds the spec's text needs no word).+ ['an array-valued name', ['Probe'], /the app's name could not be read as plain text \(it came back as a list\)\. Nothing was sent/, /^app "Probe": its name was not applied: the app's name could not be read as plain text \(it came back as a list\), so a rebuild does not replace it\./],];const PUSH_SITES = [['app-shell + publish', false], ['app-shell + pages + publish', true]];for (const [faultWhat, fault] of COMPARISON_FAULTS) {- for (const [shapeWhat, shape, described] of PROTECTED_NAMES) {+ for (const [shapeWhat, shape, , ownEditWarning] of PROTECTED_NAMES) {for (const [siteWhat, pages] of PUSH_SITES) {- test(`REAL BUNDLE: ${faultWhat} on the SDK's own comparison read, over ${shapeWhat}, ${siteWhat} — the header write is refused before a byte is sent, nothing is written, and the re-run finishes`, async () => {+ test(`REAL BUNDLE: ${faultWhat} on the SDK's own comparison read, over ${shapeWhat}, ${siteWhat} — the text that is not plain is never sent: the changed description is written alone, and the build finishes`, async () => {const f = await freshSdk({ name: shape, existingIcon: true });const injected = failComparisonRead(f, fault);const warnings = [];- const phase = pages ? 'pages' : 'app-shell';- const genpage = fakeGenpage();- const workspace = workspaceDir();- // A changed description beside the protected name: the build holds it back (and says so), and the SDK is then asked to push the copy.- const run = () => runSdkBuild(spec({ uniqueName: APP_UNIQUE, description: 'Changed' }), {- sdk: f.sdk, apply: true, publish: true, genpage, workspaceDir: workspace, env: 'https://contoso.crm.dynamics.com',+ // A changed description beside the protected name: the build applies it, takes the name off the copy, and the SDK is then asked to push the copy.+ const built = await runSdkBuild(spec({ uniqueName: APP_UNIQUE, description: 'Changed' }), {+ sdk: f.sdk, apply: true, publish: true, genpage: fakeGenpage(), workspaceDir: workspaceDir(), env: 'https://contoso.crm.dynamics.com',phases: pages ? ['app-shell', 'pages', 'publish'] : ['app-shell', 'publish'], warn: (m) => warnings.push(m),});- await assert.rejects(run(), (halt) => {- assert.strictEqual(halt.name, 'BuildHalt');- assert.strictEqual(halt.code, NOT_PLAIN, 'the halt carries the typed code');- assert.strictEqual(halt.phase, phase);- assert.match(halt.message, new RegExp(`^${phase} failed: Refused before anything was sent: the write of app ${APP_ID}'s header would have carried a text that is not plain — `));- assert.match(halt.message, described);- assert.match(halt.message, /Nothing was sent, so the app is as it was, and the push stopped before it wrote the app's navigation\. /);- assert.match(halt.message, /Run it again: a re-run normally succeeds\. If the same refusal comes back, make the app's name and description plain text in Power Apps\.$/);- assert.ok(halt.cause instanceof SdkError, 'the SDK rethrew the client\'s error as it is');- assert.strictEqual(halt.cause.code, NOT_PLAIN);- assert.strictEqual(halt.cause.transient, false);- assert.strictEqual(isTransientHalt(halt), false, 'the build does not run the phase again on its own');- return true;- });+ assert.strictEqual(built.ok, true);assert.strictEqual(injected.reads.length, 1, 'the fault reached the SDK\'s one comparison read of the header');- assert.deepStrictEqual(headerWrites(f.writes), [], 'no PATCH of the appmodule was sent');- assert.deepStrictEqual(f.state.refused, [], 'so nothing a String column cannot take reached the server');- assert.deepStrictEqual(sitemapWrites(f.writes), [], 'and the navigation was not written: the SDK writes the header first');- // No PATCH of anything, and the app not published. (What a rebuild does before its push — the app's solution membership, an idempotent add — is not the push's.) The one publish- // before the push is the request that publishes, ahead of the app's write, the tables whose forms that write adds (publishTablesBeforeApp): it is made before the push is tried,- // whichever way the push then ends, and it names tables only.- assert.deepStrictEqual(f.writes.filter((w) => w.verb === 'patch'), []);- const publishes = f.writes.filter((w) => /\/PublishXml/.test(w.url)).map((w) => String((w.body || {}).ParameterXml || ''));- assert.ok(publishes.length <= 1 && publishes.every((xml) => /^<importexportxml><entities>(<entity>[a-z_]+<\/entity>)+<\/entities><\/importexportxml>$/.test(xml)), `at most the one request for the tables before the app, and no publish of the app: ${JSON.stringify(publishes)}`);- assert.deepStrictEqual([f.state.name, f.state.description], [shape, 'Tickets'], 'the app is as it was');- assert.strictEqual(warnings.filter((w) => /^app "Probe": its description was not applied: the app's name /.test(w)).length, 1, `the held-back description is still reported, once: ${JSON.stringify(warnings)}`);-- // A re-run — the read answers now — finds the copy equal to the row, sends no header, and writes the navigation. (It also shows the failed push left the workspace copy as the- // server has it: a copy holding the refused run's edits would be refused as unpushed.)- const rerun = await run();- assert.strictEqual(rerun.ok, true);- assert.deepStrictEqual(headerWrites(f.writes), [], 're-run: still no header PATCH');- assert.deepStrictEqual(f.state.refused, [], 're-run: nothing that is not plain text was sent');- assert.strictEqual(sitemapWrites(f.writes).length, 1, 're-run: the navigation is written, once');+ // The read could not be made, so the SDK wrote every text the copy held: the description — on the row's token, as for a plain header — and not the name, which was no longer on the copy.+ assert.deepStrictEqual(headerWrites(f.writes).map((w) => [w.body, w.ifMatch]), [[{ description: 'Changed' }, 'W/"1"']]);+ assert.deepStrictEqual(f.state.refused, [], 'nothing a String column cannot take reached the server');+ assert.strictEqual(sitemapWrites(f.writes).length, 1, 'the navigation is written once');const published = f.writes.filter((w) => /\/PublishXml/.test(w.url) && /<appmodule>/.test((w.body || {}).ParameterXml || ''));- assert.ok(published.length > 0 && f.writes.indexOf(published[0]) > f.writes.indexOf(sitemapWrites(f.writes)[0]), 're-run: the app is published after its navigation');- assert.deepStrictEqual([f.state.name, f.state.description], [shape, 'Tickets'], 're-run: the header is still the maker\'s');+ assert.ok(published.length > 0 && f.writes.indexOf(published[0]) > f.writes.indexOf(sitemapWrites(f.writes)[0]), 'the app is published after its navigation');+ assert.deepStrictEqual([f.state.name, f.state.description], [shape, 'Changed'], 'the name is still the maker\'s, and the description is the spec\'s');+ assert.deepStrictEqual(warnings.filter((w) => /was not applied/.test(w)).map((w) => ownEditWarning && ownEditWarning.test(w)), ownEditWarning ? [true] : [], 'only the name\'s own edit, when the spec\'s name is not one the text already holds, is left unapplied');});}}}-// The same fault one level down, with nothing edited at all (`changed: false`) — the case a hold on the workspace copy cannot see: the SDK is still asked to push the copy, and writes its header.-// The description is judged exactly as the name is, and both together are named together.+// The same fault with nothing edited at all (`changed: false`) — the case a hold on the edits cannot see: the SDK is still asked to push the copy, and writes the texts it holds. The text that is not plain is off the+// copy, so only the other one is written: the copy's own, which is the row's (the SDK has no row to compare it with), on the row's token, as for a header that is plain. Both off: nothing is left to write.+// [what, the header the environment holds, the text the guard names in its refusal of a copy that still holds it, the header PATCH bodies the push makes]const PROTECTED_HEADERS = [- ...PROTECTED_NAMES.map(([what, name, described]) => [what, { name }, described, { name }]),- ['a localized description', { description: localizedText('Tickets', 'Billets') }, /the app's description is localized \(2 languages: 1033, 1036\)\. Nothing was sent/, { description: localizedText('Tickets', 'Billets') }],- ['a list for the description', { description: ['Tickets'] }, /the app's description could not be read as plain text \(it came back as a list\)\. Nothing was sent/, { description: ['Tickets'] }],+ ...PROTECTED_NAMES.map(([what, name, described]) => [what, { name }, described, [{ description: 'Tickets' }]]),+ ['a localized description', { description: localizedText('Tickets', 'Billets') }, /the app's description is localized \(2 languages: 1033, 1036\)\. Nothing was sent/, [{ name: 'Probe' }]],+ ['a list for the description', { description: ['Tickets'] }, /the app's description could not be read as plain text \(it came back as a list\)\. Nothing was sent/, [{ name: 'Probe' }]],['a localized name and description', { name: localizedText('Probe', 'Sonde'), description: localizedText('Tickets', 'Billets') },- /the app's name is localized \(2 languages: 1033, 1036\) and its description is localized \(2 languages: 1033, 1036\)\. Nothing was sent/, { name: localizedText('Probe', 'Sonde'), description: localizedText('Tickets', 'Billets') }],+ /the app's name is localized \(2 languages: 1033, 1036\) and its description is localized \(2 languages: 1033, 1036\)\. Nothing was sent/, []],];for (const [faultWhat, fault] of COMPARISON_FAULTS) {- for (const [shapeWhat, initial, described, held] of PROTECTED_HEADERS) {- test(`REAL BUNDLE: ${faultWhat} on the comparison read, over ${shapeWhat} and an edit of nothing — the push of the copy is refused with the typed error, and the copy is put back as the server has it`, async () => {+ for (const [shapeWhat, initial, , bodies] of PROTECTED_HEADERS) {+ test(`REAL BUNDLE: ${faultWhat} on the comparison read, over ${shapeWhat} and an edit of nothing — the push goes on without the text that is not plain, and the other text is written as it is`, async () => {const f = await freshSdk(initial);await f.sdk.fetchArtifact('app', APP_ID);const header = await applyAppHeader(f.sdk, spec(), APP_ID, { warn: () => {} });- assert.deepStrictEqual(header, { changed: false, routing: false, replaced: {} }, 'the build edited nothing (an array-valued or number text is reported as not applied; a localized one that holds the spec\'s text, or one the spec does not set, is silent)');+ assert.deepStrictEqual([header.changed, header.routing, header.replaced], [false, false, {}], 'the build edited nothing (an array-valued or number text is reported as not applied; a localized one that holds the spec\'s text, or one the spec does not set, is silent)');+ const injected = failComparisonRead(f, fault);+ const pushed = await pushAppHeader(f.sdk, APP_ID, 'Probe', header);+ assert.strictEqual(pushed.saved, true, JSON.stringify(pushed.error && pushed.error.message));+ assert.strictEqual(injected.reads.length, 1);+ assert.deepStrictEqual(headerWrites(f.writes).map((w) => w.body), bodies);+ assert.deepStrictEqual(f.state.refused, []);+ assert.strictEqual(sitemapWrites(f.writes).length, 1, 'and the navigation is written');+ for (const [key, value] of Object.entries(initial)) assert.deepStrictEqual(f.state[key], value, `the maker's ${key} is as it was`);+ });+ }+}++// The client is the last line of defence, and it stays: the build's push never carries such a text, but a push of a copy that still holds one — which the build did not make — is refused with the typed error, before+// a byte is sent, when the SDK's read fails. Nothing was written, not even the navigation, and a re-run finds the read answering.+for (const [faultWhat, fault] of COMPARISON_FAULTS) {+ for (const [shapeWhat, initial, described] of PROTECTED_HEADERS) {+ test(`REAL BUNDLE: ${faultWhat} on the comparison read, over ${shapeWhat}, pushed as the SDK holds it — the client refuses the write with the typed error before a byte is sent`, async () => {+ const f = await freshSdk(initial);+ await f.sdk.fetchArtifact('app', APP_ID);const injected = failComparisonRead(f, fault);- await assert.rejects(pushAppHeader(f.sdk, APP_ID, 'Probe', header), (e) => {- assert.ok(e instanceof SdkError);+ await assert.rejects(f.sdk.pushArtifact('app', APP_ID), (e) => {+ assert.ok(e instanceof SdkError, 'the SDK rethrew the client\'s error as it is');assert.strictEqual(e.code, NOT_PLAIN);+ assert.strictEqual(e.transient, false);assert.match(e.message, described);return true;});assert.strictEqual(injected.reads.length, 1);- assert.deepStrictEqual([headerWrites(f.writes), f.state.refused, sitemapWrites(f.writes)], [[], [], []]);- const kept = await f.sdk.getArtifact('app', APP_ID);- assert.deepStrictEqual([kept.name, kept.description], [held.name || 'Probe', held.description || 'Tickets'], 'the copy holds what the server holds');+ assert.deepStrictEqual([headerWrites(f.writes), f.state.refused, sitemapWrites(f.writes)], [[], [], []], 'nothing was sent, and the SDK writes the header first, so the navigation was not written either');+ // The copy is as the fetch read it, so a re-run's push — the read answers now — finds it equal to the row and sends no header at all.+ assert.deepStrictEqual((await f.sdk.pushArtifact('app', APP_ID)).saved, true);+ assert.deepStrictEqual(headerWrites(f.writes), []);});}}diff --git a/plugins/model-apps/scripts/tests/app-roles.test.js b/plugins/model-apps/scripts/tests/app-roles.test.jsnew file mode 100644index 000000000..2fd46c72c--- /dev/null+++ b/plugins/model-apps/scripts/tests/app-roles.test.js@@ -0,0 +1,278 @@+'use strict';+// lib/app-roles.js: what the environment says about who can OPEN an app — the security roles associated with it (the `appmoduleroles` relationship) —+// read through the SDK, read-only. verify-model-app.js reads the same relationship for the roles its personas author (appIdFor, appRoleIdsFor: moved there+// unchanged), and the design document reads it for the roles the app already has (appRolesOf).+//+// What the document reads must be an ANSWER, never a guess: an app is absent only when neither layer has it, and a list of roles is "no roles" only when the+// platform answered a list with nothing in it — a draft that was never published, a refused read and an answer that is no list are each "not checked".+const test = require('node:test');+const assert = require('node:assert');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const { withThrowawaySdk } = require('../lib/throwaway-sdk.js');+const { createFakeAppsOrg, json } = require('./helpers/fake-apps-org.js');+const roles = require('../lib/app-roles.js');++const { appIdFor, appRoleIdsFor, appRolesOf } = roles;+const ORIGIN = 'https://contoso.crm.dynamics.com';+const APP_ID = '22222222-2222-4222-8222-222222222222';+const ROLE_A = '00000000-0000-4000-8000-0000000000AA';+const ROLE_B = '00000000-0000-4000-8000-0000000000bb';+const ASSOCIATION = `/appmodules(${APP_ID})/appmoduleroles_association?$select=roleid,name,ismanaged`;++// An SDK stand-in. `appRows` answers the published-layer lookup verify makes; `resolve` the SDK's lookup in the saved layer (a draft is in it); `rows` answers+// the association read, `body` replaces the whole answer's body and `get` the whole answer. Every call is recorded. A method the code may not call is not there.+function fakeSdk({ appRows = [{ appmoduleid: APP_ID }], resolve, rows = [], body, status = 200, get } = {}) {+ const calls = [];+ return {+ calls,+ queryRecords: async (set, options) => { calls.push({ method: 'queryRecords', set, options }); return appRows; },+ resolveArtifact: async (type, query) => {+ calls.push({ method: 'resolveArtifact', type, query });+ return resolve ? resolve(type, query) : [{ id: APP_ID, name: 'Contoso PM', appModuleIdUnique: '33333333-3333-4333-8333-333333333333' }];+ },+ dataverse: {+ get: async (url) => {+ calls.push({ method: 'get', url });+ if (get) return get(url);+ return { status, headers: {}, body: status >= 300 ? { error: { message: 'denied' } } : (body !== undefined ? body : { value: rows }) };+ },+ },+ };+}++// --- verify's readers, moved ----------------------------------------------------------------------------------------------------------++test('appIdFor and appRoleIdsFor are verify-model-app.js\u2019s own exports, now defined here', () => {+ const verify = require('../verify-model-app.js');+ assert.strictEqual(verify.appIdFor, appIdFor);+ assert.strictEqual(verify.appRoleIdsFor, appRoleIdsFor);+});++test('appIdFor finds the app by its unique name in the published layer — the lookup verify always made', async () => {+ const sdk = fakeSdk();+ assert.strictEqual(await appIdFor(sdk, "contoso's_app"), APP_ID);+ assert.deepStrictEqual(sdk.calls, [{ method: 'queryRecords', set: 'appmodule', options: { select: ['appmoduleid'], filter: "uniquename eq 'contoso''s_app'", top: 1 } }]);+ assert.strictEqual(await appIdFor(fakeSdk({ appRows: [] }), 'missing_app'), undefined);+});++test('appRoleIdsFor answers { ok, roleIds } in lower case, from one read of the association with only the role id selected', async () => {+ const sdk = fakeSdk({ rows: [{ roleid: ROLE_A }, { roleid: ROLE_B }, { roleid: null }, null, {}] });+ assert.deepStrictEqual(await appRoleIdsFor(sdk, 'contoso_app'), { ok: true, roleIds: [ROLE_A.toLowerCase(), ROLE_B.toLowerCase()] });+ assert.deepStrictEqual(sdk.calls.filter((c) => c.method === 'get'), [{ method: 'get', url: `/appmodules(${APP_ID})/appmoduleroles_association?$select=roleid` }]);+});++test('appRoleIdsFor fails closed with the reasons verify has always given', async () => {+ assert.deepStrictEqual(await appRoleIdsFor(fakeSdk({ appRows: [] }), 'gone_app'), { ok: false, reason: "app 'gone_app' could not be resolved" });+ assert.deepStrictEqual(await appRoleIdsFor(fakeSdk({ status: 403 }), 'a'), { ok: false, reason: 'HTTP 403' });+ assert.deepStrictEqual(await appRoleIdsFor({ queryRecords: async () => [{ appmoduleid: APP_ID }] }, 'a'), { ok: false, reason: 'SDK dataverse reader is unavailable' });+ const thrown = await appRoleIdsFor(fakeSdk({ get: async () => { throw new Error('x'.repeat(300)); } }), 'a');+ assert.strictEqual(thrown.ok, false);+ assert.strictEqual(thrown.reason.length, 200, 'the reason is cut at 200 characters');+ assert.strictEqual((await appRoleIdsFor({ queryRecords: async () => { throw new Error(); } }, 'a')).reason, 'read failed');+});++test('appRoleIdsFor reads an answer that is not a list exactly as verify always did: no body is no ids, a value that is no list is the TypeError verify has always reported', async () => {+ for (const body of [{}, null, { value: null }]) assert.deepStrictEqual(await appRoleIdsFor(fakeSdk({ get: async () => ({ status: 200, body }) }), 'a'), { ok: true, roleIds: [] }, JSON.stringify(body));+ assert.deepStrictEqual(+ await appRoleIdsFor(fakeSdk({ body: { value: 'malformed' } }), 'a'),+ { ok: false, reason: '((res.body && res.body.value) || []).map is not a function' },+ 'the reason verify gave before the design document read the same relationship',+ );+});++// --- the read the design document makes -----------------------------------------------------------------------------------------------++test('appRolesOf finds the app in the SAVED layer — the SDK\u2019s own lookup, which finds a draft — and lists its roles, by name', async () => {+ const sdk = fakeSdk({ rows: [+ { roleid: ROLE_B, name: 'Zeta', ismanaged: true },+ { roleid: ROLE_A, name: 'alpha', ismanaged: false },+ { roleid: '00000000-0000-4000-8000-0000000000cc', name: 'Alpha' },+ ] });+ const answer = await appRolesOf(sdk, 'contoso_pm');+ assert.deepStrictEqual(sdk.calls.map((c) => c.method), ['resolveArtifact', 'get'], 'not the published-layer lookup verify makes');+ assert.deepStrictEqual(sdk.calls[0], { method: 'resolveArtifact', type: 'app', query: { uniqueName: 'contoso_pm' } });+ assert.deepStrictEqual(sdk.calls[1], { method: 'get', url: ASSOCIATION });+ assert.strictEqual(answer.state, 'read');+ assert.strictEqual(answer.appUnique, 'contoso_pm');+ assert.strictEqual(answer.appId, APP_ID);+ // By name with the letter case ignored, then by the name as written (code units: a capital first), then by id: the same order on every machine.+ assert.deepStrictEqual(answer.roles, [+ { roleId: '00000000-0000-4000-8000-0000000000cc', name: 'Alpha', managed: false },+ { roleId: ROLE_A.toLowerCase(), name: 'alpha', managed: false },+ { roleId: ROLE_B.toLowerCase(), name: 'Zeta', managed: true },+ ]);+});++test('appRolesOf says an app is absent only when the saved layer has no app, and reads no association', async () => {+ const sdk = fakeSdk({ resolve: async () => [] });+ assert.deepStrictEqual(await appRolesOf(sdk, 'contoso_pm'), { state: 'absent', appUnique: 'contoso_pm' });+ assert.deepStrictEqual(sdk.calls.map((c) => c.method), ['resolveArtifact']);+});++test('a draft app — saved, never published — is found, so it is never "absent": its roles are read if the platform answers, and not checked if it does not', async () => {+ // The published-layer lookup finds nothing for a draft (a draft answers 404 by id); the saved layer holds it.+ const answered = fakeSdk({ appRows: [], rows: [{ roleid: ROLE_A, name: 'Viewer' }] });+ assert.strictEqual((await appRolesOf(answered, 'contoso_pm')).state, 'read');+ assert.deepStrictEqual(answered.calls.map((c) => c.method), ['resolveArtifact', 'get'], 'the published layer is not asked');+ const refused = await appRolesOf(fakeSdk({ appRows: [], status: 404 }), 'contoso_pm');+ assert.deepStrictEqual(refused, { state: 'unreadable', appUnique: 'contoso_pm', reason: 'HTTP 404' });+});++test('a malformed or partial answer is "not checked", never evidence of no roles — only a list with nothing in it is', async () => {+ const bad = [+ ['no body', null],+ ['an empty object', {}],+ ['a value that is no list', { value: 'malformed' }],+ ['a null value', { value: null }],+ ['a row that is no object', { value: [null] }],+ ['a row with no role id', { value: [{ name: 'Viewer' }] }],+ ['a role id that is no text', { value: [{ roleid: 5 }] }],+ ['an empty role id', { value: [{ roleid: '' }] }],+ ['one good row beside a bad one', { value: [{ roleid: ROLE_A, name: 'Viewer' }, {}] }],+ ['a continuation link that is no link', { value: [{ roleid: ROLE_A, name: 'Viewer' }], '@odata.nextLink': 5 }],+ ];+ for (const [what, body] of bad) {+ const answer = await appRolesOf(fakeSdk({ get: async () => ({ status: 200, headers: {}, body }) }), 'contoso_pm');+ assert.strictEqual(answer.state, 'unreadable', `${what}: ${JSON.stringify(answer)}`);+ assert.ok(answer.reason && answer.reason.length <= 200, `${what}: it says why`);+ }+ assert.deepStrictEqual(await appRolesOf(fakeSdk({ rows: [] }), 'contoso_pm'), { state: 'read', appUnique: 'contoso_pm', appId: APP_ID, roles: [] }, 'a list with nothing in it is the one answer that says there are none');+});++test('a role the answer lists without a name is still a role: it is listed with the empty name, and found by its id', async () => {+ const answer = await appRolesOf(fakeSdk({ rows: [{ roleid: ROLE_A }] }), 'contoso_pm');+ assert.deepStrictEqual(answer.roles, [{ roleId: ROLE_A.toLowerCase(), name: '', managed: false }]);+});++test('a list the platform answers a page at a time is read to its end, and a link that repeats is not checked', async () => {+ const next = `${ORIGIN}/api/data/v9.0/appmodules(${APP_ID})/appmoduleroles_association?$select=roleid,name,ismanaged&$skiptoken=2`;+ const pages = fakeSdk({ get: async (url) => (/skiptoken=2/.test(url)+ ? { status: 200, body: { value: [{ roleid: ROLE_B, name: 'Beta' }] } }+ : { status: 200, body: { value: [{ roleid: ROLE_A, name: 'Alpha' }], '@odata.nextLink': next } }) });+ const answer = await appRolesOf(pages, 'contoso_pm');+ assert.deepStrictEqual(answer.roles.map((r) => r.name), ['Alpha', 'Beta']);+ assert.deepStrictEqual(pages.calls.filter((c) => c.method === 'get').map((c) => c.url), [ASSOCIATION, next]);+ const loop = await appRolesOf(fakeSdk({ get: async () => ({ status: 200, body: { value: [{ roleid: ROLE_A }], '@odata.nextLink': ASSOCIATION } }) }), 'contoso_pm');+ assert.strictEqual(loop.state, 'unreadable');+ assert.match(loop.reason, /repeated/);+});++test('appRolesOf never throws: a refused read, a failed lookup and an SDK without the methods are all "unreadable", with the reason', async () => {+ assert.deepStrictEqual(await appRolesOf(fakeSdk({ status: 403 }), 'a'), { state: 'unreadable', appUnique: 'a', reason: 'HTTP 403' });+ assert.deepStrictEqual(await appRolesOf(fakeSdk({ resolve: async () => { throw new Error('the lookup was refused'); } }), 'a'), { state: 'unreadable', appUnique: 'a', reason: 'the lookup was refused' });+ assert.deepStrictEqual(await appRolesOf({ dataverse: { get: async () => ({ status: 200, body: { value: [] } }) } }, 'a'), { state: 'unreadable', appUnique: 'a', reason: 'the SDK has no app lookup' });+ assert.deepStrictEqual(await appRolesOf({ resolveArtifact: async () => [{ id: APP_ID }] }, 'a'), { state: 'unreadable', appUnique: 'a', reason: 'SDK dataverse reader is unavailable' });+ for (const answer of [null, 'x', {}, [null], [{}], [{ id: '' }]]) {+ assert.strictEqual((await appRolesOf(fakeSdk({ resolve: async () => answer }), 'a')).state, 'unreadable', `a lookup that answers ${JSON.stringify(answer)} did not find an app`);+ }+ const long = await appRolesOf(fakeSdk({ get: async () => { throw new Error('y'.repeat(500)); } }), 'a');+ assert.strictEqual(long.state, 'unreadable');+ assert.strictEqual(long.reason.length, 200);+});++// --- the real bundle ---------------------------------------------------------------------------------------------------------------------++const client = (org) => createAzHttpClient(ORIGIN, { getToken: () => 'test-token', request: org.request, sleep: async () => {} });+const association = (rows) => (req) => (req.method === 'GET' && /\/appmoduleroles_association\?/.test(req.path) ? json(200, { value: rows }) : undefined);+const read = (org) => withThrowawaySdk({ env: ORIGIN, prefix: 'app-roles-test-', httpClient: client(org) }, (make) => appRolesOf(make(), 'contoso_pm'));+const published = { appmoduleid: APP_ID, name: 'Contoso PM', uniquename: 'contoso_pm', componentstate: 0 };+const draft = { ...published, componentstate: 1 };++test('REAL BUNDLE: a published app is found, its roles are read with one GET, and nothing is written', async () => {+ const org = createFakeAppsOrg({+ apps: [published],+ answer: association([{ roleid: ROLE_A, name: 'Contoso PM - Viewer', ismanaged: false }, { roleid: ROLE_B, name: 'Contoso PM - Project Manager', ismanaged: true }]),+ });+ const answer = await read(org);+ assert.strictEqual(answer.state, 'read', JSON.stringify(answer));+ assert.deepStrictEqual(answer.roles.map((r) => [r.name, r.managed]), [['Contoso PM - Project Manager', true], ['Contoso PM - Viewer', false]]);+ assert.deepStrictEqual(org.writes(), []);+ assert.deepStrictEqual(org.unexpected, []);+ const gets = org.requests.filter((r) => /appmoduleroles_association/.test(r.path));+ assert.deepStrictEqual(gets.map((r) => `${r.method} ${r.path}`), [`GET ${ASSOCIATION}`]);+});++test('REAL BUNDLE: a draft app — saved, never published — is not absent: it is in the list apps.js shows, its roles are read when the platform answers them', async () => {+ const org = createFakeAppsOrg({ apps: [draft], answer: association([{ roleid: ROLE_A, name: 'Viewer' }]) });+ const answer = await read(org);+ assert.strictEqual(answer.state, 'read', JSON.stringify(answer));+ assert.deepStrictEqual(answer.roles.map((r) => r.name), ['Viewer']);+ assert.deepStrictEqual(org.writes(), []);+ const { listApps } = require('../apps.js');+ const listed = await listApps(ORIGIN, {}, client(org));+ assert.deepStrictEqual(listed.apps.map((a) => [a.uniqueName, a.published, a.unpublishedChanges]), [['contoso_pm', false, true]], 'the same app, as the plugin\u2019s own listing sees it');+});++test('REAL BUNDLE: a draft whose roles the platform will not read is "not checked" with its status — never "absent"', async () => {+ const org = createFakeAppsOrg({ apps: [draft], answer: (req) => (/appmoduleroles_association/.test(req.path) ? json(404, { error: { message: 'appmodule With Id does not exist' } }) : undefined) });+ const answer = await read(org);+ assert.deepStrictEqual(answer, { state: 'unreadable', appUnique: 'contoso_pm', reason: 'HTTP 404' });+ assert.deepStrictEqual(org.writes(), []);+});++test('REAL BUNDLE: an app neither layer has is absent, and no association is read', async () => {+ const org = createFakeAppsOrg({ apps: [], answer: association([{ roleid: ROLE_A, name: 'R' }]) });+ assert.deepStrictEqual(await read(org), { state: 'absent', appUnique: 'contoso_pm' });+ assert.deepStrictEqual(org.writes(), []);+ assert.ok(!org.requests.some((r) => /appmoduleroles_association/.test(r.path)), 'no app, no association read');+});++test('REAL BUNDLE: a refused association read is unreadable with its status, and writes nothing', async () => {+ const refused = createFakeAppsOrg({+ apps: [published],+ answer: (req) => (/appmoduleroles_association/.test(req.path) ? json(403, { error: { code: '0x80040220', message: 'denied' } }) : undefined),+ });+ const answer = await read(refused);+ assert.deepStrictEqual(answer, { state: 'unreadable', appUnique: 'contoso_pm', reason: 'HTTP 403' });+ assert.deepStrictEqual(refused.writes(), []);+});++test('REAL BUNDLE: a lookup the platform refuses is "not checked", not "absent"', async () => {+ for (const status of [403, 404, 500]) {+ const org = createFakeAppsOrg({ answer: (req) => (req.path.startsWith('/appmodules/') ? json(status, { error: { message: 'lookup denied' } }) : undefined) });+ const answer = await read(org);+ assert.strictEqual(answer.state, 'unreadable', `${status}: ${JSON.stringify(answer)}`);+ assert.deepStrictEqual(org.writes(), []);+ }+});++test('REAL BUNDLE: a 200 that carries no list of roles is "not checked", not "no roles"', async () => {+ for (const body of [{}, { value: 'malformed' }, { value: [{}] }]) {+ const org = createFakeAppsOrg({ apps: [published], answer: (req) => (/appmoduleroles_association/.test(req.path) ? json(200, body) : undefined) });+ const answer = await read(org);+ assert.strictEqual(answer.state, 'unreadable', `${JSON.stringify(body)}: ${JSON.stringify(answer)}`);+ assert.deepStrictEqual(org.writes(), []);+ }+});++test('REAL BUNDLE: a list the platform answers a page at a time is read to its end through the client\u2019s own continuation', async () => {+ const link = `${ORIGIN}/api/data/v9.0/appmodules(${APP_ID})/appmoduleroles_association?$select=roleid,name,ismanaged&$skiptoken=2`;+ const org = createFakeAppsOrg({+ apps: [published],+ answer: (req) => {+ if (!/appmoduleroles_association/.test(req.path)) return undefined;+ return /skiptoken=2/.test(req.path)+ ? json(200, { value: [{ roleid: ROLE_B, name: 'Beta' }] })+ : json(200, { value: [{ roleid: ROLE_A, name: 'Alpha' }], '@odata.nextLink': link });+ },+ });+ const answer = await read(org);+ assert.deepStrictEqual(answer.roles && answer.roles.map((r) => r.name), ['Alpha', 'Beta'], JSON.stringify(answer));+ assert.deepStrictEqual(org.writes(), []);+});++test('REAL BUNDLE: verify\u2019s published-layer reader still answers what it did, over the same fake', async () => {+ const org = createFakeAppsOrg({ apps: [published], answer: association([{ roleid: ROLE_A }, { roleid: ROLE_B }]) });+ const answer = await withThrowawaySdk({ env: ORIGIN, prefix: 'app-roles-test-', httpClient: client(org) }, (make) => appRoleIdsFor(make(), 'contoso_pm'));+ assert.deepStrictEqual(answer, { ok: true, roleIds: [ROLE_A.toLowerCase(), ROLE_B.toLowerCase()] });+ assert.ok(org.requests.some((r) => r.path === `/appmodules(${APP_ID})/appmoduleroles_association?$select=roleid`));+ assert.deepStrictEqual(org.writes(), []);+});++test('REAL BUNDLE: verify reads an answer that carries no list as it always did', async () => {+ for (const [body, expected] of [[{}, { ok: true, roleIds: [] }], [{ value: 'malformed' }, { ok: false, reason: '((res.body && res.body.value) || []).map is not a function' }]]) {+ const org = createFakeAppsOrg({ apps: [published], answer: (req) => (/appmoduleroles_association/.test(req.path) ? json(200, body) : undefined) });+ const answer = await withThrowawaySdk({ env: ORIGIN, prefix: 'app-roles-test-', httpClient: client(org) }, (make) => appRoleIdsFor(make(), 'contoso_pm'));+ assert.deepStrictEqual(answer, expected, JSON.stringify(body));+ }+});diff --git a/plugins/model-apps/scripts/tests/app-spec-doc-access.test.js b/plugins/model-apps/scripts/tests/app-spec-doc-access.test.jsnew file mode 100644index 000000000..c0e97af5d--- /dev/null+++ b/plugins/model-apps/scripts/tests/app-spec-doc-access.test.js@@ -0,0 +1,427 @@+'use strict';+// The design document and its design-gap warnings, for the same two situations the lint is told apart by (spec-lint-app-access.test.js): a+// downloaded app extended with a new table while `personas[]` is left empty on purpose, and a spec for an app that does not exist yet.+//+// The document used to say, for every spec with no personas, that the app "will open only for system administrators". Who can open a DEPLOYED app+// is decided by the roles associated with it, which a spec that authors no role does not change — so the document now says what the spec+// authors, keeps two questions apart (who can open the APP; who can use the TABLES the spec introduces), and — when the environment is read with+// --env — says what the environment holds.+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { execFileSync } = require('node:child_process');+const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');+const { designGaps } = require('../write-app-spec-doc.js');+const { extensionSpec, newAppSpec, grant, persona, appWithRoles } = require('./helpers/app-access-specs.js');++const CLI = path.join(__dirname, '..', 'write-app-spec-doc.js');+const ENV = 'https://contoso.crm.dynamics.com';+const ADMIN_ONLY = /only for (system )?admin|opens only|administrator-only|admin-only|only administrators/i;++// The text between a heading and the next heading of the same or a higher level, or null when the document has no such heading.+function findSection(md, heading) {+ const level = heading.match(/^#+/)[0].length;+ const start = md.indexOf(`\n${heading}\n`);+ if (start === -1) return null;+ const rest = md.slice(start + heading.length + 2);+ const end = rest.search(new RegExp(`\\n#{1,${level}} `));+ return end === -1 ? rest : rest.slice(0, end);+}++// The same, for a section the document must have: a missing one fails here, with the document, and not as a match against null.+function section(md, heading) {+ const found = findSection(md, heading);+ assert.notEqual(found, null, `the document has no "${heading}" section:\n${md}`);+ return found;+}++// --- what the document says about a spec that authors no role -------------------------------------------------------------------------------++test('the no-personas callout does not say an extension of an existing app opens only for administrators', () => {+ const md = renderAppSpecDoc(extensionSpec());+ const jobs = section(md, '## Jobs to be done');+ assert.match(jobs, /> ⚠ No `personas\[\]` were captured/, 'still says no jobs were recorded');+ assert.match(jobs, /authors no security role/);+ assert.doesNotMatch(md, ADMIN_ONLY, 'nowhere in the document');+});++test('a spec that authors no role gets a Security section that says so and says what a new or an existing app does', () => {+ const md = renderAppSpecDoc(extensionSpec());+ assert.match(section(md, '## Security'), /This spec authors no security role/, 'the section is there although there are no personas');+ const access = section(md, '### Access to the app');+ assert.match(access, /already exists/);+ assert.match(access, /not by this spec/);+ assert.match(access, /--env/, 'says how to read the roles the app has');++ const fresh = renderAppSpecDoc(newAppSpec());+ assert.match(section(fresh, '### Access to the app'), /If the app is new, it is associated with the System Administrator role only/);+ assert.match(section(fresh, '### Access to the app'), /if it already exists, it keeps the roles it has/);+});++test('the design gap for no jobs says the spec authors no role, not that the app is administrator-only', () => {+ for (const spec of [extensionSpec(), newAppSpec()]) {+ const gaps = designGaps(spec);+ const noJobs = gaps.find((g) => /no jobs-to-be-done captured/.test(g));+ assert.ok(noJobs, JSON.stringify(gaps));+ assert.doesNotMatch(noJobs, ADMIN_ONLY);+ assert.match(noJobs, /authors no security role/);+ }+});++// --- the tables the spec introduces -------------------------------------------------------------------------------------------------++test('a new table nothing grants is a design gap and is called out in the document', () => {+ const spec = extensionSpec();+ const gaps = designGaps(spec);+ const flagged = gaps.filter((g) => /no access declared/.test(g));+ assert.equal(flagged.length, 1, JSON.stringify(gaps));+ assert.match(flagged[0], /contoso_baseline/);+ assert.match(flagged[0], /cannot use it until a grant is made/);++ const md = renderAppSpecDoc(spec);+ const callout = section(md, '### Tables with no access declared');+ assert.ok(callout, 'a sub-heading of the Security section');+ assert.match(callout, /> ⚠ `contoso_baseline` is introduced by this spec/);+ assert.match(callout, /roleGrants\[\]/);+ assert.doesNotMatch(callout, /contoso_project/, 'a table the app already holds is not introduced by this spec');+});++test('a roleGrants[] entry that covers the new table clears the gap, and the extended role and its privileges are in the document', () => {+ const spec = extensionSpec();+ spec.roleGrants = [grant('Contoso PM - Project Manager', 'contoso_baseline', ['create', 'read', 'write'], 'organization')];+ assert.deepEqual(designGaps(spec).filter((g) => /no access declared/.test(g)), []);++ const md = renderAppSpecDoc(spec);+ assert.equal(findSection(md, '### Tables with no access declared'), null);+ const extended = section(md, '### Roles extended by `roleGrants[]`');+ assert.ok(extended);+ assert.match(extended, /ADDS the privileges below and removes none/);+ assert.match(extended, /does not associate the role with the app/);+ assert.match(extended, /\| Contoso PM - Project Manager \| contoso_baseline \| create, read, write \| organization \|/);+});++test('a grant given by role id is shown by its id, and a split of scopes stays two rows', () => {+ const spec = extensionSpec();+ spec.roleGrants = [{+ roleId: '33333333-3333-3333-3333-333333333333',+ privileges: [+ { entity: 'contoso_baseline', access: ['read'], scope: 'organization' },+ { entity: 'contoso_baseline', access: ['write'], scope: 'user' },+ ],+ }];+ const extended = section(renderAppSpecDoc(spec), '### Roles extended by `roleGrants[]`');+ assert.match(extended, /\| 33333333-3333-3333-3333-333333333333 \| contoso_baseline \| read \| organization \|/);+ assert.match(extended, /\| 33333333-3333-3333-3333-333333333333 \| contoso_baseline \| write \| user \|/);+});++test('personas that cover every table leave the Security section as it was: no new sub-section', () => {+ const spec = newAppSpec();+ spec.pages = [{ key: 'overview', name: 'Overview', source: { kind: 'intent' } }];+ spec.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read', 'write'], scope: 'user' }])];+ const md = renderAppSpecDoc(spec);+ const security = section(md, '## Security');+ assert.match(security, /### Role: Agent/);+ assert.doesNotMatch(security, /### Access to the app/);+ assert.doesNotMatch(security, /### Tables with no access declared/);+ assert.doesNotMatch(security, /### Roles extended by/);+ assert.deepEqual(designGaps(spec).filter((g) => /access|role/i.test(g)), []);+});++test('personas that leave one table without a privilege get that table called out beside the roles they author', () => {+ const spec = newAppSpec({ tables: ['contoso_ticket', 'contoso_note'] });+ spec.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'] }])];+ const security = section(renderAppSpecDoc(spec), '## Security');+ assert.match(security, /### Role: Agent/);+ assert.match(section(renderAppSpecDoc(spec), '### Tables with no access declared'), /`contoso_note`/);+ assert.equal(designGaps(spec).filter((g) => /no access declared/.test(g)).length, 1);+});++// --- what the environment says (--env) ------------------------------------------------------------------------------------------------++test('with a read of the environment, the roles associated with the app are listed apart from the privileges on the new tables', () => {+ const spec = extensionSpec();+ spec.roleGrants = [grant('Contoso PM - Project Manager', 'contoso_baseline')];+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles('Contoso PM - Project Manager', 'Contoso PM - Viewer') });+ const access = section(md, '### Access to the app');+ assert.ok(access);+ assert.match(access, /The app `contoso_pm` already exists in https:\/\/contoso\.crm\.dynamics\.com and these roles are associated with it/);+ assert.match(access, /\| Contoso PM - Project Manager \| may be the role `roleGrants\[\]` extends \(matched by name only\) \|/, 'the grant names the role, not its id');+ assert.match(access, /\| Contoso PM - Viewer \| not touched by this spec \|/);+ assert.match(access, /leaves these associations as they are/);+ assert.match(access, /privileges on the tables this spec introduces are declared separately/);+ assert.doesNotMatch(md, ADMIN_ONLY);+ // The two questions are two sections: the roles are in one, the privileges for the new table in the other.+ assert.ok(md.indexOf('### Access to the app') < md.indexOf('### Roles extended by'));+ assert.doesNotMatch(section(md, '### Roles extended by `roleGrants[]`'), /Contoso PM - Viewer/);+});++test('a role a grant names by its id is the role it extends: the one case the table says so without a "may"', () => {+ const spec = extensionSpec();+ spec.roleGrants = [grant('00000000-0000-4000-8000-000000000002', 'contoso_baseline')];+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles('Viewer', 'Viewer') });+ const access = section(md, '### Access to the app');+ const rows = access.split('\n').filter((l) => /^\| Viewer \|/.test(l));+ assert.equal(rows.length, 2);+ assert.equal(rows.filter((l) => /\| extended by `roleGrants\[\]` \|/.test(l)).length, 1, 'only the role of that id, not the other that has its name');+ assert.equal(rows.filter((l) => /\| not touched by this spec \|/.test(l)).length, 1);+ const extended = section(md, '### Roles extended by `roleGrants[]`');+ assert.doesNotMatch(extended, /is named without a role id|is not among/);+});++test('a role a grant names only by name may be one of several: it is never named as the role the grant extends — roles are per business unit', () => {+ const BU = '11111111-1111-4111-8111-111111111111';+ const spec = extensionSpec();+ spec.roleGrants = [{ ...grant('Viewer', 'contoso_baseline'), businessUnitId: BU }];+ // One associated role has that name. The build resolves the grant's role by name AND business unit, and the answer carries no business unit.+ const one = renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles({ name: 'Viewer', roleId: '00000000-0000-4000-8000-000000000002' }) });+ const oneAccess = section(one, '### Access to the app');+ assert.doesNotMatch(oneAccess, /\| Viewer \| extended by `roleGrants\[\]` \|/);+ assert.match(oneAccess, /\| Viewer \| may be the role `roleGrants\[\]` extends \(matched by name only\) \|/);+ const oneNote = section(one, '### Roles extended by `roleGrants[]`');+ assert.match(oneNote, /Role "Viewer" is named without a role id: 1 associated role has that name \(id 00000000-0000-4000-8000-000000000002\), and roles are per business unit, so it may not be the role this grant extends\. Pin the role with `roleId` to be sure\./);+ assert.doesNotMatch(oneNote, /is not among the roles associated/, 'and it is not reported missing either');+ assert.deepEqual(designGaps(spec, { envUrl: ENV, appAccess: appWithRoles({ name: 'Viewer', roleId: '00000000-0000-4000-8000-000000000002' }) }).filter((g) => /Viewer/.test(g)), []);++ // Two associated roles have it: every candidate is listed, and neither is called the role the grant extends.+ const two = renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles('Viewer', 'Viewer') });+ const rows = section(two, '### Access to the app').split('\n').filter((l) => /^\| Viewer \|/.test(l));+ assert.equal(rows.length, 2);+ assert.ok(rows.every((l) => /may be the role `roleGrants\[\]` extends \(matched by name only\)/.test(l)), rows.join('\n'));+ assert.match(section(two, '### Roles extended by `roleGrants[]`'), /Role "Viewer" is named without a role id: 2 associated roles have that name \(ids 00000000-0000-4000-8000-000000000001, 00000000-0000-4000-8000-000000000002\), and roles are per business unit, so at most one of them is the role this grant extends\. Pin the role with `roleId` to be sure\./);+});++test('a persona is matched to an associated role by name only, so the role may be its own — and the build\u2019s action on it is said as what the persona asks', () => {+ const spec = newAppSpec();+ spec.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'] }])];+ const access = section(renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles('agent', 'Contoso Auditor') }), '### Access to the app');+ assert.match(access, /\| agent \| may be the role of persona `Agent` \(matched by name\); if it is, a build keeps this association \|/, 'matched by name in any letter case');+ assert.match(access, /\| Contoso Auditor \| not touched by this spec \|/);+});++test('an existing app with no role associated with it is the one case the document may call administrator-only — it has read the environment', () => {+ const spec = extensionSpec();+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles() });+ const access = section(md, '### Access to the app');+ assert.match(access, /no role is associated with it, so only administrators and other makers/);+ assert.match(access, /This spec associates none with it \(it authors no role\), so that does not change\./);+ const gaps = designGaps(spec, { envUrl: ENV, appAccess: appWithRoles() });+ assert.ok(gaps.some((g) => /exists in https:\/\/contoso\.crm\.dynamics\.com with no role associated with it/.test(g)), JSON.stringify(gaps));+});++test('an app the environment does not have yet is, with no persona that gets the app, one that only administrators can open once built', () => {+ const spec = newAppSpec();+ const appAccess = { state: 'absent', appUnique: 'contoso_support' };+ const access = section(renderAppSpecDoc(spec, { envUrl: ENV, appAccess }), '### Access to the app');+ assert.match(access, /does not exist in https:\/\/contoso\.crm\.dynamics\.com yet/);+ assert.match(access, /associates the System Administrator role with it/);+ assert.match(access, /users without a maker-level role cannot open it until a role is associated with it/);+ const gaps = designGaps(spec, { envUrl: ENV, appAccess });+ assert.ok(gaps.some((g) => /does not exist in https:\/\/contoso\.crm\.dynamics\.com yet/.test(g)), JSON.stringify(gaps));++ // With a persona that gets the app, the build associates its role, says which, and nothing needs warning of.+ spec.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'] }])];+ assert.deepEqual(designGaps(spec, { envUrl: ENV, appAccess }).filter((g) => /does not exist/.test(g)), []);+ const withPersona = section(renderAppSpecDoc(spec, { envUrl: ENV, appAccess }), '### Access to the app');+ assert.match(withPersona, /and the role of persona `Agent`\./);+ assert.doesNotMatch(withPersona, /roles authored above/);+});++// --- a persona that opts out of the app, and a persona that gets it ------------------------------------------------------------------------+// A persona's role is associated with the app unless `appAccess: false` — which makes the build REMOVE the association (sdk-build.js, security phase). So what the document+// says of the roles a build associates follows the personas' `appAccess`, not whether there are personas at all.++const readerOptedOut = () => {+ const spec = newAppSpec();+ spec.personas = [persona('Reader', [{ entity: 'contoso_ticket', access: ['read'] }], { appAccess: false })];+ return spec;+};+const agentGetsApp = () => {+ const spec = newAppSpec();+ spec.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'] }])];+ return spec;+};++test('a spec whose only persona opts out of the app associates no role with it: a new app is still administrator-only once built, and the document says so', () => {+ const spec = readerOptedOut();+ const absent = { state: 'absent', appUnique: 'contoso_support' };+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess: absent });+ assert.match(section(md, '## Security'), /_Data-only — the app is \*\*not\*\* granted to this role\._/);+ const access = section(md, '### Access to the app');+ assert.doesNotMatch(access, /roles authored above|and the role of persona/, 'the data-only persona gets no association');+ assert.match(access, /this spec associates no other role \(its personas are data-only: `appAccess: false`\), so users without a maker-level role cannot open it until a role is associated with it/);+ const gaps = designGaps(spec, { envUrl: ENV, appAccess: absent });+ assert.ok(gaps.some((g) => /does not exist in https:\/\/contoso\.crm\.dynamics\.com yet and this spec associates no role with it, so once built it opens only for administrators and other makers/.test(g)), JSON.stringify(gaps));+});++test('an existing app with no role associated with it, and a spec whose persona opts out, is still one nothing here associates a role with', () => {+ const spec = readerOptedOut();+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles() });+ const access = section(md, '### Access to the app');+ assert.match(access, /no role is associated with it, so only administrators and other makers/);+ assert.doesNotMatch(access, /associates the app with the role/);+ assert.match(access, /This spec associates none with it \(its personas are data-only: `appAccess: false`\), so that does not change\./);+ const gaps = designGaps(spec, { envUrl: ENV, appAccess: appWithRoles() });+ assert.ok(gaps.some((g) => /with no role associated with it, so only administrators and other makers can open it, and this spec associates none with it/.test(g)), JSON.stringify(gaps));+});++test('a persona that gets the app is named where the document says what a build associates, and the gap that the app has no role is not raised', () => {+ const spec = agentGetsApp();+ const empty = section(renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles() }), '### Access to the app');+ assert.match(empty, /A build with this spec associates the app with the role of persona `Agent`\./);+ assert.deepEqual(designGaps(spec, { envUrl: ENV, appAccess: appWithRoles() }).filter((g) => /no role associated/.test(g)), []);+});++test('a failed read does not turn the words for a spec with no personas into the words for a spec that has some', () => {+ const unreadable = { state: 'unreadable', appUnique: 'contoso_support', reason: 'HTTP 403' };+ // A persona that gets the app: what the build does for it, not "personas[] does that" (it has one).+ const gets = section(renderAppSpecDoc(agentGetsApp(), { envUrl: ENV, appAccess: unreadable }), '### Access to the app');+ assert.match(gets, /A build associates the app with the role of persona `Agent`\./);+ assert.doesNotMatch(gets, /personas\[\] does that/);+ // A persona that opts out, on an app that exists: the build removes the association, so the roles are not simply "left as they are".+ const optedOut = readerOptedOut();+ optedOut.app.uniqueName = 'contoso_support';+ const removes = section(renderAppSpecDoc(optedOut, { envUrl: ENV, appAccess: unreadable }), '### Access to the app');+ assert.match(removes, /removes the app from the role of persona `Reader` \(`appAccess: false`\) if it has it/);+ assert.match(removes, /It carries app\.uniqueName/);+ assert.doesNotMatch(removes, /a build leaves the roles associated with an existing app as they are:/, 'the exception is part of the sentence');+ assert.match(removes, /changes the roles associated with an existing app only for its personas/);+});++test('with the roles read, the build\u2019s action on each persona is said by what the persona asks: it keeps the association of one that gets the app and removes that of one that opts out', () => {+ const spec = agentGetsApp();+ spec.personas.push(persona('Reader', [{ entity: 'contoso_ticket', access: ['read'] }], { appAccess: false }));+ const access = section(renderAppSpecDoc(spec, { envUrl: ENV, appAccess: appWithRoles('Agent', 'Reader', 'Contoso Auditor') }), '### Access to the app');+ assert.match(access, /\| Agent \| may be the role of persona `Agent` \(matched by name\); if it is, a build keeps this association \|/);+ assert.match(access, /\| Reader \| may be the role of persona `Reader` \(matched by name, `appAccess: false`\); if it is, a build removes this association \|/);+ assert.match(access, /A build with this spec associates the app with the role of persona `Agent`, removes it from the role of persona `Reader` \(`appAccess: false`\) where it is associated, and leaves every other association as it is\./);+ assert.match(access, /\| Contoso Auditor \| not touched by this spec \|/);+});++// --- every line of the access section follows the structured answer --------------------------------------------------------------------------+// The sentences are chosen from the personas' `appAccess` and from the read's state, in one place (lib/app-access.js appAccessModel): whichever way a spec and an+// answer combine, the document, the warnings and the model agree on who gets the app and on whether it is administrator-only.++test('across personas that get the app, personas that opt out, and every state of the read, the sentences agree with the model', () => {+ const { appAccessModel } = require('../lib/app-access.js');+ const personaSets = {+ none: () => [],+ gets: () => [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'] }])],+ optedOut: () => [persona('Reader', [{ entity: 'contoso_ticket', access: ['read'] }], { appAccess: false })],+ both: () => [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'] }]), persona('Reader', [{ entity: 'contoso_ticket', access: ['read'] }], { appAccess: false })],+ };+ const reads = {+ absent: { state: 'absent', appUnique: 'contoso_support' },+ empty: appWithRoles(),+ roles: appWithRoles('Contoso Auditor'),+ unreadable: { state: 'unreadable', appUnique: 'contoso_support', reason: 'HTTP 403' },+ };+ const CURRENTLY_ADMIN_ONLY = /no role is associated with it, so only administrators and other makers/;+ const STAYS_ADMIN_ONLY = /so that does not change\.|cannot open it until a role is associated with it\./;+ let combinations = 0;+ for (const [personaName, makePersonas] of Object.entries(personaSets)) {+ for (const [readName, appAccess] of Object.entries(reads)) {+ for (const marked of [false, true]) {+ const spec = newAppSpec();+ spec.personas = makePersonas();+ if (marked) spec.app.uniqueName = 'contoso_support';+ const what = `${personaName} / ${readName} / ${marked ? 'marked' : 'unmarked'}`;+ const model = appAccessModel(spec, appAccess);+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess });+ const access = section(md, '### Access to the app');+ const gaps = designGaps(spec, { envUrl: ENV, appAccess });+ const noneGet = model.personas.gets.length === 0;+ // Administrator-only stays so exactly when the environment shows the app has no role (or does not have it yet) and no persona gets the app.+ const staysAdminOnly = noneGet && (readName === 'absent' || readName === 'empty');+ combinations += 1;++ assert.deepEqual(model.personas.gets, personaName === 'gets' || personaName === 'both' ? ['Agent'] : [], what);+ assert.deepEqual(model.personas.optedOut, personaName === 'optedOut' || personaName === 'both' ? ['Reader'] : [], what);+ assert.equal(CURRENTLY_ADMIN_ONLY.test(access), readName === 'empty', `the document says the app has no role only when it was read to have none: ${what}\n${access}`);+ assert.equal(STAYS_ADMIN_ONLY.test(access) && readName !== 'unreadable', staysAdminOnly, `the document says it stays administrator-only only when no persona gets it: ${what}\n${access}`);+ assert.equal(gaps.some((g) => /opens only for administrators and other makers|only administrators and other makers can open it/.test(g)), staysAdminOnly, `the warnings: ${what}\n${gaps.join('\n')}`);+ // Every persona that gets the app is named where a build's associations are said; none of those that opt out is.+ for (const name of model.personas.gets) assert.match(access, new RegExp(`the role of persona \`${name}\``), `${what}: ${name} gets the app`);+ if (noneGet) assert.doesNotMatch(access, /associates the app with the role|and the role of persona/, `${what}: no persona gets the app`);+ // Where a build could remove an association — the app has roles, or is not known — the persona that opts out is named with what the build does.+ if (readName === 'roles' || readName === 'unreadable') {+ for (const name of model.personas.optedOut) assert.match(access, new RegExp(`removes (it|the app) from the role of persona \`${name}\` \\(\`appAccess: false\`\\)`), `${what}: ${name} opts out`);+ }+ if (staysAdminOnly && model.personas.optedOut.length) assert.match(access, /its personas are data-only: `appAccess: false`/, what);+ assert.doesNotMatch(access, /roles authored above/, what);+ // A failed read states nothing about the roles, whatever the spec holds.+ if (readName === 'unreadable') {+ assert.match(access, /could not be read from https:\/\/contoso\.crm\.dynamics\.com \(HTTP 403\), so who can open it was not checked/, what);+ assert.ok(gaps.some((g) => /who can open it was not checked/.test(g)), what);+ }+ }+ }+ }+ assert.equal(combinations, 32);+});++test('a read that failed is said to be unchecked, in the document and in the warnings, and it states nothing about the roles', () => {+ const spec = extensionSpec();+ const appAccess = { state: 'unreadable', appUnique: 'contoso_pm', reason: 'HTTP 403' };+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess });+ const access = section(md, '### Access to the app');+ assert.match(access, /> ⚠ The roles associated with the app could not be read from https:\/\/contoso\.crm\.dynamics\.com \(HTTP 403\), so who can open it was not checked/);+ assert.match(access, /already exists/, 'falls back to what the spec itself can say');+ assert.doesNotMatch(md, ADMIN_ONLY);+ const gaps = designGaps(spec, { envUrl: ENV, appAccess });+ assert.ok(gaps.some((g) => /could not be read from https:\/\/contoso\.crm\.dynamics\.com \(HTTP 403\) — who can open it was not checked/.test(g)), JSON.stringify(gaps));+});++test('a roleGrants[] role the app does not have is named: its users get the privileges but may not be able to open the app', () => {+ const spec = extensionSpec();+ spec.roleGrants = [+ grant('Contoso PM - Project Manager', 'contoso_baseline'),+ grant('Contoso PM - Auditor', 'contoso_baseline'),+ grant('00000000-0000-4000-8000-000000000002', 'contoso_baseline'),+ grant('99999999-9999-4999-8999-999999999999', 'contoso_baseline'),+ ];+ // The grants are one per role in a valid spec; this checks the cross-reading, not the validator.+ const appAccess = appWithRoles('contoso pm - project manager', 'Contoso PM - Viewer');+ const md = renderAppSpecDoc(spec, { envUrl: ENV, appAccess });+ const extended = section(md, '### Roles extended by `roleGrants[]`');+ assert.match(extended, /> ⚠ Role "Contoso PM - Auditor" is not among the roles associated with the app/);+ assert.match(extended, /> ⚠ Role "99999999-9999-4999-8999-999999999999" is not among the roles associated with the app/);+ assert.doesNotMatch(extended, /Role "Contoso PM - Project Manager" is not among/, 'matched by name in any letter case');+ assert.doesNotMatch(extended, /Role "00000000-0000-4000-8000-000000000002" is not among/, 'matched by id');+ const gaps = designGaps(spec, { envUrl: ENV, appAccess });+ assert.equal(gaps.filter((g) => /is not among the roles associated with app 'contoso_pm'/.test(g)).length, 2, JSON.stringify(gaps));+ // Offline there is nothing to compare with, so nothing is said.+ assert.deepEqual(designGaps(spec).filter((g) => /is not among the roles/.test(g)), []);+});++test('a malformed discovery answer or spec renders instead of throwing', () => {+ for (const appAccess of [null, {}, { state: 'read' }, { state: 'read', roles: 'x' }, { state: 'read', roles: [null, {}, { name: 5 }] }, { state: 'nonsense' }]) {+ assert.doesNotThrow(() => renderAppSpecDoc(extensionSpec(), { envUrl: ENV, appAccess }), JSON.stringify(appAccess));+ assert.doesNotThrow(() => designGaps(extensionSpec(), { envUrl: ENV, appAccess }), JSON.stringify(appAccess));+ }+ for (const spec of [{ roleGrants: {} }, { roleGrants: [null, 'x'] }, { entities: [null, 'x', {}] }, { entities: {}, roleGrants: [{ role: 'R', privileges: 'x' }] }]) {+ assert.doesNotThrow(() => renderAppSpecDoc(spec, { appAccess: appWithRoles('R') }), JSON.stringify(spec));+ assert.doesNotThrow(() => designGaps(spec, { appAccess: appWithRoles('R') }), JSON.stringify(spec));+ }+});++// --- the command, offline ---------------------------------------------------------------------------------------------------------------++test('the command with no --env makes the same findings and reads no environment', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'appdoc-access-'));+ try {+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(extensionSpec()), 'utf8');+ const out = JSON.parse(execFileSync(process.execPath, [CLI, '--spec', `@${specPath}`], { encoding: 'utf8' }));+ assert.equal(out.ok, true);+ assert.ok(out.warnings.some((w) => /no jobs-to-be-done captured/.test(w) && !ADMIN_ONLY.test(w)), JSON.stringify(out.warnings));+ assert.ok(out.warnings.some((w) => /contoso_baseline.*no access declared/.test(w)), JSON.stringify(out.warnings));+ const md = fs.readFileSync(out.docPath, 'utf8');+ assert.doesNotMatch(md, ADMIN_ONLY);+ assert.match(md, /### Tables with no access declared/);+ assert.match(md, /The roles associated with the app were not read: pass `--env <envUrl>` to read them\./);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/scripts/tests/app-spec-doc.test.js b/plugins/model-apps/scripts/tests/app-spec-doc.test.jsindex 5993e14f5..ae5165271 100644--- a/plugins/model-apps/scripts/tests/app-spec-doc.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-doc.test.js@@ -53,7 +53,7 @@ function realisticSpec() {{name: 'Triage new tickets',description: 'See what came in overnight',- privileges: [{ entity: 'new_ticket', access: ['read', 'write'], scope: 'user' }],+ privileges: [{ entity: 'new_ticket', access: ['read', 'write'], scope: 'user' }, { entity: 'new_customer', access: ['read'], scope: 'organization' }],surfaces: ['Active Tickets', 'overview'],},{diff --git a/plugins/model-apps/scripts/tests/app-spec-key-size.test.js b/plugins/model-apps/scripts/tests/app-spec-key-size.test.jsnew file mode 100644index 000000000..9f6fb5f69--- /dev/null+++ b/plugins/model-apps/scripts/tests/app-spec-key-size.test.js@@ -0,0 +1,170 @@+'use strict';++// How much room an alternate key has beside its table's name column. The platform takes a key of at most 1,700 bytes, 2 for each character of+// text, and a name column is 850 characters at most — 1,700 bytes by themselves — so a key over the column and any other column cannot fit while+// the column is that long, and a key over it alone always does. The build decides where to make a key labelled in several languages from a floor+// of the key's size (lib/app-spec.js, keyBytesAtLeast): what the floor shows is certain, and what it leaves open the platform decides.+// Measured: a key over a name column of 850 characters alone was accepted, and the same key with a column of one character or of a hundred was+// refused (HTTP 400, code 0x80060895, "Index size exceeded the size limit of 1700 bytes").+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys++const { test } = require('node:test');+const assert = require('node:assert');+const { KEY_BYTES_LIMIT, PRIMARY_NAME_MAX_LENGTH, keyBytesAtLeast, keyCannotFitAt, keyHasRoomOnlyAfterLength, maxLengthSent } = require('../lib/app-spec.js');+const { SDK_COLUMN_TYPE } = require('../lib/entity-provision.js');++const entity = (primaryAttribute = { schemaName: 'new_Name', maxLength: 120 }, columns = [{ schemaName: 'new_code', type: 'Text' }]) => ({ schemaName: 'new_t', primaryAttribute, columns });+const key = (columns, extra = {}) => ({ schemaName: 'new_k', columns, ...extra });++test('the longest name column is exactly the bytes a key may hold', () => {+ assert.strictEqual(KEY_BYTES_LIMIT, 1700);+ assert.strictEqual(PRIMARY_NAME_MAX_LENGTH * 2, KEY_BYTES_LIMIT, '850 characters, 2 bytes each');+});++test('a text column takes 2 bytes for each character: the name column at the length it has, another at its maxLength, else the 100 the SDK gives it', () => {+ const e = entity(undefined, [+ { schemaName: 'new_code', type: 'Text' },+ { schemaName: 'new_long', type: 'Text', maxLength: 200 },+ { schemaName: 'new_ref', type: 'AutoNumber', autoNumberFormat: 'R-{SEQNUM:4}' },+ { schemaName: 'new_odd', type: 'Text', maxLength: 0 },+ { schemaName: 'new_untyped' },+ ]);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name']), 850), 1700);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name']), 120), 240);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name', 'new_code']), 120), 240 + 200, 'a text column with no maxLength is 100 characters');+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name', 'new_long']), 120), 240 + 400, 'and one with a maxLength is that many');+ assert.strictEqual(keyBytesAtLeast(e, key(['new_ref']), 120), 200, 'an auto-number column is text');+ assert.strictEqual(keyBytesAtLeast(e, key(['new_odd']), 120), 200, 'a maxLength that is not a length is the default');+ assert.strictEqual(keyBytesAtLeast(e, key(['new_untyped']), 120), 200, 'a column that gives no type is a text column, as the build creates it');+});++test('every other column counts for one byte, however much more it takes: the floor shows only what is certain', () => {+ const e = entity(undefined, [{ schemaName: 'new_count', type: 'Integer' }, { schemaName: 'new_when', type: 'DateTime' }, { schemaName: 'new_kind', type: 'Choice' }]);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name', 'new_count']), 120), 240 + 1);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name', 'new_count', 'new_when', 'new_kind']), 120), 240 + 3);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name', 'createdon', 'new_parentid']), 120), 240 + 2, 'nor does a column the spec does not describe: a system column, a lookup a relationship makes');+});++test('a name column is matched whatever the case, and a length that is no length counts as one character', () => {+ assert.strictEqual(keyBytesAtLeast(entity(), key(['NEW_NAME']), 120), 240, 'logical names are lower case, whatever case the spec writes');+ assert.strictEqual(keyBytesAtLeast(entity(), key(['NEW_NAME', 'New_Code']), 120), 240 + 200);+ for (const nameLength of [undefined, null, 0, -5, 1.5, '120', NaN]) assert.strictEqual(keyBytesAtLeast(entity(), key(['new_name']), nameLength), 2, `${nameLength}`);+});++test('the measured answers: the name column of 850 characters alone fits, and any column beside it does not — a character, a hundred, a number', () => {+ const e = entity(undefined, [{ schemaName: 'new_one', type: 'Text', maxLength: 1 }, { schemaName: 'new_code', type: 'Text', maxLength: 100 }, { schemaName: 'new_count', type: 'Integer' }]);+ assert.strictEqual(keyCannotFitAt(e, key(['new_name']), 850), false, 'accepted');+ assert.strictEqual(keyCannotFitAt(e, key(['new_name', 'new_one']), 850), true, '1,702 bytes: refused');+ assert.strictEqual(keyCannotFitAt(e, key(['new_name', 'new_code']), 850), true, '1,900 bytes: refused');+ assert.strictEqual(keyCannotFitAt(e, key(['new_name', 'new_count']), 850), true, 'a column of any type takes at least a byte');+ for (const columns of [['new_name', 'new_one'], ['new_name', 'new_code'], ['new_name', 'new_count']]) {+ assert.strictEqual(keyCannotFitAt(e, key(columns), 120), false, `${columns}: at the length the spec asks it has room`);+ }+ assert.strictEqual(keyCannotFitAt(e, key(['new_name', 'new_code']), 750), false, '1,700 bytes, to the byte: the platform takes a key of the limit itself');+ assert.strictEqual(keyCannotFitAt(e, key(['new_name', 'new_code']), 751), true);+});++test('only a key that holds the name column and cannot fit at 850 characters, but may at the length the spec asks, has room only after the length step', () => {+ const e = entity(undefined, [{ schemaName: 'new_code', type: 'Text' }, { schemaName: 'new_wide', type: 'Text', maxLength: 900 }]);+ assert.strictEqual(keyHasRoomOnlyAfterLength(e, key(['new_name', 'new_code'])), true, 'the name column and another column');+ assert.strictEqual(keyHasRoomOnlyAfterLength(e, key(['new_code', 'NEW_NAME'])), true, 'in any order and case');+ assert.strictEqual(keyHasRoomOnlyAfterLength(e, key(['new_name'])), false, 'the name column alone fits at 850 characters: nothing depends on the length');+ assert.strictEqual(keyHasRoomOnlyAfterLength(e, key(['new_code'])), false, 'a key that does not hold the name column is not in its way');+ assert.strictEqual(keyHasRoomOnlyAfterLength(e, key(['new_name', 'new_wide'])), false, '1,800 bytes beside the name column: too large at the length asked as well, so waiting changes nothing');+ assert.strictEqual(keyHasRoomOnlyAfterLength(entity({ schemaName: 'new_name' }), key(['new_name', 'new_code'])), false, 'a spec that asks no length has no length step to wait for');+ assert.strictEqual(keyHasRoomOnlyAfterLength(entity({ schemaName: 'new_name', maxLength: 850 }), key(['new_name', 'new_code'])), false, 'and one that asks the longest has nothing to shorten');+ assert.strictEqual(keyHasRoomOnlyAfterLength(entity({ schemaName: 'new_name', maxLength: 760 }), key(['new_name', 'new_code'])), false, '1,720 bytes at the length asked');+ assert.strictEqual(keyHasRoomOnlyAfterLength(entity({ schemaName: 'new_name', maxLength: 750 }), key(['new_name', 'new_code'])), true, '1,700 bytes at the length asked: the platform takes it');+});++test('the floor never throws: a key, an entity or a column that is not what it should be holds what can be counted of it', () => {+ for (const [what, e, k, room] of [+ ['no key', entity(), undefined, false],+ ['no columns', entity(), { schemaName: 'new_k' }, false],+ ['columns that are not a list', entity(), { schemaName: 'new_k', columns: 'new_name' }, false],+ ['no entity', undefined, key(['new_name']), false],+ ['no primary attribute', { schemaName: 'new_t', columns: [] }, key(['new_name']), false],+ // The key holds the name column and a column the spec does not describe, which counts for a byte: too large at 850 characters, not at 120.+ ['columns that are not a list, on the entity', { schemaName: 'new_t', primaryAttribute: { schemaName: 'new_name', maxLength: 120 }, columns: 'x' }, key(['new_name', 'new_code']), true],+ ['a hole among the columns', { schemaName: 'new_t', primaryAttribute: { schemaName: 'new_name', maxLength: 120 }, columns: [null, { schemaName: 'new_code' }] }, key(['new_name', 'new_code']), true],+ ]) {+ assert.doesNotThrow(() => keyBytesAtLeast(e, k, 120), what);+ assert.doesNotThrow(() => keyCannotFitAt(e, k, 850), what);+ assert.strictEqual(keyHasRoomOnlyAfterLength(e, k), room, what);+ }+});++// A column is judged by the length the build creates it with, which is not always the length the spec writes. The build sends a column's+// `maxLength` only when the column names its type Text (or Memo, which a key cannot hold) — maxLengthSent, the one rule what the build sends+// (columnOptions, lib/entity-provision.js) and the floor both follow — so an auto-number column and a column that gives no type, which the build+// creates as text all the same, are the 100 characters the SDK gives a text column, whatever maxLength they carry. What the real bundle makes of+// each column is pinned where it runs (table-columns-in-create.test.js).++test('the maxLength the build passes on is a Text or Memo column\'s own, when it is truthy, as written — and no other column\'s, whatever it carries', () => {+ for (const type of ['Text', 'Memo']) {+ assert.strictEqual(maxLengthSent({ schemaName: 'new_c', type, maxLength: 300 }), 300, type);+ assert.strictEqual(maxLengthSent({ schemaName: 'new_c', type, maxLength: '300' }), '300', `${type}: as written, for the platform to judge`);+ for (const unsent of [undefined, null, 0, '', false, NaN]) assert.strictEqual(maxLengthSent({ schemaName: 'new_c', type, maxLength: unsent }), undefined, `${type}: ${String(unsent)}`);+ }+ for (const [what, column] of [+ ['an auto-number column', { schemaName: 'new_c', type: 'AutoNumber', autoNumberFormat: 'R-{SEQNUM:4}', maxLength: 300 }],+ ['a column that gives no type', { schemaName: 'new_c', maxLength: 300 }],+ ['a column of another type', { schemaName: 'new_c', type: 'Integer', maxLength: 300 }],+ ['a type the build does not know', { schemaName: 'new_c', type: 'text', maxLength: 300 }],+ ['no column', undefined],+ ['a hole', null],+ ['a name', 'new_c'],+ ]) assert.strictEqual(maxLengthSent(column), undefined, what);+});++test('a column counts for the characters the build creates it with: only a column that names its type Text is as long as its maxLength says', () => {+ const e = entity(undefined, [+ { schemaName: 'new_text', type: 'Text', maxLength: 300 },+ { schemaName: 'new_ref', type: 'AutoNumber', autoNumberFormat: 'R-{SEQNUM:4}', maxLength: 900 },+ { schemaName: 'new_untyped', maxLength: 900 },+ ]);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_text']), 120), 600, 'a Text column is created at its maxLength');+ assert.strictEqual(keyBytesAtLeast(e, key(['new_ref']), 120), 200, 'an auto-number column is created 100 characters long: the build sends no length for it, whatever maxLength it carries');+ assert.strictEqual(keyBytesAtLeast(e, key(['new_untyped']), 120), 200, 'and so is a column that gives no type: it is created as text, but its length is read only for the type it names');+ assert.strictEqual(keyBytesAtLeast(e, key(['new_name', 'new_ref', 'new_untyped']), 850), 1700 + 200 + 200, 'in a key, beside the name column');+});++test('a maxLength the build sends that is no length counts one character, and one it never sends the 100 of the SDK: the floor is never more than can have been created', () => {+ // The build sends any value that is truthy as it is (`if (c.maxLength)`), and the platform refuses it or reads it as it pleases.+ for (const sent of ['300', 1.5, -5, true, Infinity, [], {}]) {+ const e = entity(undefined, [{ schemaName: 'new_odd', type: 'Text', maxLength: sent }]);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_odd']), 120), 2, `${typeof sent} ${String(sent)}`);+ }+ for (const unsent of [0, '', null, false, undefined, NaN]) {+ const e = entity(undefined, [{ schemaName: 'new_odd', type: 'Text', maxLength: unsent }]);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_odd']), 120), 200, `${typeof unsent} ${String(unsent)}`);+ }+});++test('every type of column the build creates is sized on purpose: a text column by its length, and every other as a single byte — the floor claims nothing about a size that was not measured', () => {+ const sized = { Text: 2 * 300, AutoNumber: 2 * 100 };+ for (const type of Object.keys(SDK_COLUMN_TYPE)) {+ const e = entity(undefined, [{ schemaName: 'new_col', type, maxLength: 300 }]);+ assert.strictEqual(keyBytesAtLeast(e, key(['new_col']), 120), sized[type] || 1, type);+ }+ // Customer is no entry of SDK_COLUMN_TYPE: createCustomerColumn makes it — a lookup, a type a key can hold, whose size was not measured either.+ assert.strictEqual(keyBytesAtLeast(entity(undefined, [{ schemaName: 'new_col', type: 'Customer' }]), key(['new_col']), 120), 1, 'Customer');+});++test('where a key has room follows from the lengths the build creates: an auto-number column, or one that gives no type, is 100 characters whatever maxLength it carries', () => {+ for (const [what, column] of [+ ['an auto-number column', { schemaName: 'new_ref', type: 'AutoNumber', autoNumberFormat: 'R-{SEQNUM:4}', maxLength: 900 }],+ ['a column that gives no type', { schemaName: 'new_ref', maxLength: 900 }],+ ]) {+ const e = entity(undefined, [column]);+ const pair = key(['new_name', 'new_ref']);+ assert.strictEqual(keyCannotFitAt(e, pair, 850), true, `${what}: 1,900 bytes beside a name column of 850 characters`);+ assert.strictEqual(keyCannotFitAt(e, pair, 120), false, `${what}: 440 bytes at the 120 the spec asks`);+ assert.strictEqual(keyHasRoomOnlyAfterLength(e, pair), true, `${what}: so only the length step gives it room`);+ assert.strictEqual(keyCannotFitAt(e, pair, 600), false, `${what}: 1,400 bytes beside a name column of 600 characters — it fits, and a key that fits is not moved`);+ assert.strictEqual(keyCannotFitAt(e, pair, 750), false, `${what}: 1,700 bytes, to the byte`);+ assert.strictEqual(keyCannotFitAt(e, pair, 751), true, what);+ }+ const text = entity(undefined, [{ schemaName: 'new_ref', type: 'Text', maxLength: 900 }]);+ assert.strictEqual(keyHasRoomOnlyAfterLength(text, key(['new_name', 'new_ref'])), false, 'a Text column of 900 characters is created 900 long: no length of the name column leaves room for it');+});diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex d120eb537..a75cd933f 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -546,7 +546,7 @@ test('transient auto-retry: a non-transient halt is NOT retried', async () => {assert.strictEqual(attempts, 1, 'no retry on a non-transient error');});-// ── A throttle's wait crosses the layers, and what the build's own layers add is one budget ──────────────────────────────────────────────────────────+// ── A throttle's wait crosses the layers, and the waits the build's own layers add are one budget with the HTTP client's ─────────────────────────────────// The page backend sends a throttled page write again up to six times, waiting what the service asked; when that is not enough it raises an error that carries the last ask (`retryAfterMs`) and the moment before which// nothing may be sent (`retryNotBefore`). The loop that runs the build again then waits for THAT — never its own, shorter, backoff — and every wait it spends on a throttle comes out of the budget the backend spends from:// five minutes for the whole run (lib/throttle-budget.js). A wait that does not fit ends the run with a halt that says what the service asked, and that a later run continues.@@ -571,7 +571,7 @@ const throttleDriver = async ({ failures, budget, retryDelayMs, spec = desk, onRrunBuild: async (s, o) => {attempts += 1;budgets.push(o.throttle);- if (onRun) onRun(attempts, () => clock, (ms) => { clock += ms; });+ if (onRun) onRun(attempts, () => clock, (ms) => { clock += ms; }, o.throttle);const failure = failures(attempts, clock);if (failure) throw new BuildHalt(`pages failed: ${failure.message}`, { phase: 'pages', code: 'CONNECTION_ERROR', recoverable: true, cause: failure });return { ok: true };@@ -669,6 +669,55 @@ test('retry loop: the budget is the run\'s — the backend\'s waits count, so whassert.ok(own.budgets[0].spentMs() >= 3000, 'and a throttle that asked for nothing still waited the build\'s backoff, which is a throttle wait too');});+// The HTTP client draws its waits for a throttled answer from this same budget (lib/sdk-http-client.js). A wait that does not fit is not taken: the answer comes back as the 429 it is — the SDK's error carries none of what the service asked, nor+// that nothing more was sent — and the client tells the budget (`decline`). The loop reads that, so a request the budget stopped ends the run as the budget's halt does, with what the service asked, and is not run again to be refused again.+const declinedBy = (askedMs, waitMs = askedMs, spent = 250000) => (n, clock, advance, throttle) => { if (n === 1) { throttle.spend(spent); throttle.decline({ askedMs, waitMs }); } };+const sdkThrottle = () => throttledFailure(0, 0);++test('retry loop: a request the HTTP client did not wait for — the budget had no room for what the service asked — ends the run with the budget\'s halt, naming what the service asked, and is not run again', async () => {+ const out = await throttleDriver({ onRun: declinedBy(90000), failures: (n) => (n === 1 ? sdkThrottle() : null) });+ assert.strictEqual(out.attempts, 1, 'the run is not run again to meet the same answer: the service said it was not ready');+ assert.deepStrictEqual(out.sleeps, [], 'and nothing was waited for');+ assert.ok(out.halt, 'the build stops');+ assert.strictEqual(out.halt.code, 'throttle-budget-exhausted');+ assert.strictEqual(out.halt.phase, 'pages');+ assert.strictEqual(out.halt.recoverable, true);+ assert.strictEqual(out.halt.statusCode, 429);+ assert.strictEqual(isTransientHalt(out.halt), true, 'a transient halt: nothing is wrong with the build, and a later run can go on');+ assert.strictEqual(out.halt.message, 'pages stopped: the service asked to wait 90 s before the next send, which does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service (250 s are spent). Nothing more is sent now: run the same command again later, and it continues from here.');+ assert.strictEqual(out.halt.cause.cause.statusCode, 429, 'the failure itself is its cause');+ assert.deepStrictEqual([out.closed[0].status, out.closed[0].code, out.closed[0].recoverable], ['halt', 'throttle-budget-exhausted', true], 'the journal says where the run stopped');+ // A decline whose service asked for nothing — the wait that did not fit was the schedule's — says so in the words of the budget's other halt.+ const bare = await throttleDriver({ onRun: declinedBy(0, 8000, 296000), failures: (n) => (n === 1 ? sdkThrottle() : null) });+ assert.strictEqual(bare.halt.code, 'throttle-budget-exhausted');+ assert.match(bare.halt.message, /^pages stopped: the next wait, 8 s, does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service \(296 s are spent\)/);+ // What the failure itself asked, when it carries an ask (the page backend's), counts too: the longer of the two is said.+ const both = await throttleDriver({ onRun: declinedBy(90000), failures: (n, clock) => (n === 1 ? throttledFailure(clock, 120000) : null) });+ assert.strictEqual(both.attempts, 1);+ assert.match(both.halt.message, /^pages stopped: the service asked to wait 120 s before the next send, which does not fit/);+});++test('retry loop: a request the client did not wait for ends the run on the last run as on the first — the failure the retries ran out on is the budget\'s halt, not a bare 429', async () => {+ // Three runs end in a throttle that asked for nothing (the build waits 3, 6 and 12 s between them); in the fourth the client is refused a wait.+ const out = await throttleDriver({ onRun: (n, clock, advance, throttle) => { if (n === 4) throttle.decline({ askedMs: 0, waitMs: 9000 }); }, failures: () => sdkThrottle() });+ assert.strictEqual(out.attempts, 4, 'the retries were spent');+ assert.strictEqual(out.halt.code, 'throttle-budget-exhausted', 'and what stopped the last one was the budget');+ assert.match(out.halt.message, /^pages stopped: the next wait, 9 s, does not fit in what is left of the 5 minutes/);+});++test('retry loop: a request the client did not wait for changes nothing for a failure that is not a throttle, nor for a later run in which nothing was refused', async () => {+ // A 503 that follows a refused wait is the service's gateway, not a throttle: the build runs again after its own backoff, as it does for any 503, and the budget's halt is not for it.+ const gateway = await throttleDriver({ onRun: declinedBy(90000), failures: (n) => (n === 1 ? Object.assign(new Error('the service is unavailable'), { statusCode: 503 }) : null) });+ assert.strictEqual(gateway.halt, null);+ assert.strictEqual(gateway.attempts, 2);+ assert.ok(gateway.sleeps.length === 1 && gateway.sleeps[0] >= 3000 && gateway.sleeps[0] < 4000, `the build's backoff: ${gateway.sleeps}`);+ // What was refused in one run is not read again in the next: a throttle in the second run, with nothing refused in it, is waited for as any other.+ const later = await throttleDriver({ onRun: declinedBy(0, 8000, 0), failures: (n) => (n === 1 ? Object.assign(new Error('the service is unavailable'), { statusCode: 503 }) : n === 2 ? sdkThrottle() : null) });+ assert.strictEqual(later.halt, null, 'the third run got through');+ assert.strictEqual(later.attempts, 3);+ assert.deepStrictEqual(later.sleeps.map((ms) => Math.floor(ms / 1000)), [3, 6], 'the build\'s own backoff before each run, and no halt for a refusal of the first');+});+test('retry loop: only a throttle spends the budget — the backoff of any other transient failure is the build\'s own, as it was', async () => {const out = await throttleDriver({ failures: (n) => (n <= 3 ? Object.assign(new Error('the service is unavailable'), { statusCode: 503 }) : null) });assert.strictEqual(out.attempts, 4, 'three more runs, as ever');@@ -1854,7 +1903,7 @@ test('makeSdk\u2019s return shape and main\u2019s destructure stay in agreement'test('the build verifies dashboards through makeSdk\u2019s isolated reader, sharing the build\u2019s client', () => {const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');const body = src.slice(src.indexOf('async function makeSdk'), src.indexOf('return { sdk, provisionSdk'));- assert.match(body, /const httpClient = createAzHttpClient\(env\);/);+ assert.match(body, /const httpClient = createAzHttpClient\(env, \{ throttle, sendOnce: isTranslationExport \}\);/, 'one client, made with the run\u2019s throttle budget, that sends a translation export once');assert.match(body, /isolatedReaderFor\(env, \{ httpClient \}\)/, 'the reader is made around the build\u2019s own client');const wiring = src.slice(src.indexOf('verify: async (s, verifyOpts) =>'));assert.match(wiring.split(/\r?\n/).find((l) => /verifySpec\(/.test(l)), /isolatedReader \}/, 'verify takes the reader makeSdk returned');diff --git a/plugins/model-apps/scripts/tests/connectivity-real-bundle.test.js b/plugins/model-apps/scripts/tests/connectivity-real-bundle.test.jsindex 801e32b22..8bcaecc13 100644--- a/plugins/model-apps/scripts/tests/connectivity-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/connectivity-real-bundle.test.js@@ -704,7 +704,7 @@ test('PROCESS: a refused read of the connection references prints no Dataverse tassert.strictEqual(run.requests.filter((r) => r.path.endsWith('/connectionreferences')).length, 1, 'the read was made once: a 403 is not retried');});-test('PROCESS control: a read of the connection references that SUCCEEDS is printed as it came, even when a value in it is the token\'s own text — a success is the caller\'s data and is never altered', () => {+test('PROCESS control: a read of the connection references that SUCCEEDS is read as it came, and is printed without the token when a value in it is the token\'s own text — a success is the caller\'s data until a script writes it', () => {const run = runScript('list-connections.js', [ORG], {platform: {tokens: { dataverse: DATAVERSE_ECHO },@@ -715,7 +715,11 @@ test('PROCESS control: a read of the connection references that SUCCEEDS is prin});assert.strictEqual(run.status, 0, run.stderr);const out = JSON.parse(run.lines[0]);- assert.deepStrictEqual(out.connectionReferences, [{ logicalName: 'new_weather', connectorId: WEATHER, connectionId: DATAVERSE_ECHO }]);+ // The client hands the answer over as it came (tests/sdk-http-client-scrub.test.js); what the process WRITES holds no token it obtained (lib/output-redaction.js), the data of a success included.+ assert.deepStrictEqual(out.connectionReferences, [{ logicalName: 'new_weather', connectorId: WEATHER, connectionId: '<token>' }]);+ for (const text of [run.stdout, run.stderr]) {+ for (const secret of [DATAVERSE_ECHO, ...DATAVERSE_ECHO.split('.')]) assert.ok(!text.includes(secret), `the Dataverse token (or a part of it) was printed: ${text}`);+ }});test('PROCESS: a usage error of list-connections.js — no environment URL, a flag it does not take — is the problem on stderr alone: exit 1, nothing on stdout, nothing asked of anyone', () => {diff --git a/plugins/model-apps/scripts/tests/dashboard-roundtrip.test.js b/plugins/model-apps/scripts/tests/dashboard-roundtrip.test.jsindex a257bd3d0..6cd46baab 100644--- a/plugins/model-apps/scripts/tests/dashboard-roundtrip.test.js+++ b/plugins/model-apps/scripts/tests/dashboard-roundtrip.test.js@@ -88,3 +88,91 @@ for (const [label, tile] of Object.entries(TILES)) {assert.strictEqual(comps.length, 1, `the tile must come back; got ${JSON.stringify(comps)}`);});}++// A tile's height is its rowspan, counted in rows of the dashboard grid, and the app draws a one-row tile as its+// title bar alone: no chart, no list. The build used to send `rowspan: 1` for every tile the spec did not size, so a+// generated dashboard showed a column of title bars. The platform's own dashboards give chart and list tiles 9 to 24+// rows, most often 12, which is the default now. These tests push the payload PRODUCTION builds for a spec's tiles —+// `dashboardTileOpts` (the tile with its authored size) and then `dashboardComponent` (the default size) — through the+// real bundle, and read the cells it wrote:+// <cell id="{…}" colspan="1" rowspan="12" showlabel="true"><labels>…</labels><control …>…</control></cell>+const VIEW = '{44444444-4444-4444-4444-444444444444}';+const CHART = '{55555555-5555-5555-5555-555555555555}';++// Pushes a dashboard of the given spec tiles the way the build's dashboards phase does. Returns the stored FormXML's+// rows, each a list of [rowspan, colspan] per tile cell, and the same pair for each tile the SDK reads back.+async function pushTiles(specTiles) {+ const { dashboardTileOpts, dashboardComponent } = require(path.resolve(__dirname, '..', 'lib', 'sdk-build.js'));+ const spec = { views: [{ name: 'Open', entity: 'cfo_workorder' }], charts: [{ name: 'By Status', entity: 'cfo_workorder' }] };+ const created = { views: { 'cfo_workorder|Open': VIEW }, charts: { 'cfo_workorder|By Status': CHART } };+ const { sdk, store } = await harness();+ const art = await sdk.createArtifact('dashboard', { name: 'Field Ops' });+ for (let i = 0; i < specTiles.length; i++) {+ await sdk.addElement('dashboard', art.id, '/components', dashboardComponent(dashboardTileOpts(spec, specTiles[i], { created }), i));+ }+ await sdk.pushArtifact('dashboard', art.id);+ const formxml = String(store.row && store.row.formxml);+ // Only a cell holding a control is a tile; a cell without one is a spacer.+ const rows = [...formxml.matchAll(/<row>([\s\S]*?)<\/row>/g)].map((row) => [...row[1].matchAll(/<cell\b([^>]*)>([\s\S]*?)<\/cell>/g)]+ .filter((cell) => /<control\b/.test(cell[2]))+ .map((cell) => ['rowspan', 'colspan'].map((attr) => Number(new RegExp(`\\b${attr}="(\\d+)"`).exec(cell[1])[1]))));+ const back = await sdk.fetchArtifact('dashboard', DASH_ID);+ const components = (back && (back.components || (back.artifact && back.artifact.components))) || [];+ return { formxml, rows, read: components.map((c) => [c.rowspan, c.colspan]) };+}++test('REAL BUNDLE: a tile the spec does not size is built 12 rows tall, and an authored size is kept', async () => {+ const { rows, read } = await pushTiles([+ { type: 'chart', chart: 'By Status', view: 'Open' },+ { type: 'list', view: 'Open', name: 'Open' },+ { type: 'list', view: 'Open', name: 'Recent', rowspan: 6, colspan: 2 },+ { type: 'iframe', name: 'Map', url: 'https://contoso.com/map' },+ { type: 'webresource', name: 'Widget', webResource: 'new_widget.html' },+ { type: 'list', view: 'Open', name: 'Strip', rowspan: 1 },+ ]);+ const sizes = [[12, 1], [12, 1], [6, 2], [12, 1], [12, 1], [1, 1]];+ assert.deepStrictEqual(rows.flat(), sizes, `each tile's cell must carry its size, in tile order; got ${JSON.stringify(rows)}`);+ assert.deepStrictEqual(read, sizes, 'the SDK must read the same sizes back');+});++// How tiles lay out is the adapter's, not the plugin's: a grid two columns wide, filled in tile order from left to+// right. The App Spec reference tells authors so (two `colspan: 1` tiles share a row; `colspan: 2` is a full-width+// one), and a wider default height changes none of it, so it is pinned here against the bundle that does it.+test('REAL BUNDLE: tiles fill a two-column grid left to right, and a tile too wide for the rest of a row starts the next', async () => {+ const { rows, formxml } = await pushTiles([+ { type: 'list', view: 'Open', name: 'A' },+ { type: 'list', view: 'Open', name: 'B' },+ { type: 'list', view: 'Open', name: 'C', colspan: 2 },+ { type: 'list', view: 'Open', name: 'D' },+ { type: 'list', view: 'Open', name: 'E', colspan: 2 },+ { type: 'list', view: 'Open', name: 'F', colspan: 3 },+ ]);+ assert.match(formxml, /<section\b[^>]*\bcolumns="2"/, 'the section is two columns wide');+ assert.deepStrictEqual(rows.map((row) => row.map(([, colspan]) => colspan)), [[1, 1], [2], [1], [2], [2]],+ `A and B share a row, C takes one, D waits alone because E does not fit beside it, and F's colspan 3 is narrowed to the grid; got ${JSON.stringify(rows)}`);+});++test('dashboardComponent: every tile kind defaults to 12 rows by 1 column, and an authored size wins', () => {+ const { dashboardComponent } = require(path.resolve(__dirname, '..', 'lib', 'sdk-build.js'));+ for (const tile of [{ type: 'chart' }, { type: 'list' }, { type: 'iframe', url: 'https://contoso.com/map' }, { type: 'webresource', webResourceName: 'new_widget.html' }]) {+ const c = dashboardComponent(tile, 0);+ assert.deepStrictEqual([c.rowspan, c.colspan], [12, 1], `${tile.type} tile default size`);+ }+ const sized = dashboardComponent({ type: 'list', rowspan: 1, colspan: 2 }, 0);+ assert.deepStrictEqual([sized.rowspan, sized.colspan], [1, 2], 'an authored size is kept, even a rowspan of 1');+ // The two sizes are independent: authoring one leaves the other at its default.+ const tall = dashboardComponent({ type: 'list', rowspan: 4 }, 0);+ assert.deepStrictEqual([tall.rowspan, tall.colspan], [4, 1], 'an authored rowspan leaves the width at 1');+ const wide = dashboardComponent({ type: 'list', colspan: 2 }, 0);+ assert.deepStrictEqual([wide.rowspan, wide.colspan], [12, 2], 'an authored colspan leaves the height at 12');+});++test('dashboardComponent: a list tile\'s payload carries its class, its place in the grid, its size and its parameters', () => {+ const { dashboardComponent } = require(path.resolve(__dirname, '..', 'lib', 'sdk-build.js'));+ assert.deepStrictEqual(dashboardComponent({ type: 'list', name: 'Open', targetEntity: 'cfo_workorder', viewId: VIEW }, 2), {+ type: 'list', name: 'Open', classId: 'E7A81278-8635-4D9E-8D4D-59480B391C5B',+ position: { tabIndex: 0, columnIndex: 0, sectionIndex: 0, rowIndex: 2, cellIndex: 0 },+ colspan: 1, rowspan: 12,+ parameters: { TargetEntityType: 'cfo_workorder', ViewId: VIEW, IsUserView: 'false', ChartGridMode: 'Grid', RecordsPerPage: '10' },+ });+});diff --git a/plugins/model-apps/scripts/tests/download-file-image-columns-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-file-image-columns-real-bundle.test.jsnew file mode 100644index 000000000..841c6bcac--- /dev/null+++ b/plugins/model-apps/scripts/tests/download-file-image-columns-real-bundle.test.js@@ -0,0 +1,640 @@+'use strict';+// A download keeps the File and Image columns it reads. Both report `AttributeType: "Virtual"` — the type a download leaves out — with+// `AttributeTypeName` FileType / ImageType, so before this every download dropped them without a word and a rebuild elsewhere lost them.+// Pinned at two levels:+// - the projection (entityFromMetadata over readEntityWithDescriptions, against a scripted SDK): what each column comes back as, what+// is left out and named, what is left out silently, and which reads a table costs;+// - the round trip, over the REAL vendored SDK, the plugin's own HTTP client and the stateful fake Dataverse of the lifecycle matrix+// (helpers/fake-lifecycle-org.js, helpers/lifecycle-harness.js): build -> download -> the columns as they were made; the+// downloaded spec rebuilt in the same environment sends no write for them; built into a FRESH environment it makes them as they+// are in the first. The size a build gives a column that sets none is read off that build's own wire, which is what keeps the+// download's DEFAULT_MAX_SIZE_KB honest.+const test = require('node:test');+const assert = require('node:assert/strict');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { createLifecycleHarness, appUniqueName } = require('./helpers/lifecycle-harness.js');+const { entityFromMetadata, readEntityWithDescriptions } = require('../download-model-app.js');+const { DEFAULT_MAX_SIZE_KB } = require('../lib/entity-provision.js');+const { validateAppSpec } = require('../lib/app-spec.js');++// ====================================================================================================================================+// THE PROJECTION, against a scripted SDK. `attributes` is the SDK's own projection of the table (fetchEntityMetadata), `rows` what the+// attribute read answers (AttributeTypeName, AttributeOf, IsLogical, labels), `file` / `image` what each cast read answers, and+// `answers` replaces a whole answer: `table` (the table's label read), `rows`, `file` or `image`.++const label = (text) => ({ LocalizedLabels: [{ Label: text, LanguageCode: 1033 }], UserLocalizedLabel: { Label: text, LanguageCode: 1033 } });+const sdkAttribute = (logicalName, attributeType, attributeTypeName, extra = {}) => ({ logicalName, displayName: logicalName, attributeType, attributeTypeName, isCustomAttribute: true, ...extra });+const row = (LogicalName, typeName, extra = {}) => ({ LogicalName, DisplayName: label(LogicalName.replace(/^contoso_/, '')), AttributeTypeName: { Value: typeName }, AttributeOf: null, IsLogical: false, ...extra });++// A File column and an Image column with the companions the platform makes, in the shape a live environment reports (MEASURED):+// File `x` Virtual / FileType AttributeOf null not logical `x_name` String AttributeOf `x` logical+// Image `y` Virtual / ImageType AttributeOf `yid` LOGICAL `yid` Uniqueidentifier, custom, AttributeOf null, not logical+// `y_timestamp` BigInt, `y_url` String: AttributeOf `yid`, logical+// The Image column is the logical projection of its `<image>id` — the opposite of what an earlier fake modelled. Given both ways the+// download reads them: `attributes` (the SDK's projection, which carries `attributeOf` when there is one) and `rows` (the column read).+function fileColumn(name) {+ return {+ attributes: [sdkAttribute(name, 'Virtual', 'FileType'), sdkAttribute(`${name}_name`, 'String', 'StringType', { attributeOf: name })],+ rows: [row(name, 'FileType'), row(`${name}_name`, 'StringType', { AttributeOf: name, IsLogical: true })],+ };+}+function imageColumn(name) {+ const id = `${name}id`;+ return {+ attributes: [+ sdkAttribute(name, 'Virtual', 'ImageType', { attributeOf: id }), sdkAttribute(id, 'Uniqueidentifier', 'UniqueidentifierType'),+ sdkAttribute(`${name}_timestamp`, 'BigInt', 'BigIntType', { attributeOf: id }), sdkAttribute(`${name}_url`, 'String', 'StringType', { attributeOf: id }),+ ],+ rows: [+ row(name, 'ImageType', { AttributeOf: id, IsLogical: true }), row(id, 'UniqueidentifierType'),+ row(`${name}_timestamp`, 'BigIntType', { AttributeOf: id, IsLogical: true }), row(`${name}_url`, 'StringType', { AttributeOf: id, IsLogical: true }),+ ],+ };+}+const columnsOf = (...columns) => ({ attributes: columns.flatMap((c) => c.attributes), rows: columns.flatMap((c) => c.rows) });++function scriptedSdk({ attributes, rows = [], file = [], image = [], answers = {}, urls = [] }) {+ const answer = (name, value) => (answers[name] ? answers[name] : { status: 200, headers: {}, body: { value } });+ return {+ fetchEntityMetadata: async (logical) => ({ logicalName: logical, schemaName: logical, displayName: 'Asset', primaryNameAttribute: 'contoso_name', attributes: [sdkAttribute('contoso_name', 'String', 'StringType'), ...attributes] }),+ dataverse: {+ get: async (url) => {+ urls.push(url);+ if (/FileAttributeMetadata/.test(url)) return answer('file', file);+ if (/ImageAttributeMetadata/.test(url)) return answer('image', image);+ if (/AttributeMetadata/.test(url)) return { status: 200, headers: {}, body: { value: [] } }; // the option-set and Money casts+ if (/\/Attributes\?/.test(url)) return answer('rows', [row('contoso_name', 'StringType'), ...rows]);+ return answers.table || { status: 200, headers: {}, body: { DisplayName: label('Asset'), DisplayCollectionName: label('Assets') } };+ },+ },+ };+}++const FILE_CAST = "/EntityDefinitions(LogicalName='contoso_asset')/Attributes/Microsoft.Dynamics.CRM.FileAttributeMetadata?$select=LogicalName,MaxSizeInKB";+const IMAGE_CAST = "/EntityDefinitions(LogicalName='contoso_asset')/Attributes/Microsoft.Dynamics.CRM.ImageAttributeMetadata?$select=LogicalName,MaxSizeInKB,IsPrimaryImage";+const castReads = (urls) => urls.filter((u) => /(File|Image)AttributeMetadata/.test(u));++test('a File and an Image column download typed, with the size and the primary-image flag each was made with', async () => {+ const urls = [];+ const sdk = scriptedSdk({+ urls,+ ...columnsOf(fileColumn('contoso_contract'), imageColumn('contoso_logo')),+ file: [{ LogicalName: 'contoso_contract', MaxSizeInKB: 1024 }],+ image: [{ LogicalName: 'contoso_logo', MaxSizeInKB: 30720, IsPrimaryImage: true }],+ });+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset');+ assert.deepEqual(e.columns, [+ { schemaName: 'contoso_contract', displayName: 'contract', type: 'File', maxSizeKb: 1024 },+ { schemaName: 'contoso_logo', displayName: 'logo', type: 'Image', maxSizeKb: 30720, isPrimaryImage: true },+ ]);+ // One read per type the table has, through the cast that carries the size: MaxSizeInKB is not a property of AttributeMetadata.+ assert.deepEqual(castReads(urls), [FILE_CAST, IMAGE_CAST]);+});++test('a size a build gives a column that sets none is left out, and so is a primary-image flag that is false', async () => {+ // So a column authored without a size downloads exactly as it was authored, and a rebuild makes it at the same size.+ const sdk = scriptedSdk({+ ...columnsOf(fileColumn('contoso_manual'), imageColumn('contoso_photo')),+ file: [{ LogicalName: 'contoso_manual', MaxSizeInKB: DEFAULT_MAX_SIZE_KB }],+ image: [{ LogicalName: 'contoso_photo', MaxSizeInKB: DEFAULT_MAX_SIZE_KB, IsPrimaryImage: false }],+ });+ const incomplete = [];+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset', { incomplete });+ assert.deepEqual(e.columns, [+ { schemaName: 'contoso_manual', displayName: 'manual', type: 'File' },+ { schemaName: 'contoso_photo', displayName: 'photo', type: 'Image' },+ ]);+ // Left out because they are the defaults, not because they are missing: the answer was complete.+ assert.deepEqual(incomplete, []);+});++test('a table without a File or Image column reads neither cast, and downloads byte for byte as before', async () => {+ const urls = [];+ const sdk = scriptedSdk({+ urls,+ attributes: [sdkAttribute('contoso_serial', 'String', 'StringType'), sdkAttribute('contoso_bought', 'DateTime', 'DateTimeType')],+ rows: [row('contoso_serial', 'StringType'), row('contoso_bought', 'DateTimeType')],+ });+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset');+ assert.deepEqual(castReads(urls), []);+ // The bytes an earlier release wrote for this table, unchanged.+ assert.equal(JSON.stringify(e), '{"schemaName":"contoso_asset","displayName":"Asset","primaryAttribute":{"schemaName":"contoso_name","displayName":"name"},"columns":[{"schemaName":"contoso_serial","displayName":"serial","type":"Text"},{"schemaName":"contoso_bought","displayName":"bought","type":"DateTime"}],"existing":true}');+});++test("the table's own image, entityimage, and its companions are left out, and a table that has only it reads no cast", async () => {+ // The worst case: reported as custom and with no AttributeOf, so only the name keeps them out.+ const urls = [];+ const sdk = scriptedSdk({+ urls,+ attributes: [+ sdkAttribute('entityimage', 'Virtual', 'ImageType'), sdkAttribute('entityimage_url', 'String', 'StringType'),+ sdkAttribute('entityimage_timestamp', 'BigInt', 'BigIntType'), sdkAttribute('entityimageid', 'Uniqueidentifier', 'UniqueidentifierType'),+ ],+ rows: [row('entityimage', 'ImageType'), row('entityimage_url', 'StringType'), row('entityimage_timestamp', 'BigIntType'), row('entityimageid', 'UniqueidentifierType')],+ });+ const unexpressible = [];+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset', { unexpressible });+ assert.deepEqual(e.columns, []);+ assert.deepEqual(unexpressible, [], 'the table image is the platform\'s, not a column the download fails to express');+ assert.deepEqual(castReads(urls), []);+});++test('the companions of a File or Image column stay out even when the read that names them failed', async () => {+ // The column read carries `AttributeOf`, which is how a companion is normally told from a column. When it fails, the SDK's own+ // projection still says which columns are File and Image, and their companions are named by the platform's rule.+ const live = columnsOf(fileColumn('contoso_contract'), imageColumn('contoso_logo'));+ const sdk = scriptedSdk({+ answers: { rows: { status: 403, headers: {}, body: {} } },+ attributes: live.attributes,+ file: [{ LogicalName: 'contoso_contract', MaxSizeInKB: 4096 }],+ image: [{ LogicalName: 'contoso_logo', MaxSizeInKB: DEFAULT_MAX_SIZE_KB, IsPrimaryImage: false }],+ });+ const meta = await readEntityWithDescriptions(sdk, 'contoso_asset');+ assert.equal(meta.labelReadFailed, 'HTTP 403');+ const e = entityFromMetadata(meta, 'contoso_asset');+ assert.deepEqual(e.columns, [+ { schemaName: 'contoso_contract', displayName: 'contoso_contract', type: 'File', maxSizeKb: 4096 },+ { schemaName: 'contoso_logo', displayName: 'contoso_logo', type: 'Image' },+ ]);+});++test('an Image column is kept as the platform reports it — logical, the projection of its <image>id — and none of its companions is', async () => {+ // MEASURED: an Image column reports `AttributeOf: "<image>id"` and `IsLogical: true`, the two marks the shadow rules leave a column out+ // by. Its type name is positive evidence against both. The companions stay out: `_timestamp` and `_url` by both marks and by name, and+ // `<image>id` — a custom Uniqueidentifier with no `AttributeOf`, not logical — by name, and by its type, which no App Spec column has+ // (it is not Virtual either, so nothing names it). A File column is neither logical nor `AttributeOf` anything; its `_name` is both.+ const sdk = scriptedSdk({+ ...columnsOf(fileColumn('contoso_contract'), imageColumn('contoso_logo')),+ file: [{ LogicalName: 'contoso_contract', MaxSizeInKB: 1024 }],+ image: [{ LogicalName: 'contoso_logo', MaxSizeInKB: DEFAULT_MAX_SIZE_KB, IsPrimaryImage: true }],+ });+ const unexpressible = [];+ const incomplete = [];+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset', { unexpressible, incomplete });+ assert.deepEqual(e.columns, [+ { schemaName: 'contoso_contract', displayName: 'contract', type: 'File', maxSizeKb: 1024 },+ { schemaName: 'contoso_logo', displayName: 'logo', type: 'Image', isPrimaryImage: true },+ ]);+ assert.deepEqual({ unexpressible, incomplete }, { unexpressible: [], incomplete: [] });+});++// The attribute list of a table on a live environment with three File columns and two Image columns, the first of them made its+// primary image by the platform, as `GET EntityDefinitions(LogicalName='<table>')/Attributes?$select=LogicalName,AttributeType,+// AttributeTypeName,AttributeOf,IsLogical,IsCustomAttribute` answered it (MEASURED; renamed to this file's prefix, nothing else changed):+// [LogicalName, AttributeType, AttributeTypeName, AttributeOf, IsLogical, IsCustomAttribute]+const LIVE_ATTRIBUTES = [+ ['createdby', 'Lookup', 'LookupType', null, false, false],+ ['createdbyname', 'String', 'StringType', 'createdby', true, false],+ ['createdbyyominame', 'String', 'StringType', 'createdby', true, false],+ ['createdon', 'DateTime', 'DateTimeType', null, false, false],+ ['createdonbehalfby', 'Lookup', 'LookupType', null, false, false],+ ['createdonbehalfbyname', 'String', 'StringType', 'createdonbehalfby', true, false],+ ['createdonbehalfbyyominame', 'String', 'StringType', 'createdonbehalfby', true, false],+ ['importsequencenumber', 'Integer', 'IntegerType', null, false, false],+ ['modifiedby', 'Lookup', 'LookupType', null, false, false],+ ['modifiedbyname', 'String', 'StringType', 'modifiedby', true, false],+ ['modifiedbyyominame', 'String', 'StringType', 'modifiedby', true, false],+ ['modifiedon', 'DateTime', 'DateTimeType', null, false, false],+ ['modifiedonbehalfby', 'Lookup', 'LookupType', null, false, false],+ ['modifiedonbehalfbyname', 'String', 'StringType', 'modifiedonbehalfby', true, false],+ ['modifiedonbehalfbyyominame', 'String', 'StringType', 'modifiedonbehalfby', true, false],+ ['overriddencreatedon', 'DateTime', 'DateTimeType', null, false, false],+ ['ownerid', 'Owner', 'OwnerType', null, false, false],+ ['owneridname', 'String', 'StringType', 'ownerid', true, false],+ ['owneridtype', 'EntityName', 'EntityNameType', 'ownerid', false, false],+ ['owneridyominame', 'String', 'StringType', 'ownerid', true, false],+ ['owningbusinessunit', 'Lookup', 'LookupType', null, false, false],+ ['owningbusinessunitname', 'String', 'StringType', 'owningbusinessunit', true, false],+ ['owningteam', 'Lookup', 'LookupType', null, true, false],+ ['owninguser', 'Lookup', 'LookupType', null, true, false],+ ['statecode', 'State', 'StateType', null, false, false],+ ['statecodename', 'Virtual', 'VirtualType', 'statecode', true, false],+ ['statuscode', 'Status', 'StatusType', null, false, false],+ ['statuscodename', 'Virtual', 'VirtualType', 'statuscode', true, false],+ ['contoso_contrato', 'Virtual', 'FileType', null, false, true],+ ['contoso_contrato_name', 'String', 'StringType', 'contoso_contrato', true, true],+ ['contoso_escaneo', 'Virtual', 'FileType', null, false, true],+ ['contoso_escaneo_name', 'String', 'StringType', 'contoso_escaneo', true, true],+ ['contoso_etiquetaid', 'Uniqueidentifier', 'UniqueidentifierType', null, false, false],+ ['contoso_foto', 'Virtual', 'ImageType', 'contoso_fotoid', true, true],+ ['contoso_foto_timestamp', 'BigInt', 'BigIntType', 'contoso_fotoid', true, true],+ ['contoso_foto_url', 'String', 'StringType', 'contoso_fotoid', true, true],+ ['contoso_fotoid', 'Uniqueidentifier', 'UniqueidentifierType', null, false, true],+ ['contoso_insignia', 'Virtual', 'ImageType', 'contoso_insigniaid', true, true],+ ['contoso_insignia_timestamp', 'BigInt', 'BigIntType', 'contoso_insigniaid', true, true],+ ['contoso_insignia_url', 'String', 'StringType', 'contoso_insigniaid', true, true],+ ['contoso_insigniaid', 'Uniqueidentifier', 'UniqueidentifierType', null, false, true],+ ['contoso_manual', 'Virtual', 'FileType', null, false, true],+ ['contoso_manual_name', 'String', 'StringType', 'contoso_manual', true, true],+ ['contoso_nombre', 'String', 'StringType', null, false, true],+ ['timezoneruleversionnumber', 'Integer', 'IntegerType', null, false, false],+ ['utcconversiontimezonecode', 'Integer', 'IntegerType', null, false, false],+ ['versionnumber', 'BigInt', 'BigIntType', null, false, false],+];+// ...and what its two casts answered (the same environment, the same moment).+const LIVE_FILE_CAST = [{ LogicalName: 'contoso_contrato', MaxSizeInKB: 2048 }, { LogicalName: 'contoso_escaneo', MaxSizeInKB: 32768 }, { LogicalName: 'contoso_manual', MaxSizeInKB: 10240 }];+const LIVE_IMAGE_CAST = [{ LogicalName: 'contoso_foto', IsPrimaryImage: true, MaxSizeInKB: 10240 }, { LogicalName: 'contoso_insignia', IsPrimaryImage: false, MaxSizeInKB: 30720 }];++test("a live table's attribute list downloads every File and Image column, and nothing that is the platform's", async () => {+ const live = LIVE_ATTRIBUTES.map(([LogicalName, AttributeType, typeName, AttributeOf, IsLogical, IsCustomAttribute]) => ({ LogicalName, AttributeType, AttributeTypeName: { Value: typeName }, AttributeOf, IsLogical, IsCustomAttribute }));+ const named = (e) => e.columns.map((c) => `${c.schemaName} ${c.type}${c.maxSizeKb ? ` ${c.maxSizeKb}` : ''}${c.isPrimaryImage ? ' primary' : ''}`);+ // The download's own column filter over the list alone, as the live check fed it.+ const unexpressible = [];+ const bare = entityFromMetadata({ primaryNameAttribute: 'contoso_nombre', attributes: live }, 'contoso_etiqueta', { unexpressible });+ assert.deepEqual(named(bare), ['contoso_contrato File', 'contoso_escaneo File', 'contoso_foto Image', 'contoso_insignia Image', 'contoso_manual File']);+ assert.deepEqual(unexpressible, []);+ // And through the download's reads, the list answered both ways it is read and the casts as the environment answered them: the primary+ // image is the one the platform reports (the build sent `false` for it), and the size a build gives a column that sets none is left out.+ const sdk = {+ fetchEntityMetadata: async (logical) => ({+ logicalName: logical, schemaName: logical, displayName: 'Etiqueta', primaryNameAttribute: 'contoso_nombre',+ attributes: live.map((a) => ({ logicalName: a.LogicalName, displayName: a.LogicalName, attributeType: a.AttributeType, attributeTypeName: a.AttributeTypeName.Value, isCustomAttribute: a.IsCustomAttribute, ...(a.AttributeOf ? { attributeOf: a.AttributeOf } : {}) })),+ }),+ dataverse: {+ get: async (url) => {+ if (/FileAttributeMetadata/.test(url)) return { status: 200, headers: {}, body: { value: LIVE_FILE_CAST } };+ if (/ImageAttributeMetadata/.test(url)) return { status: 200, headers: {}, body: { value: LIVE_IMAGE_CAST } };+ if (/AttributeMetadata/.test(url)) return { status: 200, headers: {}, body: { value: [] } };+ if (/\/Attributes\?/.test(url)) return { status: 200, headers: {}, body: { value: live } };+ return { status: 200, headers: {}, body: { DisplayName: label('Etiqueta'), DisplayCollectionName: label('Etiquetas') } };+ },+ },+ };+ const incomplete = [];+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_etiqueta'), 'contoso_etiqueta', { unexpressible, incomplete });+ assert.deepEqual(named(e), ['contoso_contrato File 2048', 'contoso_escaneo File 32768', 'contoso_foto Image primary', 'contoso_insignia Image 30720', 'contoso_manual File']);+ assert.deepEqual({ unexpressible, incomplete }, { unexpressible: [], incomplete: [] });+});++test('a Virtual column of another kind is left out and named; a companion is left out without a word', async () => {+ const sdk = scriptedSdk({+ attributes: [+ sdkAttribute('contoso_sensor', 'Virtual', 'VirtualType'),+ sdkAttribute('contoso_kind', 'Picklist', 'PicklistType'), sdkAttribute('contoso_kindname', 'Virtual', 'VirtualType'),+ ],+ rows: [row('contoso_sensor', 'VirtualType'), row('contoso_kind', 'PicklistType'), row('contoso_kindname', 'VirtualType', { AttributeOf: 'contoso_kind', IsLogical: true })],+ });+ const unexpressible = [];+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset', { unexpressible });+ assert.deepEqual(e.columns.map((c) => c.schemaName), ['contoso_kind']);+ assert.deepEqual(unexpressible, [{ table: 'contoso_asset', column: 'contoso_sensor', typeName: 'VirtualType' }]);+});++test('without the attribute read, a Virtual column cannot be told from a companion, so none is named', async () => {+ // The failed read is what the download reports then (its label-read warning); naming every companion would be noise.+ const sdk = scriptedSdk({+ answers: { rows: { status: 503, headers: {}, body: {} } },+ attributes: [sdkAttribute('contoso_sensor', 'Virtual', 'VirtualType'), sdkAttribute('contoso_kindname', 'Virtual', 'VirtualType')],+ });+ const unexpressible = [];+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset', { unexpressible });+ assert.deepEqual(e.columns, []);+ assert.deepEqual(unexpressible, []);+});++test('a File read that fails keeps the File columns typed, without their size, and records that read alone; the Image read stands', async () => {+ const sdk = scriptedSdk({+ answers: { file: { status: 503, headers: {}, body: {} } },+ ...columnsOf(fileColumn('contoso_contract'), imageColumn('contoso_logo')),+ image: [{ LogicalName: 'contoso_logo', MaxSizeInKB: 2048, IsPrimaryImage: false }],+ });+ const meta = await readEntityWithDescriptions(sdk, 'contoso_asset');+ assert.deepEqual(meta.mediaReadFailures, { File: 'HTTP 503' });+ const incomplete = [];+ assert.deepEqual(entityFromMetadata(meta, 'contoso_asset', { incomplete }).columns, [+ { schemaName: 'contoso_contract', displayName: 'contract', type: 'File' },+ { schemaName: 'contoso_logo', displayName: 'logo', type: 'Image', maxSizeKb: 2048 },+ ]);+ // The File column's read failed, which is said as such; the Image answer was complete.+ assert.deepEqual(incomplete, []);+});++test('an Image read that fails keeps the Image columns typed, without their size or flag, and records that read alone; the File read stands', async () => {+ const sdk = scriptedSdk({+ answers: { image: { status: 503, headers: {}, body: {} } },+ ...columnsOf(fileColumn('contoso_contract'), imageColumn('contoso_logo')),+ file: [{ LogicalName: 'contoso_contract', MaxSizeInKB: 1024 }],+ });+ const meta = await readEntityWithDescriptions(sdk, 'contoso_asset');+ assert.deepEqual(meta.mediaReadFailures, { Image: 'HTTP 503' });+ const incomplete = [];+ assert.deepEqual(entityFromMetadata(meta, 'contoso_asset', { incomplete }).columns, [+ { schemaName: 'contoso_contract', displayName: 'contract', type: 'File', maxSizeKb: 1024 },+ { schemaName: 'contoso_logo', displayName: 'logo', type: 'Image' },+ ]);+ assert.deepEqual(incomplete, []);+});++test('a cast answer without a column, or with an unusable value, is reported by column, and what did come back is kept', async () => {+ // A successful answer is checked against the File and Image columns the download writes: a row that is not there, a size that is+ // not a positive whole number, a primary-image flag that is not true or false. No request is added for it.+ const urls = [];+ const sdk = scriptedSdk({+ urls,+ ...columnsOf(imageColumn('contoso_badge'), fileColumn('contoso_contract'), imageColumn('contoso_logo'), fileColumn('contoso_manual'), imageColumn('contoso_photo')),+ file: [{ LogicalName: 'contoso_manual', MaxSizeInKB: 4096 }], // no row for contoso_contract+ image: [+ { LogicalName: 'contoso_badge', MaxSizeInKB: 2048, IsPrimaryImage: null }, // a size, but no usable flag+ { LogicalName: 'contoso_logo', MaxSizeInKB: '30720', IsPrimaryImage: true }, // a flag, but no usable size+ ], // no row for contoso_photo+ });+ const incomplete = [];+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'contoso_asset'), 'contoso_asset', { incomplete });+ assert.deepEqual(e.columns, [+ { schemaName: 'contoso_badge', displayName: 'badge', type: 'Image', maxSizeKb: 2048 },+ { schemaName: 'contoso_contract', displayName: 'contract', type: 'File' },+ { schemaName: 'contoso_logo', displayName: 'logo', type: 'Image', isPrimaryImage: true },+ { schemaName: 'contoso_manual', displayName: 'manual', type: 'File', maxSizeKb: 4096 },+ { schemaName: 'contoso_photo', displayName: 'photo', type: 'Image' },+ ]);+ assert.deepEqual(incomplete, [+ { table: 'contoso_asset', column: 'contoso_badge', type: 'Image', missing: ['primary'] },+ { table: 'contoso_asset', column: 'contoso_contract', type: 'File', missing: ['size'] },+ { table: 'contoso_asset', column: 'contoso_logo', type: 'Image', missing: ['size'] },+ { table: 'contoso_asset', column: 'contoso_photo', type: 'Image', missing: ['size', 'primary'] },+ ]);+ assert.deepEqual(castReads(urls), [FILE_CAST, IMAGE_CAST]);+});++test('the two label reads are recorded apart: the table\'s own, and the columns\'', async () => {+ // Each read carries different things, so what a download says about a failure depends on which one failed. `labelReadFailed`, the+ // first of the two reasons, is kept for its readers.+ const read = async (answers) => {+ const meta = await readEntityWithDescriptions(scriptedSdk({ attributes: [], answers }), 'contoso_asset');+ return { table: meta.tableLabelReadFailed, columns: meta.attributeReadFailed, first: meta.labelReadFailed };+ };+ const refused = (status) => ({ status, headers: {}, body: {} });+ assert.deepEqual(await read({ table: refused(403) }), { table: 'HTTP 403', columns: undefined, first: 'HTTP 403' });+ assert.deepEqual(await read({ rows: refused(503) }), { table: undefined, columns: 'HTTP 503', first: 'HTTP 503' });+ assert.deepEqual(await read({ table: refused(403), rows: refused(503) }), { table: 'HTTP 403', columns: 'HTTP 503', first: 'HTTP 403' });+ assert.deepEqual(await read({}), { table: undefined, columns: undefined, first: undefined });+});++// ====================================================================================================================================+// THE ROUND TRIP, over the real bundle. One environment, walked in order: the build, what a maker then adds in Maker, the download, the+// rebuild of the downloaded spec, the same spec built into a fresh environment; then downloads the environment refuses one read of, or+// answers one read short.++const spec = {+ schemaVersion: 2,+ minimumPluginVersion: '2.13.0',+ solution: { uniqueName: 'ContosoAssets', displayName: 'Contoso Assets', publisherPrefix: 'contoso', description: 'Assets, with their files and pictures.' },+ app: { name: 'Asset Register', description: 'The assets the company owns.' },+ entities: [{+ schemaName: 'contoso_asset', displayName: 'Asset', pluralName: 'Assets', description: 'A thing the company owns.',+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },+ columns: [+ { schemaName: 'contoso_serial', displayName: 'Serial', type: 'Text' },+ { schemaName: 'contoso_manual', displayName: 'Manual', type: 'File' },+ { schemaName: 'contoso_contract', displayName: 'Contract', type: 'File', maxSizeKb: 2048 },+ { schemaName: 'contoso_photo', displayName: 'Photo', type: 'Image' },+ ],+ }],+ appShell: { areas: [{ label: 'Assets', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_asset', title: 'Assets' }] }] }] },+};+const APP = appUniqueName(spec);++// An environment with a seam in front of its transport. `refuse` answers what it names with the Dataverse OData error a client does not+// retry (the error shape: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#parse-errors-from-the-response);+// `alter` lets the fake answer what it names and edits the JSON body of that answer — a read that succeeds with less than it should.+// A rule names a method and a path and, where one path is read for different things, the `$select`: the table's own label read and+// the SDK's metadata read of the table share their path.+function environment(prefix) {+ const org = createLifecycleOrg();+ const rules = [];+ const ruleFor = (req, kind) => {+ const url = new URL(req.url);+ const where = decodeURIComponent(url.pathname);+ return rules.find((r) => r.kind === kind && r.method === req.method && r.path.test(where) && (r.select === undefined || url.searchParams.get('$select') === r.select));+ };+ const request = async (req) => {+ if (ruleFor(req, 'refuse')) {+ return { statusCode: 400, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error: { code: '0x80040216', message: 'An unexpected error occurred.' } }) };+ }+ const res = await org.request(req);+ const alter = ruleFor(req, 'alter');+ return alter ? { ...res, body: JSON.stringify(alter.edit(JSON.parse(res.body))) } : res;+ };+ const root = makeTempDir(prefix);+ const harness = createLifecycleHarness({ ...org, request }, root);+ const add = (rule) => { rules.push(rule); return () => rules.splice(rules.indexOf(rule), 1); };+ const refuse = (method, pattern, { select } = {}) => add({ kind: 'refuse', method, path: pattern, select });+ const alter = (method, pattern, edit) => add({ kind: 'alter', method, path: pattern, edit });+ return { org, root, harness, refuse, alter };+}++// What a maker sends from Maker, as the Web API call Maker makes.+async function inMaker(org, method, where, body) {+ const res = await org.request({ url: `${org.API}${where}`, method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });+ assert.ok(res.statusCode < 300, `${method} ${where} answered ${res.statusCode}: ${res.body}`);+}++// The File and Image columns of the table as the environment holds them: `<type> <size> KB[ primary]`.+function mediaColumns(org) {+ const table = org.metadata.tables.get('contoso_asset');+ return Object.fromEntries([...table.Attributes.values()]+ .filter((a) => ['FileType', 'ImageType'].includes(a.AttributeTypeName.Value))+ .map((a) => [a.LogicalName, `${a.AttributeTypeName.Value} ${a.MaxSizeInKB} KB${a.IsPrimaryImage ? ' primary' : ''}`])+ .sort(([a], [b]) => (a < b ? -1 : 1)));+}++const ran = (step, what) => {+ if (step.error) throw step.error;+ assert.deepEqual(step.unexpected, [], `every request ${what} sent is one the fake models`);+ return step;+};++let walkP;+const walk = () => walkP || (walkP = (async () => {+ const env = environment('download-file-image-');+ const { org, harness } = env;+ const build = ran(await harness.measure(() => harness.build(spec)), 'the build');+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));+ env.built = mediaColumns(org);+ // Then, in Maker: a File column at the size Maker gives one (32 MB, Microsoft Learn: file-attributes); a second Image column, sent+ // as the table's primary image, which the platform ignores because the table's first Image column (the build's) already is; the+ // table's own image with its companions; and a Virtual column of a kind the App Spec has no type for. The fake has no Web API create+ // for that last kind, so it is put in its store with the shape the platform reports.+ const where = "/EntityDefinitions(LogicalName='contoso_asset')/Attributes";+ await inMaker(org, 'POST', where, { '@odata.type': 'Microsoft.Dynamics.CRM.FileAttributeMetadata', SchemaName: 'contoso_scan', DisplayName: { LocalizedLabels: [{ Label: 'Scan', LanguageCode: 1033 }] }, RequiredLevel: { Value: 'None' }, MaxSizeInKB: 32768 });+ await inMaker(org, 'POST', where, { '@odata.type': 'Microsoft.Dynamics.CRM.ImageAttributeMetadata', SchemaName: 'contoso_stamp', DisplayName: { LocalizedLabels: [{ Label: 'Stamp', LanguageCode: 1033 }] }, RequiredLevel: { Value: 'None' }, MaxSizeInKB: 30720, IsPrimaryImage: true });+ await inMaker(org, 'POST', where, { '@odata.type': 'Microsoft.Dynamics.CRM.ImageAttributeMetadata', SchemaName: 'EntityImage', DisplayName: { LocalizedLabels: [{ Label: 'Entity Image', LanguageCode: 1033 }] }, RequiredLevel: { Value: 'None' }, MaxSizeInKB: 10240, IsPrimaryImage: false });+ const table = org.metadata.tables.get('contoso_asset');+ const sensor = org.metadata.makeAttribute(table, { '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata', SchemaName: 'contoso_sensor', DisplayName: 'Sensor' });+ Object.assign(sensor, { '@odata.type': '#Microsoft.Dynamics.CRM.AttributeMetadata', AttributeType: 'Virtual', AttributeTypeName: { Value: 'VirtualType' } });+ delete sensor.MaxLength;+ delete sensor.FormatName;+ table.Attributes.set(sensor.LogicalName, sensor);+ env.held = mediaColumns(org);+ env.download = ran(await harness.measure(() => harness.download(APP, path.join(env.root, 'download'))), 'the download');+ return env;+})());++test('the size a build gives a File or Image column that sets none is DEFAULT_MAX_SIZE_KB, on the real wire', async () => {+ // What the download leaves out must be what the build really makes: read off the environment the real SDK wrote to. The build sent+ // `IsPrimaryImage: false` for contoso_photo; it is the table's first Image column, so the platform made it the primary image anyway.+ const { built } = await walk();+ assert.deepEqual(built, {+ contoso_contract: 'FileType 2048 KB',+ contoso_manual: `FileType ${DEFAULT_MAX_SIZE_KB} KB`,+ contoso_photo: `ImageType ${DEFAULT_MAX_SIZE_KB} KB primary`,+ });+});++test('a download writes each File and Image column as it was made, leaves the platform\'s own out, and names what it cannot express', async () => {+ const { download } = await walk();+ const { emitted, spec: downloaded, stderr } = download.value;+ assert.equal(emitted.ok, true, JSON.stringify(emitted));+ const asset = downloaded.entities.find((e) => e.schemaName === 'contoso_asset');+ // The authored columns as authored, but for the primary image the platform made of contoso_photo (written, as it is what the+ // environment reports); the two made in Maker with what they were made with. No `entityimage`, no companion (`*_name`, `*id`,+ // `*_timestamp`, `*_url`), no `contoso_sensor`.+ assert.deepEqual(asset.columns.slice().sort((a, b) => (a.schemaName < b.schemaName ? -1 : 1)), [+ { schemaName: 'contoso_contract', displayName: 'Contract', type: 'File', maxSizeKb: 2048 },+ { schemaName: 'contoso_manual', displayName: 'Manual', type: 'File' },+ { schemaName: 'contoso_photo', displayName: 'Photo', type: 'Image', isPrimaryImage: true },+ { schemaName: 'contoso_scan', displayName: 'Scan', type: 'File', maxSizeKb: 32768 },+ { schemaName: 'contoso_serial', displayName: 'Serial', type: 'Text' },+ { schemaName: 'contoso_stamp', displayName: 'Stamp', type: 'Image', maxSizeKb: 30720 },+ ]);+ const warnings = stderr.split('\n').filter((l) => /^WARNING:/.test(l));+ assert.deepEqual(warnings, [+ 'WARNING: 1 column(s) have a type the App Spec cannot express and were left out of the spec (contoso_asset.contoso_sensor (VirtualType)). Rebuilding this spec into an environment that already has the table leaves them as they are, but rebuilding into a FRESH environment would not create them: add them there in Maker after the rebuild.',+ ]);+ assert.deepEqual(validateAppSpec(downloaded, { profile: 'plan', reconstructed: true }).errors, []);+});++test('the downloaded spec rebuilt in the same environment sends no write for a File or Image column', async () => {+ const { org, harness, root, download, held } = await walk();+ const before = org.inventory();+ const dir = path.join(root, 'download');+ // The spec rebuilt is the one that carries `isPrimaryImage: true` for contoso_photo (the test above): the column exists, so nothing+ // of it is sent, and the environment's primary image stays where the platform put it.+ const rebuild = ran(await harness.measure(() => harness.build(download.value.spec, { appFolder: dir, workspace: path.join(dir, '.maker-workspace') })), 'the rebuild of the downloaded spec');+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));+ const columnWrites = Object.keys(rebuild.writes).filter((w) => /Attributes/.test(w));+ assert.deepEqual(columnWrites, [], `no column is created or changed: ${JSON.stringify(rebuild.writes)}`);+ assert.deepEqual(org.inventory(), before);+ assert.deepEqual(mediaColumns(org), held);+});++test('the downloaded spec built into a fresh environment makes each File and Image column as it is in the first', async () => {+ // Here the primary image, contoso_photo, is also the first Image column by name, so the fresh build creates it first and the platform+ // makes it the primary image there too; the last test of this file pins what happens when it is not.+ const { held, download } = await walk();+ const fresh = environment('download-file-image-fresh-');+ const build = ran(await fresh.harness.measure(() => fresh.harness.build(download.value.spec)), 'the build into a fresh environment');+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));+ // Everything but the table's own image, which no build makes.+ const { entityimage, ...authorable } = held;+ assert.equal(entityimage, 'ImageType 10240 KB');+ assert.deepEqual(mediaColumns(fresh.org), authorable);+});++// What a download of the walked environment says about each read that failed or came back short, word for word: each warning names+// only what the read it is about carries, so one read failing never reads as another's loss.+const SENSOR_NAMED = 'WARNING: 1 column(s) have a type the App Spec cannot express and were left out of the spec (contoso_asset.contoso_sensor (VirtualType)). Rebuilding this spec into an environment that already has the table leaves them as they are, but rebuilding into a FRESH environment would not create them: add them there in Maker after the rebuild.';+const TABLE_LABEL_READ_FAILED = "WARNING: the table label read failed for 1 table(s) (contoso_asset (HTTP 400)). Their display names and descriptions fall back to ONE language and their plurals are not written, so rebuilding into a FRESH environment would recreate each of those tables labelled in one language, with the plural '<display name>s'. Re-run the download to recover them before a cross-environment rebuild.";+const COLUMN_READ_FAILED = "WARNING: the column read failed for 1 table(s) (contoso_asset (HTTP 400)). Their COLUMN labels and descriptions fall back to ONE language, so a column labelled in several languages downloads as single-language and rebuilding into a FRESH environment would recreate it that way. That read also carries the flags that identify a lookup's synthetic '<lookup>name' column, so those tables may additionally have captured one as a real Text column — delete any you see before a cross-environment rebuild — and the type names that tell a column of a type the App Spec cannot express from the platform's own, so any such column on those tables was left out without being named. Re-run the download to recover them.";+const FILE_READ_FAILED = `WARNING: the File column read failed for 1 table(s) (contoso_asset (HTTP 400)). Their File columns are captured WITHOUT the maximum size each was made with, so rebuilding into a FRESH environment would create them at the default size of ${DEFAULT_MAX_SIZE_KB} KB. Re-run the download to recover them before a cross-environment rebuild.`;+const IMAGE_READ_FAILED = `WARNING: the Image column read failed for 1 table(s) (contoso_asset (HTTP 400)). Their Image columns are captured WITHOUT the maximum size each was made with or whether one is the table's primary image, so rebuilding into a FRESH environment would create them at the default size of ${DEFAULT_MAX_SIZE_KB} KB, none of them asked to be the table's primary image. Re-run the download to recover them before a cross-environment rebuild.`;+const READ_INCOMPLETE = `WARNING: the File/Image column read came back incomplete for 3 column(s): contoso_asset.contoso_contract (its maximum size), contoso_asset.contoso_photo (its maximum size and whether it is the table's primary image), contoso_asset.contoso_stamp (whether it is the table's primary image). Each is captured without what did not come back, so rebuilding into a FRESH environment would create a column without its maximum size at the default size of ${DEFAULT_MAX_SIZE_KB} KB and would not ask an Image column without its primary-image flag to be the table's primary image. Re-run the download to recover them before a cross-environment rebuild.`;++// The table's File and Image columns as a download wrote them, `<name> <type>[ <size>][ primary]`, and the warnings it printed.+const mediaOf = (downloaded) => downloaded.entities[0].columns.filter((c) => c.type === 'File' || c.type === 'Image')+ .map((c) => `${c.schemaName} ${c.type}${c.maxSizeKb ? ` ${c.maxSizeKb}` : ''}${c.isPrimaryImage ? ' primary' : ''}`).sort();+const warningsOf = (stderr) => stderr.split('\n').filter((l) => /^WARNING:/.test(l));+const HEALTHY_MEDIA = ['contoso_contract File 2048', 'contoso_manual File', 'contoso_photo Image primary', 'contoso_scan File 32768', 'contoso_stamp Image 30720'];++// One download of the walked environment with `rules` in front of it (each returns its own undo), into a folder of its own.+async function downloadWith(name, rules) {+ const env = await walk();+ const undo = rules(env);+ try {+ const step = ran(await env.harness.measure(() => env.harness.download(APP, path.join(env.root, name))), `the download ${name}`);+ assert.equal(step.value.emitted.ok, true, JSON.stringify(step.value.emitted));+ return step.value;+ } finally {+ for (const lift of undo) lift();+ }+}++const TABLE_LABEL_READ = { select: 'LogicalName,Description,DisplayName,DisplayCollectionName' };++test('a download the environment refuses only the table label read of says so of the table\'s labels alone, and still names what it cannot express', async () => {+ const { spec: downloaded, stderr } = await downloadWith('download-no-table-labels', ({ refuse }) => [+ refuse('GET', /^\/api\/data\/v9\.\d\/EntityDefinitions\(LogicalName='contoso_asset'\)$/, TABLE_LABEL_READ),+ ]);+ assert.deepEqual(mediaOf(downloaded), HEALTHY_MEDIA);+ // The table's label comes from the SDK's own read; its plural, which only the refused read carries, is not written.+ assert.deepEqual({ displayName: downloaded.entities[0].displayName, plural: 'pluralName' in downloaded.entities[0] }, { displayName: 'Asset', plural: false });+ assert.deepEqual(warningsOf(stderr), [TABLE_LABEL_READ_FAILED, SENSOR_NAMED]);+});++test('a download the environment refuses the column read of still keeps each File and Image column and none of their companions, and says what that read carries', async () => {+ // That read carries AttributeOf, which normally tells a companion from a column; without it the SDK's own projection still names the+ // File and Image columns, and their companions are known by the platform's names for them. A Virtual column the App Spec cannot+ // express cannot be told from the platform's own without it, so none is named — and the warning says that is why.+ const { spec: downloaded, stderr } = await downloadWith('download-no-column-read', ({ refuse }) => [+ refuse('GET', /^\/api\/data\/v9\.\d\/EntityDefinitions\(LogicalName='contoso_asset'\)\/Attributes$/),+ ]);+ assert.deepEqual(downloaded.entities[0].columns.map((c) => c.schemaName).sort(), ['contoso_contract', 'contoso_manual', 'contoso_photo', 'contoso_scan', 'contoso_serial', 'contoso_stamp']);+ assert.deepEqual(mediaOf(downloaded), HEALTHY_MEDIA);+ assert.deepEqual(warningsOf(stderr), [COLUMN_READ_FAILED]);+});++test('a download the environment refuses the File read of keeps the File columns, without their size, and says so of the File columns alone', async () => {+ const { spec: downloaded, stderr } = await downloadWith('download-no-file-read', ({ refuse }) => [+ refuse('GET', /\/Attributes\/Microsoft\.Dynamics\.CRM\.FileAttributeMetadata$/),+ ]);+ // The Image read was not refused: its sizes and flag stand.+ assert.deepEqual(mediaOf(downloaded), ['contoso_contract File', 'contoso_manual File', 'contoso_photo Image primary', 'contoso_scan File', 'contoso_stamp Image 30720']);+ assert.deepEqual(warningsOf(stderr), [FILE_READ_FAILED, SENSOR_NAMED]);+});++test('a download the environment refuses the Image read of keeps the Image columns, without their size or flag, and says so of the Image columns alone', async () => {+ const { spec: downloaded, stderr } = await downloadWith('download-no-image-read', ({ refuse }) => [+ refuse('GET', /\/Attributes\/Microsoft\.Dynamics\.CRM\.ImageAttributeMetadata$/),+ ]);+ // The File read was not refused: its sizes stand.+ assert.deepEqual(mediaOf(downloaded), ['contoso_contract File 2048', 'contoso_manual File', 'contoso_photo Image', 'contoso_scan File 32768', 'contoso_stamp Image']);+ assert.deepEqual(warningsOf(stderr), [IMAGE_READ_FAILED, SENSOR_NAMED]);+});++test('a File or Image read that answers without a column, or with an unusable value, keeps what did come back and names each column it lacks', async () => {+ // Both reads succeed, but the File answer has no row for contoso_contract, and the Image answer has no row for contoso_photo and no+ // usable primary-image flag for contoso_stamp — what an answer read while the table changes, say, can carry. No request is added.+ const { spec: downloaded, stderr } = await downloadWith('download-short-answers', ({ alter }) => [+ alter('GET', /\/Attributes\/Microsoft\.Dynamics\.CRM\.FileAttributeMetadata$/, (body) => ({ ...body, value: body.value.filter((r) => r.LogicalName !== 'contoso_contract') })),+ alter('GET', /\/Attributes\/Microsoft\.Dynamics\.CRM\.ImageAttributeMetadata$/, (body) => ({ ...body, value: body.value.filter((r) => r.LogicalName !== 'contoso_photo').map((r) => (r.LogicalName === 'contoso_stamp' ? { ...r, IsPrimaryImage: null } : r)) })),+ ]);+ assert.deepEqual(mediaOf(downloaded), ['contoso_contract File', 'contoso_manual File', 'contoso_photo Image', 'contoso_scan File 32768', 'contoso_stamp Image 30720']);+ assert.deepEqual(warningsOf(stderr), [READ_INCOMPLETE, SENSOR_NAMED]);+});++test('a rebuild into a fresh environment makes the first Image column it creates the primary image: isPrimaryImage on a later one is not honoured', async () => {+ // What the platform does with `IsPrimaryImage` on a create: a table's FIRST Image column becomes its primary image whatever was sent+ // (MEASURED: sent `false`, read back `true`), and on a later one a `true` "is ignored if set to true when creating a new image column"+ // (Microsoft Learn, image-attributes). A download writes `isPrimaryImage: true` where the environment reports it, and lists a table's+ // columns by name, so where the primary image is not the first Image column by name, a rebuild into a FRESH environment creates+ // another Image column first, and that one becomes the primary image. A limitation of the build, not of the download — the flag is+ // only sent on create, and the build creates columns in the spec's order — pinned so a change (the build creating the flagged column+ // first, or setting it with an update after the create, which Learn allows) shows here. The same environment is not affected: a+ // rebuild there sends nothing for an existing column (above).+ const twoImages = { ...spec, entities: [{ ...spec.entities[0], columns: [+ { schemaName: 'contoso_portrait', displayName: 'Portrait', type: 'Image' },+ { schemaName: 'contoso_badge', displayName: 'Badge', type: 'Image' },+ ] }] };+ const primaryImageOf = (org) => org.metadata.tables.get('contoso_asset').PrimaryImageAttribute;+ const source = environment('download-primary-image-');+ const built = ran(await source.harness.measure(() => source.harness.build(twoImages)), 'the build');+ assert.equal(built.value.result.ok, true, JSON.stringify(built.value.result.errors));+ const download = ran(await source.harness.measure(() => source.harness.download(appUniqueName(twoImages), path.join(source.root, 'download'))), 'the download');+ assert.deepEqual(mediaOf(download.value.spec), ['contoso_badge Image', 'contoso_portrait Image primary']);+ const fresh = environment('download-primary-image-fresh-');+ const rebuilt = ran(await fresh.harness.measure(() => fresh.harness.build(download.value.spec)), 'the build into a fresh environment');+ assert.equal(rebuilt.value.result.ok, true, JSON.stringify(rebuilt.value.result.errors));+ assert.deepEqual({ source: primaryImageOf(source.org), fresh: primaryImageOf(fresh.org) }, { source: 'contoso_portrait', fresh: 'contoso_badge' });+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/download-plural-name-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-plural-name-real-bundle.test.jsnew file mode 100644index 000000000..60adffde5--- /dev/null+++ b/plugins/model-apps/scripts/tests/download-plural-name-real-bundle.test.js@@ -0,0 +1,173 @@+'use strict';+// A download keeps a table's plural when a rebuild would not derive it. A plain plural used to be left out of every download as+// "derivable", but only "<display name>s" is: "Tag Catalog" is not derivable from "Tag", so a downloaded spec rebuilt into another+// environment named the table "Tags". Now the download leaves out exactly the plural the build's own derivation (derivedPluralName,+// lib/app-spec.js) writes for a spec without one, and keeps every other. Pinned at two levels:+// - the projection (entityFromMetadata): which plurals are written, the bytes of an ordinary table (unchanged), localized labels+// (unchanged), and the one derivation the build, lint and the download share;+// - the round trip over the REAL vendored SDK and the lifecycle fake (helpers/fake-lifecycle-org.js, helpers/lifecycle-harness.js):+// build -> download -> the plural where one is needed; the downloaded spec rebuilt in place writes no table; built into a fresh+// environment it names each table as the first one does.+const test = require('node:test');+const assert = require('node:assert/strict');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { createLifecycleHarness, appUniqueName } = require('./helpers/lifecycle-harness.js');+const { entityFromMetadata } = require('../download-model-app.js');+const { derivedPluralName, validateAppSpec } = require('../lib/app-spec.js');+const { lintAppSpec } = require('../lib/spec-lint.js');++// ====================================================================================================================================+// THE PROJECTION. `meta` is what readEntityWithDescriptions hands entityFromMetadata: the SDK's flattened `displayName`, and the raw+// Dataverse labels of the table read beside it.++const dvLabel = (pairs) => ({ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode })) });+const tableMeta = (singular, plural, extra = {}) => ({+ logicalName: 'contoso_tag', schemaName: 'contoso_tag', displayName: typeof singular === 'string' ? singular : 'Tag', primaryNameAttribute: 'contoso_name',+ ...(singular !== undefined ? { DisplayName: typeof singular === 'string' ? dvLabel([[1033, singular]]) : dvLabel(Object.entries(singular).map(([k, v]) => [Number(k), v])) } : {}),+ ...(plural !== undefined ? { DisplayCollectionName: typeof plural === 'string' ? dvLabel([[1033, plural]]) : dvLabel(Object.entries(plural).map(([k, v]) => [Number(k), v])) } : {}),+ attributes: [],+ ...extra,+});++test('a plain plural that is not the display name plus "s" is written, because a rebuild would derive another', () => {+ assert.equal(entityFromMetadata(tableMeta('Tag', 'Tag Catalog'), 'contoso_tag').pluralName, 'Tag Catalog');+ assert.equal(entityFromMetadata(tableMeta('Box', 'Boxes'), 'contoso_tag').pluralName, 'Boxes');+ // Exact, as the build writes it: a plural that differs from the derivation only in case is a different label.+ assert.equal(entityFromMetadata(tableMeta('Tag', 'tags'), 'contoso_tag').pluralName, 'tags');+});++test('a plain plural a rebuild would derive is left out, and the table downloads byte for byte as before', () => {+ const e = entityFromMetadata(tableMeta('Tag', 'Tags'), 'contoso_tag');+ assert.equal('pluralName' in e, false);+ // The bytes an earlier release wrote for this table, unchanged.+ assert.equal(JSON.stringify(e), '{"schemaName":"contoso_tag","displayName":"Tag","primaryAttribute":{"schemaName":"contoso_name","displayName":"Name"},"columns":[],"existing":true}');+});++test('a localized plural, or a plural beside a localized display name, is written exactly as before', () => {+ const both = entityFromMetadata(tableMeta({ 1033: 'Tag', 3082: 'Etiqueta' }, { 1033: 'Tags', 3082: 'Etiquetas' }), 'contoso_tag');+ assert.equal(JSON.stringify({ displayName: both.displayName, pluralName: both.pluralName }), '{"displayName":{"1033":"Tag","3082":"Etiqueta"},"pluralName":{"1033":"Tags","3082":"Etiquetas"}}');+ // A plural that is derivable in English is still written beside a localized display name: validateAppSpec requires it there.+ const singularLocalized = entityFromMetadata(tableMeta({ 1033: 'Tag', 3082: 'Etiqueta' }, 'Tags'), 'contoso_tag');+ assert.equal(singularLocalized.pluralName, 'Tags');+ const pluralLocalized = entityFromMetadata(tableMeta('Tag', { 1033: 'Tags', 3082: 'Etiquetas' }), 'contoso_tag');+ assert.deepEqual(pluralLocalized.pluralName, { 1033: 'Tags', 3082: 'Etiquetas' });+});++test('without a usable display label, the plural is compared with the one derived from the name the spec falls back to', () => {+ // The table's own label is empty, so the spec carries the SDK's flattened `displayName` — and the derivation is of that.+ const derivable = entityFromMetadata(tableMeta(undefined, 'Tags', { DisplayName: dvLabel([]) }), 'contoso_tag');+ assert.equal(derivable.displayName, 'Tag');+ assert.equal('pluralName' in derivable, false);+ const kept = entityFromMetadata(tableMeta(undefined, 'Tag Catalog', { DisplayName: dvLabel([]) }), 'contoso_tag');+ assert.equal(kept.pluralName, 'Tag Catalog');+ // With no table labels read at all (that read failed), there is no plural to write, as before.+ assert.equal('pluralName' in entityFromMetadata(tableMeta(undefined, undefined), 'contoso_tag'), false);+});++test('derivedPluralName is the build\'s rule: the display name in the build\'s language, else the schema name, plus "s"', () => {+ assert.equal(derivedPluralName({ schemaName: 'contoso_tag', displayName: 'Tag' }), 'Tags');+ assert.equal(derivedPluralName({ schemaName: 'contoso_tag' }), 'contoso_tags');+ assert.equal(derivedPluralName({ schemaName: 'contoso_tag', displayName: '' }), 'contoso_tags');+ assert.equal(derivedPluralName({ schemaName: 'contoso_tag', displayName: { 1033: 'Tag', 3082: 'Etiqueta' } }, 3082), 'Etiquetas');+ assert.equal(derivedPluralName({ schemaName: 'contoso_tag', displayName: { 1033: 'Tag', 3082: 'Etiqueta' } }), 'Tags');+});++test('lint names the stock default views by the same derivation the build writes', () => {+ // A view named like a table's "Active <plural>" merges onto that stock view; lint must predict the plural the build will write.+ const spec = (pluralName, viewName) => ({+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoTags', publisherPrefix: 'contoso' },+ app: { name: 'Tags' },+ entities: [{ schemaName: 'contoso_tag', displayName: 'Tag', ...(pluralName ? { pluralName } : {}), primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],+ views: [{ entity: 'contoso_tag', name: viewName, columns: ['contoso_name'] }],+ });+ const merges = (s) => lintAppSpec(s).warnings.some((w) => /stock default view/.test(w));+ assert.equal(merges(spec(undefined, 'Active Tags')), true);+ assert.equal(merges(spec('Tag Catalog', 'Active Tag Catalog')), true);+ assert.equal(merges(spec('Tag Catalog', 'Active Tags')), false);+});++// ====================================================================================================================================+// THE ROUND TRIP, over the real bundle. One environment, walked in order: the build, the download, the rebuild of the downloaded spec,+// and the same spec built into a fresh environment.++// One table of each kind: no plural (the build derives "Tags"), a plural a rebuild derives ("Orders"), and two it does not ("Ledger" for+// "Ledger Entry", and "Boxes", which is not "Box" plus "s").+const spec = {+ schemaVersion: 2,+ minimumPluginVersion: '2.13.0',+ solution: { uniqueName: 'ContosoStock', displayName: 'Contoso Stock', publisherPrefix: 'contoso', description: 'Stock keeping.' },+ app: { name: 'Stock Room', description: 'What is in the stock room.' },+ entities: [+ { schemaName: 'contoso_tag', displayName: 'Tag', description: 'A label.', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] },+ { schemaName: 'contoso_order', displayName: 'Order', pluralName: 'Orders', description: 'An order.', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] },+ { schemaName: 'contoso_ledgerentry', displayName: 'Ledger Entry', pluralName: 'Ledger', description: 'A line of the ledger.', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] },+ { schemaName: 'contoso_box', displayName: 'Box', pluralName: 'Boxes', description: 'A box on a shelf.', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] },+ ],+ appShell: { areas: [{ label: 'Stock', groups: [{ label: 'Records', subAreas: [+ { entity: 'contoso_tag', title: 'Tags' }, { entity: 'contoso_order', title: 'Orders' },+ { entity: 'contoso_ledgerentry', title: 'Ledger' }, { entity: 'contoso_box', title: 'Boxes' },+ ] }] }] },+};++// Each table's plural as the environment holds it.+const plurals = (org) => Object.fromEntries(spec.entities.map((e) => {+ const table = org.metadata.tables.get(e.schemaName);+ return [e.schemaName, table ? org.metadata.textOf(table.DisplayCollectionName) : null];+}));++const ran = (step, what) => {+ if (step.error) throw step.error;+ assert.deepEqual(step.unexpected, [], `every request ${what} sent is one the fake models`);+ return step;+};++let walkP;+const walk = () => walkP || (walkP = (async () => {+ const org = createLifecycleOrg();+ const root = makeTempDir('download-plural-');+ const harness = createLifecycleHarness(org, root);+ const build = ran(await harness.measure(() => harness.build(spec)), 'the build');+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));+ const built = plurals(org);+ const download = ran(await harness.measure(() => harness.download(appUniqueName(spec), path.join(root, 'download'))), 'the download');+ return { org, root, harness, built, download };+})());++test('the build names a table without a plural by the derivation, and keeps each one the spec gives', async () => {+ const { built } = await walk();+ assert.deepEqual(built, { contoso_tag: 'Tags', contoso_order: 'Orders', contoso_ledgerentry: 'Ledger', contoso_box: 'Boxes' });+ assert.equal(built.contoso_tag, derivedPluralName(spec.entities[0], 1033));+});++test('a download writes the plural of each table a rebuild would name differently, and only those', async () => {+ const { download } = await walk();+ const { emitted, spec: downloaded } = download.value;+ assert.equal(emitted.ok, true, JSON.stringify(emitted));+ assert.deepEqual(Object.fromEntries(downloaded.entities.map((e) => [e.schemaName, e.pluralName === undefined ? null : e.pluralName])), {+ contoso_tag: null, contoso_order: null, contoso_ledgerentry: 'Ledger', contoso_box: 'Boxes',+ });+ assert.deepEqual(validateAppSpec(downloaded, { profile: 'plan', reconstructed: true }).errors, []);+});++test('the downloaded spec rebuilt in the same environment writes no table', async () => {+ const { org, harness, root, download } = await walk();+ const before = org.inventory();+ const dir = path.join(root, 'download');+ const rebuild = ran(await harness.measure(() => harness.build(download.value.spec, { appFolder: dir, workspace: path.join(dir, '.maker-workspace') })), 'the rebuild of the downloaded spec');+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));+ const tableWrites = Object.keys(rebuild.writes).filter((w) => /EntityDefinitions/.test(w));+ assert.deepEqual(tableWrites, [], `no table is created or changed: ${JSON.stringify(rebuild.writes)}`);+ assert.deepEqual(org.inventory(), before);+});++test('the downloaded spec built into a fresh environment names each table as the first environment does', async () => {+ const { built, download } = await walk();+ const org = createLifecycleOrg();+ const harness = createLifecycleHarness(org, makeTempDir('download-plural-fresh-'));+ const build = ran(await harness.measure(() => harness.build(download.value.spec)), 'the build into a fresh environment');+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));+ assert.deepEqual(plurals(org), built);+});diff --git a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.jsindex 0d545d88a..63ad77ee9 100644--- a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js+++ b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js@@ -112,6 +112,11 @@ function recordingLifecycleSdk({ systemOnly = false } = {}) {SchemaName: RELATIONSHIP, ReferencedEntity: 'contoso_project', ReferencingEntity: 'contoso_task',ReferencingAttribute: 'contoso_projectid', IsCustomRelationship: true,}] : [] } };+ // The collection the rebuild's own probe reads, from the referenced table: the relationship as the platform lists it, with the lookup+ // that says which relationship it is (a name alone does not identify one).+ if (url.includes('/OneToManyRelationships')) return { status: 200, body: { value: logical === 'contoso_project' ? [{+ SchemaName: RELATIONSHIP, ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid',+ }] : [] } };if (url.includes('/LookupAttributeMetadata')) return { status: 200, body: { value: [] } };if (/\/(?:Attributes|ManyToManyRelationships)/.test(url)) return { status: 200, body: { value: [] } };// The saved (unpublished) layer of every sitemap, read once for the shared-page scan. This fixture holds no pending edit, so each app's saved navigation isdiff --git a/plugins/model-apps/scripts/tests/exit-writes-inventory.test.js b/plugins/model-apps/scripts/tests/exit-writes-inventory.test.jsnew file mode 100644index 000000000..5b77fe7bb--- /dev/null+++ b/plugins/model-apps/scripts/tests/exit-writes-inventory.test.js@@ -0,0 +1,247 @@+'use strict';+// A SYNTACTIC TRIPWIRE on the exits of the plugin's own code. A script that writes and then ends the process at once must make its writes blocking+// first (lib/output-redaction.js makeWritesBlocking), or a pipe on Linux and macOS takes only what fits at once. This scan of the source fails when+// - an exit — `process.exit(…)`, the injectable `io.exit(…)` / `proc.exit(…)`, an `exit(<status>)`, or a call of a name bound to process.exit+// (`const exit = … process.exit`, `const { exit } = process`) — has no makeWritesBlocking call before it in a block that also holds it, and is+// not listed in ALLOWED with the bound that makes it safe without one: it writes nothing, or only a constant text, or a value from a closed set;+// - the call that protects an exit comes after a write in its own block (with no `await` between them), or leaves out a stream that is written+// directly (`process.stderr.write(…)`, `console.log(…)`, …) between it and the exit.+// It reads the source, not what runs: it shows that a new exit has a call before it, not that the call runs, or runs before every write that+// matters. What a process does is shown by printers-whole-before-exit.test.js and result-whole-before-exit.test.js: the order in which a printer+// makes its streams blocking and writes to them, recorded by the process itself, and the text a reader receives.+//+// Read: every .js/.cjs/.mjs file under scripts/ and hooks/ — the scripts the skills run and their libraries, the hooks the host runs, and the+// maintainers' tools in scripts/_vendor-build/ — but not tests/, the generated vendor/ bundle or node_modules/. Comments and the contents of strings,+// templates and regular expressions are blanked first by the plugin's own lexer (lib/source-literals.js), so an exit named in a comment is not one.+// A call protects only as a statement of its own (`makeWritesBlocking(…);` or `x.makeWritesBlocking(…);`) — not as the body of an unbraced `if`,+// `else` or loop, an arrow function or an operand — and the innermost `{ … }` around it must also hold the exit; when it is the first statement of a+// `try` block, the block that holds that `try` (the write it protects is in the try, so that a stream that cannot be read fails with the write).+//+// Known limits, which a reader of a finding (or of a pass) should keep in mind: a write in an enclosing block, or in an earlier turn of the event+// loop (before an `await`), is not compared with the call; a write through a helper (`emitResult`, a `warn(…)`, a stream kept in a variable) is not+// seen — the helper's own call protects it; protection inside a called function is not seen (run-tests.js, smoke-eval.js and+// resolve-interaction-mode.js are listed for it); an exit reached through an alias of another form (an argument, a property of an object other+// than `io` or `proc`) is not found; and control flow is not followed. `process.exitCode` with a natural end waits for the writes and is no exit.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { blankLiterals } = require('../lib/source-literals.js');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const ROOTS = ['scripts', 'hooks', 'scripts/_vendor-build'].map((dir) => path.join(PLUGIN_ROOT, ...dir.split('/')));+const SKIPPED = new Set(['tests', 'vendor', 'node_modules', '_vendor-build']);+const EXIT = /\b(?:process|io|proc)\.exit\s*\(|(?<![.\w$])exit\(\s*\d/g;+const GUARD = /\bmakeWritesBlocking\s*\(/g;+// A name bound to process.exit — a reference that is not a call (`const exit = opts.exit || process.exit;`) or `const { exit } = process;`.+const ALIAS = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=[^;]*?\bprocess\.exit\b(?!\s*\()/g;+const DESTRUCTURED = /\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*process\b/g;+// A direct write, and the stream it goes to: a stream's own `write`, or the console — `log`, `info`, `debug`, `dir` and `table` print on stdout,+// `error`, `warn` and `trace` on stderr (https://nodejs.org/api/console.html#class-console).+const WRITE = /\b(process|io|proc)\.(stdout|stderr)\.write\s*\(|(?<![.\w$])console\.(log|info|debug|dir|table|error|warn|trace)\s*\(/g;+const CONSOLE_STREAM = { log: 'stdout', info: 'stdout', debug: 'stdout', dir: 'stdout', table: 'stdout', error: 'stderr', warn: 'stderr', trace: 'stderr' };++// The exits of one source text that no makeWritesBlocking call protects (`unprotected`, 1-based line numbers), and the protected ones whose call+// comes after a write of its block or leaves out a stream written before the exit (`misguarded`, one sentence each).+function readExits(source) {+ const blank = blankLiterals(source);+ const lineOf = (at) => source.slice(0, at).split('\n').length;+ const blocks = [];+ const open = [];+ for (let i = 0; i < blank.length; i += 1) {+ if (blank[i] === '{') open.push(i);+ else if (blank[i] === '}' && open.length) blocks.push([open.pop(), i]);+ }+ const innermost = (at) => blocks.filter(([a, b]) => a < at && at < b).reduce((best, block) => (!best || block[0] > best[0] ? block : best), null) || [-1, blank.length];+ const closing = (at) => {+ for (let i = at, depth = 0; i < blank.length; i += 1) {+ if (blank[i] === '(') depth += 1;+ else if (blank[i] === ')' && (depth -= 1) === 0) return i;+ }+ return blank.length;+ };+ // A statement of its own: what comes before the call (its receiver skipped — `outputRedaction.`, `require('…').`) is the start of the text, `{`,+ // `}` or `;`. After `)` it is the body of an `if (…)` or a loop; after `=>`, `&&`, `?` or `else` it runs only sometimes, or not here.+ const isStatement = (at) => {+ let i = at - 1;+ const skipSpace = () => { while (i >= 0 && /\s/.test(blank[i])) i -= 1; };+ skipSpace();+ while (blank[i] === '.') {+ i -= 1;+ skipSpace();+ if (blank[i] === ')') {+ for (let depth = 0; i >= 0; i -= 1) {+ if (blank[i] === ')') depth += 1;+ else if (blank[i] === '(' && (depth -= 1) === 0) break;+ }+ i -= 1;+ skipSpace();+ }+ while (i >= 0 && /[\w$]/.test(blank[i])) i -= 1;+ skipSpace();+ }+ return i < 0 || '{};'.includes(blank[i]);+ };+ const exits = new Set([...blank.matchAll(EXIT)].map((m) => m.index));+ const aliases = new Set([...blank.matchAll(ALIAS)].map((m) => m[1]));+ for (const m of blank.matchAll(DESTRUCTURED)) {+ for (const part of m[1].split(',')) {+ const [key, name] = part.split(':').map((word) => word.trim());+ if (key === 'exit') aliases.add(name || key);+ }+ }+ for (const name of aliases) for (const m of blank.matchAll(new RegExp(`(?<![.\\w$])${name.replace(/\$/g, '\\$')}\\s*\\(`, 'g'))) exits.add(m.index);+ const guards = [];+ for (const m of blank.matchAll(GUARD)) {+ // The declaration of the function itself (`function makeWritesBlocking(`) is not a call of it.+ if (/function\s+$/.test(blank.slice(Math.max(0, m.index - 16), m.index)) || !isStatement(m.index)) continue;+ const paren = m.index + m[0].length - 1;+ const names = blank.slice(paren + 1, closing(paren)).split(',').map((name) => name.replace(/\s+/g, '')).filter(Boolean);+ let [a, b] = innermost(m.index);+ if (a >= 0 && /\btry\s*$/.test(blank.slice(0, a)) && blank.slice(a + 1, m.index).trim() === '') [a, b] = innermost(a);+ guards.push({ at: m.index, a, b, names });+ }+ const writes = [...blank.matchAll(WRITE)].map((m) => ({ at: m.index, stream: m[1] ? `${m[1]}.${m[2]}` : `process.${CONSOLE_STREAM[m[3]]}` }));+ const unprotected = [];+ const misguarded = [];+ for (const at of [...exits].sort((x, y) => x - y)) {+ const by = guards.filter((guard) => guard.at < at && guard.a < at && at < guard.b);+ if (!by.length) {+ unprotected.push(lineOf(at));+ continue;+ }+ const first = by[0];+ for (const write of writes) {+ if (write.at > first.at && write.at < at && !by.some((guard) => guard.at < write.at && guard.names.includes(write.stream))) {+ misguarded.push(`the exit on line ${lineOf(at)}: ${write.stream} is written on line ${lineOf(write.at)}, and no makeWritesBlocking call before it names it`);+ }+ if (write.at > first.a && write.at < first.at && innermost(write.at)[0] === first.a && !/\bawait\b/.test(blank.slice(write.at, first.at))) {+ misguarded.push(`the exit on line ${lineOf(at)}: ${write.stream} is written on line ${lineOf(write.at)}, before the makeWritesBlocking call of its block (line ${lineOf(first.at)})`);+ }+ }+ }+ return { unprotected, misguarded };+}++const unprotectedExits = (source) => readExits(source).unprotected;++function productionFiles() {+ const files = new Set();+ const walk = (dir) => {+ if (!fs.existsSync(dir)) return;+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!SKIPPED.has(entry.name)) walk(full);+ } else if (/\.(?:c|m)?js$/.test(entry.name)) {+ files.add(full);+ }+ }+ };+ for (const root of ROOTS) walk(root);+ return [...files].sort();+}++const label = (file) => path.relative(PLUGIN_ROOT, file).split(path.sep).join('/');++// Each exit left unprotected, per file: how many, and the bound that makes it safe. The USAGE constants are at most 425 bytes (teardown-model-app.js's,+// the longest of either plugin, measured) and are the first thing the process writes, so an empty pipe takes them at once: a pipe takes at least 4 KiB+// at once on either system, one page when Linux has shrunk it for a user over their pipe quota, and normally 64 KiB (Linux) or 16 KiB (macOS).+const NOTHING = 'writes nothing before it ends';+const USAGE = 'prints only its USAGE constant (at most 425 bytes) as its first output';+const ALLOWED = {+ 'hooks/run-skill-posttool-validation.js': [3, 'the kill switch writes nothing; the two debug lines (DEBUG=1 only) are a constant and the name of one of the plugin\'s own skills'],+ 'hooks/run-skill-pretool-telemetry.js': [9, `the telemetry hook ${NOTHING} on any path`],+ 'hooks/run-user-prompt-telemetry.js': [7, `the telemetry hook ${NOTHING} on any path`],+ 'hooks/validate-icon-imports.js': [10, `every fail-open path ${NOTHING}; the two that block are protected`],+ 'hooks/validate-write-safety.js': [4, `the kill switch and the not-a-write-tool path write nothing; the two debug lines (DEBUG=1 only) are constants`],+ 'scripts/_vendor-build/build-typescript.js': [1, 'a maintainer tool\'s two constant usage lines'],+ 'scripts/_vendor-build/build.js': [4, 'a maintainer tool\'s constant lines; one names a count of changes and a commit hash (about 300 bytes)'],+ 'scripts/add-page-to-solution.js': [1, USAGE],+ 'scripts/ai-preflight.js': [1, USAGE],+ 'scripts/build-model-app.js': [2, `${USAGE}, or one constant line`],+ 'scripts/capture-fixture.js': [1, '--help prints a constant help text (704 bytes)'],+ 'scripts/check-version.js': [3, NOTHING],+ 'scripts/create-connection-reference.js': [1, USAGE],+ 'scripts/dataverse-request.js': [1, USAGE],+ 'scripts/download-model-app.js': [1, USAGE],+ 'scripts/generate-page-manifest.js': [1, '--help prints a constant help text (329 bytes)'],+ 'scripts/launch-playwright-mcp.js': [2, 'the server\'s own end: a signal\'s name, or nothing (the server wrote its output itself)'],+ 'scripts/lib/exit-cleanup.js': [2, `ends the process on a signal and ${NOTHING}`],+ 'scripts/lib/feature-flags.js': [3, 'the Custom API gate\'s constant message (440 bytes and its line break), the CLI\'s constant usage line, and "enabled" or "disabled"'],+ 'scripts/lib/telemetry/lib/emit-dispatcher.js': [1, `the detached dispatcher ${NOTHING}`],+ 'scripts/lib/telemetry/lib/telemetry-config.js': [4, 'the shared telemetry library (shared/telemetry, copied into five plugins), which the telemetry skill runs without --plugin: constant sentences and the plugin\'s own name (about 1.2 KB measured), and the config folder\'s path once or twice; under the 4 KiB any pipe takes at once unless that path is over 1,400 characters'],+ 'scripts/list-connections.js': [1, USAGE],+ 'scripts/list-custom-apis.js': [1, USAGE],+ 'scripts/list-languages.js': [1, USAGE],+ 'scripts/preview-app.js': [1, USAGE],+ 'scripts/preview-form.js': [1, USAGE],+ 'scripts/promote-intent-pages.js': [3, `${USAGE}, or a constant line, or a typeof name (a closed set)`],+ 'scripts/provision-entities.js': [1, USAGE],+ 'scripts/provision-solution.js': [1, USAGE],+ 'scripts/resolve-interaction-mode.js': [1, 'main prints {"ok":true,"interactive",…,"reason"} with a reason from a closed set of three (under 120 bytes)'],+ 'scripts/run-tests.js': [1, 'main makes both streams blocking before its reports; its usage line is a constant'],+ 'scripts/smoke-eval.js': [2, 'a constant usage line; main makes both streams blocking when it starts, before everything it forwards'],+ 'scripts/teardown-model-app.js': [1, USAGE],+ 'scripts/verify-model-app.js': [1, USAGE],+ 'scripts/write-app-spec-doc.js': [1, USAGE],+ 'scripts/write-page-plan.js': [1, USAGE],+};++test('the inventory reader: what protects an exit, what does not, and a call that comes after a write or leaves out a stream', () => {+ const source = [+ 'function printer(text) {',+ ' makeWritesBlocking(process.stdout, process.stderr);',+ ' if (text) { process.stdout.write(text); process.exit(0); }',+ ' process.exit(1);',+ '}',+ 'function other() {',+ ' if (a) { makeWritesBlocking(process.stderr); process.stderr.write("x"); process.exit(2); }',+ ' if (b) { process.stderr.write("y"); process.exit(3); }',+ '}',+ '// process.exit(4) in a comment, and "process.exit(5)" in a string',+ 'main().then((code) => process.exit(code));',+ 'const exit = opts.exit || process.exit; exit(6); exit(text ? 0 : 1);',+ 'io.exit(1); proc.exit(1);',+ 'function makeWritesBlocking(...streams) { process.exit(7); }',+ 'function skipped(text) { if (quiet) makeWritesBlocking(process.stdout); process.stdout.write(text); process.exit(0); }',+ 'function operand(text) { const later = () => makeWritesBlocking(process.stdout); process.stdout.write(text); process.exit(0); }',+ 'const { exit: quit } = process; quit(9);',+ 'function fatal(text) { try { makeWritesBlocking(process.stderr); process.stderr.write(text); } catch {} process.exit(1); }',+ 'function notFirst(text) { try { prepare(); makeWritesBlocking(process.stderr); process.stderr.write(text); } catch {} process.exit(1); }',+ 'function member(text) { require("./lib/output-redaction.js").makeWritesBlocking(process.stdout, process.stderr); console.log(text); process.exit(0); }',+ 'function wrongStream(text) { makeWritesBlocking(process.stderr); process.stdout.write(text); process.exit(0); }',+ 'function lateGuard(text) { process.stdout.write(text); makeWritesBlocking(process.stdout); process.exit(0); }',+ 'function viaConsole(text) { makeWritesBlocking(process.stdout); console.error(text); process.exit(1); }',+ 'async function earlierTurn(text) { process.stderr.write("working"); await done(); makeWritesBlocking(process.stdout, process.stderr); console.error(text); process.exit(1); }',+ 'function ended(text) { if (text) { makeWritesBlocking(process.stderr); process.stderr.write(text); process.exit(2); } makeWritesBlocking(process.stderr); process.stderr.write("none"); process.exit(2); }',+ ].join('\n');+ // Not protected: a branch without the call, a callback, an alias (called with a status, and without one), io/proc, an exit in the function itself,+ // a call in an unbraced if, a call in an arrow function, a destructured alias, and a call that is not the first statement of its try.+ assert.deepEqual(unprotectedExits(source), [8, 11, 12, 12, 13, 13, 14, 15, 16, 17, 19]);+ assert.deepEqual(readExits(source).misguarded, [+ 'the exit on line 21: process.stdout is written on line 21, and no makeWritesBlocking call before it names it',+ 'the exit on line 22: process.stdout is written on line 22, before the makeWritesBlocking call of its block (line 22)',+ 'the exit on line 23: process.stderr is written on line 23, and no makeWritesBlocking call before it names it',+ ]);+});++test('every exit of the plugin\'s own code is protected, or listed with the bound that makes it safe — and nothing listed is gone; no protecting call comes after a write of its block or leaves out a stream', () => {+ const found = {};+ const misguarded = [];+ let exits = 0;+ for (const file of productionFiles()) {+ const source = fs.readFileSync(file, 'utf8');+ exits += [...blankLiterals(source).matchAll(EXIT)].length;+ const read = readExits(source);+ if (read.unprotected.length) found[label(file)] = read.unprotected;+ misguarded.push(...read.misguarded.map((finding) => `${label(file)}: ${finding}`));+ }+ assert.ok(exits > 140, `the scan read the plugin (${exits} exits)`);+ assert.deepEqual(misguarded, [], 'a makeWritesBlocking call that comes after a write of its block, or leaves out a stream written before the exit it protects');+ const unlisted = Object.keys(found).filter((file) => !ALLOWED[file]).map((file) => `${file}: lines ${found[file].join(', ')}`);+ assert.deepEqual(unlisted, [], 'an exit that is neither protected by makeWritesBlocking nor listed in ALLOWED with its bound');+ const changed = Object.entries(ALLOWED).filter(([file, [count]]) => (found[file] || []).length !== count)+ .map(([file, [count]]) => `${file}: listed ${count}, found ${(found[file] || []).length} (lines ${(found[file] || []).join(', ') || 'none'})`);+ assert.deepEqual(changed, [], 'a listed file whose unprotected exits changed: protect the new one, or update its count and bound');+});diff --git a/plugins/model-apps/scripts/tests/fake-lifecycle-org-contract.test.js b/plugins/model-apps/scripts/tests/fake-lifecycle-org-contract.test.jsnew file mode 100644index 000000000..93bc8e390--- /dev/null+++ b/plugins/model-apps/scripts/tests/fake-lifecycle-org-contract.test.js@@ -0,0 +1,239 @@+'use strict';+// The CONTRACT of the stateful fake the lifecycle tests run on (helpers/fake-lifecycle-org.js, fake-lifecycle-metadata.js): a read it+// does not model must FAIL LOUD — 501 and an entry in `org.unexpected`, which every lifecycle test asserts is empty — and never answer+// an empty success that the code under test could take for "nothing there". Each refusal is pinned twice, over a collection that holds+// rows and over one that holds none (the check runs before any row is looked at), beside a control that the same shape with a known+// name is answered. A read it DOES accept must answer what it asks for — every option applied, pinned on the values and the row counts+// it returns; a function's arguments and a record's key are checked before anything is resolved. And the content proof the lifecycle+// tests rely on (org.contents + diffContents) is pinned to see an overwrite the identity inventory cannot.+const test = require('node:test');+const assert = require('node:assert/strict');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { seedForeignWork, diffContents, FOREIGN } = require('./helpers/lifecycle-harness.js');++const BASIC_USER = '11111111-0000-4000-8000-000000000007';++async function send(org, method, where, body, headers = {}) {+ const from = org.unexpected.length;+ const res = await org.request({ url: `${org.API}${where}`, method, headers: { 'Content-Type': 'application/json', ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null, unexpected: org.unexpected.slice(from) };+}+// A fresh environment with another maker's work in it (populated), and one with nothing but what a new environment has (empty).+async function populated() {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ return org;+}+const empty = async () => createLifecycleOrg();++// A refusal: 501, the platform's error envelope, and one `unexpected` entry that names what was not modelled.+function refused(res, names) {+ assert.equal(res.status, 501, JSON.stringify(res.body));+ assert.equal(res.unexpected.length, 1);+ assert.match(res.unexpected[0], names);+ assert.match(res.body.error.message, /does not model/);+}+const answered = (res) => { assert.equal(res.status, 200, JSON.stringify(res.body)); assert.deepEqual(res.unexpected, []); return res.body; };++// The record reads. `workflows` holds no row in either environment, `solutions` and `roles` hold several.+const RECORD_CASES = [+ { what: 'an unknown column in $filter', populated: "/solutions?$filter=unmodelledfield eq 'FabrikamCore'", empty: "/workflows?$filter=unmodelledfield eq 'x'", names: /no column unmodelledfield/, control: "/solutions?$filter=uniquename eq 'FabrikamCore'&$select=solutionid" },+ { what: 'an unknown filter function', populated: '/solutions?$filter=mystery(uniquename)', empty: '/workflows?$filter=mystery(name)', names: /function mystery is not modelled/, control: "/solutions?$filter=contains(uniquename,'fabrikam')&$select=solutionid" },+ { what: 'an unknown column in $select', populated: '/roles?$select=roleid,unmodelledfield', empty: '/workflows?$select=workflowid,unmodelledfield', names: /no column unmodelledfield \(\$select/, control: '/roles?$select=roleid,name,description' },+ { what: 'an unknown column in $orderby', populated: '/publishers?$orderby=unmodelledfield desc', empty: '/workflows?$orderby=unmodelledfield', names: /no column unmodelledfield \(\$orderby/, control: '/publishers?$select=publisherid&$orderby=uniquename desc' },+ { what: 'an unknown query option', populated: '/roles?$apply=groupby((name))', empty: '/workflows?$count=true', names: /query option \$(apply|count) is not modelled/, control: '/roles?$select=roleid&$top=1' },+ { what: 'an unknown navigation in a lambda', populated: `/roles?$filter=unknown_association/any(x:x/roleid eq ${FOREIGN.app})`, empty: `/workflows?$filter=unknown_association/any(x:x/workflowid eq ${FOREIGN.app})`, names: /has no navigation unknown_association/, control: `/appmodules?$select=appmoduleid&$filter=appmoduleroles_association/any(x:x/roleid eq ${BASIC_USER})` },+ { what: 'an unknown column of the rows a lambda reads', populated: `/appmodules?$filter=appmoduleroles_association/any(x:x/nothere eq ${BASIC_USER})`, empty: `/appmodules?$filter=appmoduleroles_association/any(x:x/nothere eq ${BASIC_USER})`, names: /role has no column nothere/, control: `/appmodules?$select=appmoduleid&$filter=appmoduleroles_association/any(x:x/name eq 'Basic User')` },+ { what: 'a navigation path to a column that is not the key', populated: "/roles?$filter=parentrootroleid/name eq 'Basic User'", empty: "/workflows?$filter=parentworkflowid/workflowid eq null", names: /navigation path/, control: `/roles?$select=roleid&$filter=parentrootroleid/roleid eq ${BASIC_USER}` },+ { what: 'an unknown $expand', populated: '/solutions?$expand=unknownnav($select=x)', empty: '/workflows?$expand=publisherid($select=publisherid)', names: /\$expand=(unknownnav|publisherid) on/, control: '/solutions?$select=solutionid&$expand=publisherid($select=publisherid,uniquename)' },+ { what: 'an unknown column of an expanded row', populated: '/solutions?$expand=publisherid($select=nothere)', empty: '/solutions?$expand=publisherid($select=nothere)', names: /publisher has no column nothere/, control: '/solutions?$select=solutionid&$expand=publisherid($select=customizationprefix)' },+];++for (const c of RECORD_CASES) {+ test(`fake contract: ${c.what} is refused, over a collection with rows and one without`, async () => {+ refused(await send(await populated(), 'GET', c.populated), c.names);+ refused(await send(await empty(), 'GET', c.empty), c.names);+ answered(await send(await populated(), 'GET', c.control));+ });+}++test('fake contract: an unknown single-row navigation, a function and a path suffix are refused; the declared one is answered', async () => {+ const org = await populated();+ refused(await send(org, 'GET', `/roles(${BASIC_USER})/unknown_association`), /has no navigation unknown_association/);+ refused(await send(org, 'GET', `/roles(${BASIC_USER})/Microsoft.Dynamics.CRM.Mystery()`), /has no navigation|GET \/roles/);+ refused(await send(org, 'GET', `/roles(${BASIC_USER})/appmoduleroles_association/extra`), /GET \/roles/);+ refused(await send(org, 'GET', `/roles(${BASIC_USER})/appmoduleroles_association?$select=nothere`), /appmodule has no column nothere/);+ refused(await send(org, 'GET', '/notamodelledset'), /no table has the entity set notamodelledset/);+ assert.deepEqual(answered(await send(org, 'GET', `/roles(${BASIC_USER})/appmoduleroles_association?$select=appmoduleid`)).value, []);+});++test('fake contract: the page tables refuse an unknown column before the page fake sees the read', async () => {+ for (const org of [await populated(), await empty()]) {+ refused(await send(org, 'GET', '/uxagentprojects?$select=uxagentprojectid,nothere'), /uxagentproject has no column nothere/);+ refused(await send(org, 'GET', "/uxagentprojectfiles?$filter=nothere eq 'x'"), /uxagentprojectfile has no column nothere/);+ refused(await send(org, 'GET', '/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$filter=mystery(name)'), /function mystery/);+ answered(await send(org, 'GET', '/uxagentprojects?$select=uxagentprojectid,name'));+ }+});++test('fake contract: a column the platform lets be empty reads null; one it always fills, missing from a row, is refused', async () => {+ const org = await populated();+ const solutions = answered(await send(org, 'GET', "/solutions?$select=uniquename,description&$filter=uniquename eq 'Default'")).value;+ assert.deepEqual(solutions.map((s) => [s.uniquename, s.description]), [['Default', null]]);+ // A row the fake made without a column every row of its table has: the read names the gap instead of answering null.+ const publisher = [...org.rowsOf('publishers').values()].find((row) => row.data.uniquename === 'fabrikam');+ delete publisher.data.friendlyname;+ refused(await send(org, 'GET', '/publishers?$select=uniquename,friendlyname'), /holds no friendlyname, which the platform always fills/);+});++// The metadata reads. A fresh environment has no relationship and no global option set; the seeded one has both.+const METADATA_CASES = [+ { what: 'an unknown attribute cast', populated: "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes/Microsoft.Dynamics.CRM.UnknownAttributeMetadata", empty: "/EntityDefinitions(LogicalName='account')/Attributes/Microsoft.Dynamics.CRM.UnknownAttributeMetadata", names: /cast UnknownAttributeMetadata/, control: "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength" },+ { what: 'an unknown *Relationships navigation', populated: "/EntityDefinitions(LogicalName='fabrikam_widget')/UnknownRelationships", empty: "/EntityDefinitions(LogicalName='account')/UnknownRelationships", names: /UnknownRelationships is not modelled/, control: "/EntityDefinitions(LogicalName='account')/OneToManyRelationships?$select=SchemaName" },+ { what: 'an unknown GlobalOptionSetDefinitions navigation', populated: '/GlobalOptionSetDefinitions/UnknownNavigation?$select=Name', empty: '/GlobalOptionSetDefinitions/UnknownNavigation?$select=Name', names: /GlobalOptionSetDefinitions\/UnknownNavigation is not modelled/, control: '/GlobalOptionSetDefinitions?$select=Name' },+ { what: 'an unknown property in $filter', populated: "/EntityDefinitions?$select=LogicalName&$filter=UnknownProperty eq 'fabrikam_widget'", empty: "/RelationshipDefinitions?$select=SchemaName&$filter=UnknownProperty eq 'x'", names: /has no property UnknownProperty \(\$filter/, control: "/EntityDefinitions?$select=LogicalName&$filter=LogicalName eq 'fabrikam_widget'" },+ { what: 'an unknown property in $select', populated: '/GlobalOptionSetDefinitions?$select=Name,UnknownProperty', empty: '/GlobalOptionSetDefinitions?$select=Name,UnknownProperty', names: /has no property UnknownProperty \(\$select/, control: '/GlobalOptionSetDefinitions?$select=Name,IsManaged,Description' },+ { what: "a derived type's property on the base collection", populated: "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes?$select=LogicalName,MaxLength", empty: "/EntityDefinitions(LogicalName='account')/Attributes?$select=LogicalName,MaxLength", names: /AttributeMetadata has no property MaxLength/, control: "/EntityDefinitions(LogicalName='account')/Attributes?$select=LogicalName,AttributeType" },+ { what: 'an unknown $expand of a table', populated: "/EntityDefinitions(LogicalName='fabrikam_widget')?$expand=UnknownNavigation", empty: "/EntityDefinitions(LogicalName='account')?$expand=Attributes($select=MaxLength)", names: /has no (navigation UnknownNavigation|property MaxLength)/, control: "/EntityDefinitions(LogicalName='account')?$select=LogicalName&$expand=Attributes($select=LogicalName)" },+ { what: 'an unknown relationship cast', populated: '/RelationshipDefinitions/Microsoft.Dynamics.CRM.UnknownRelationshipMetadata', empty: '/RelationshipDefinitions/Microsoft.Dynamics.CRM.UnknownRelationshipMetadata', names: /cast UnknownRelationshipMetadata/, control: '/RelationshipDefinitions/Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata?$select=SchemaName,ReferencedEntity' },+ { what: 'a key a collection is not keyed by', populated: "/EntityDefinitions(SchemaName='fabrikam_widget')", empty: "/EntityDefinitions(SchemaName='account')", names: /not keyed by SchemaName/, control: "/EntityDefinitions(LogicalName='account')?$select=LogicalName" },+];++for (const c of METADATA_CASES) {+ test(`fake contract: metadata — ${c.what} is refused, with definitions and without`, async () => {+ refused(await send(await populated(), 'GET', c.populated), c.names);+ refused(await send(await empty(), 'GET', c.empty), c.names);+ answered(await send(await populated(), 'GET', c.control));+ });+}++test("fake contract: a Money column's base-currency twin has the live-measured flags, and goes with the column", async () => {+ const org = await populated();+ const label = (text) => ({ LocalizedLabels: [{ Label: text, LanguageCode: 1033 }] });+ const created = await send(org, 'POST', "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes", { '@odata.type': 'Microsoft.Dynamics.CRM.MoneyAttributeMetadata', SchemaName: 'fabrikam_price', DisplayName: label('Price'), RequiredLevel: { Value: 'None' }, PrecisionSource: 2 });+ assert.equal(created.status, 204);+ const read = answered(await send(org, 'GET', "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes?$select=LogicalName,AttributeType,AttributeOf,IsLogical,IsCustomAttribute,IsValidForCreate&$filter=startswith(LogicalName,'fabrikam_price')")).value;+ const money = answered(await send(org, 'GET', "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency")).value;+ // As measured on stock opportunity.estimatedvalue / estimatedvalue_base (download-model-app.test.js pins the same shape): the twin+ // is a physical, custom, non-logical column with NO AttributeOf — only IsBaseCurrency tells it from the column it converts.+ assert.deepEqual(read.map((a) => [a.LogicalName, a.AttributeType, a.AttributeOf, a.IsLogical, a.IsCustomAttribute, a.IsValidForCreate]).sort(), [+ ['fabrikam_price', 'Money', null, false, true, true],+ ['fabrikam_price_base', 'Money', null, false, true, false],+ ]);+ assert.deepEqual(money.map((a) => [a.LogicalName, a.IsBaseCurrency]).sort(), [['fabrikam_price', false], ['fabrikam_price_base', true]]);+ assert.equal((await send(org, 'DELETE', "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes(LogicalName='fabrikam_price')")).status, 204);+ assert.deepEqual([...org.metadata.tables.get('fabrikam_widget').Attributes.keys()].filter((name) => name.startsWith('fabrikam_price')), []);+});++test("fake contract: the content proof sees another maker's work overwritten, which the identity inventory does not", async () => {+ const overwrites = [+ ['the foreign view\'s FetchXML', async (org) => { const v = org.find('savedqueries', (r) => r.name === 'Open Projects')[0]; return send(org, 'PATCH', `/savedqueries(${v.savedqueryid})`, { fetchxml: '<fetch><entity name="wrong_table"/></fetch>' }); }, /changed: savedqueries .* "Open Projects" \(saved\.fetchxml, saved\.modifiedon, saved\.versionnumber\)/],+ ['the foreign web resource\'s content', async (org) => { const w = org.find('webresourceset', (r) => r.name === 'fabrikam_widget.js')[0]; return send(org, 'PATCH', `/webresourceset(${w.webresourceid})`, { content: Buffer.from('destroyed').toString('base64') }); }, /changed: webresourceset .* "fabrikam_widget\.js" \(saved\.content/],+ ['the foreign column\'s maximum length', async (org) => send(org, 'PUT', "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes(LogicalName='fabrikam_name')", { MaxLength: 1 }), /changed: table fabrikam_widget \(Attributes\.fabrikam_name\)/],+ ['the foreign global choice\'s options', async (org) => send(org, 'PUT', "/GlobalOptionSetDefinitions(Name='fabrikam_size')", { Options: [] }), /changed: global option set fabrikam_size \(.*\bOptions\)/],+ ];+ for (const [what, overwrite, reported] of overwrites) {+ const org = await populated();+ const inventory = org.inventory();+ const before = org.contents();+ const res = await overwrite(org);+ assert.equal(res.status, 204, what);+ assert.deepEqual(org.inventory(), inventory, `${what}: the identity inventory does not see it`);+ const changes = diffContents(before, org.contents());+ assert.equal(changes.length, 1, `${what}: ${JSON.stringify(changes)}`);+ assert.match(changes[0], reported, what);+ }+});++// ====================================================================================================================================+// What an ACCEPTED read answers: every option the checker admits is applied — the values and the row counts below, not only the status.++// A second page that only has a draft, next to the published one the seed made: the two layers a page read can see.+const DRAFT_PAGE = '33333333-0000-4000-8000-000000000001';+async function withDraftPage() {+ const org = await populated();+ org.pageServer.seedPage(DRAFT_PAGE, { name: 'AAA Page' });+ return org;+}+const keysOf = (row) => Object.keys(row).sort();++test('fake contract: a page read applies its $filter, $select, $orderby and $top, over the layer it sees', async () => {+ const org = await withDraftPage();+ const values = async (where, headers) => answered(await send(org, 'GET', where, undefined, headers)).value;+ // The plain read is the published layer: the draft page is not in it, and a filter on any column narrows it.+ assert.deepEqual(await values("/uxagentprojects?$select=uxagentprojectid&$filter=name eq 'No Such Page'"), []);+ const widget = await values("/uxagentprojects?$select=uxagentprojectid&$filter=name eq 'Widget Board'");+ assert.deepEqual(widget.map((row) => [row.uxagentprojectid, keysOf(row)]), [[FOREIGN.page, ['@odata.etag', 'uxagentprojectid']]]);+ assert.deepEqual((await values('/uxagentprojects?$select=name')).map((row) => row.name), ['Widget Board']);+ // With MSCRM.IncludeUnpublished the saved rows are seen, drafts included, in the order asked for, cut at $top.+ const unpublished = { 'MSCRM.IncludeUnpublished': 'true' };+ assert.deepEqual((await values('/uxagentprojects?$select=name&$orderby=name asc', unpublished)).map((row) => row.name), ['AAA Page', 'Widget Board']);+ assert.deepEqual((await values('/uxagentprojects?$select=name&$orderby=name desc&$top=1', unpublished)).map((row) => row.name), ['Widget Board']);+ // RetrieveUnpublishedMultiple() is the saved layer with componentstate.+ const many = '/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()';+ assert.deepEqual(await values(`${many}?$select=uxagentprojectid&$top=0`), []);+ const first = await values(`${many}?$select=uxagentprojectid&$orderby=name asc&$top=1`);+ assert.deepEqual(first.map((row) => [row.uxagentprojectid, keysOf(row)]), [[DRAFT_PAGE, ['@odata.etag', 'uxagentprojectid']]]);+ assert.deepEqual((await values(`${many}?$select=name,componentstate&$filter=componentstate eq 1`)).map((row) => [row.name, row.componentstate]), [['AAA Page', 1]]);+ assert.deepEqual((await values(`${many}?$select=name&$filter=startswith(name,'Widget')`)).map((row) => row.name), ['Widget Board']);+ // By id: the selected columns, the draft only with the header.+ const byId = answered(await send(org, 'GET', `/uxagentprojects(${FOREIGN.page})?$select=name`));+ assert.deepEqual([byId.name, keysOf(byId)], ['Widget Board', ['@odata.etag', 'name', 'uxagentprojectid']]);+ assert.equal((await send(org, 'GET', `/uxagentprojects(${DRAFT_PAGE})?$select=name`)).status, 404);+ assert.equal(answered(await send(org, 'GET', `/uxagentprojects(${DRAFT_PAGE})?$select=name`, undefined, unpublished)).name, 'AAA Page');+});++test("fake contract: a page's files and conversation are read with their own filter, order, cut and columns", async () => {+ const org = await withDraftPage();+ const values = async (where) => answered(await send(org, 'GET', where)).value;+ // The published page's four files; the draft page's are not in the published layer.+ const files = await values(`/uxagentprojectfiles?$select=filename&$filter=_uxagentprojectid_value eq ${FOREIGN.page}&$orderby=filename desc&$top=2`);+ assert.deepEqual(files.map((row) => [row.filename, keysOf(row)]), [+ ['src/pages/page.tsx', ['@odata.etag', 'filename', 'uxagentprojectfileid']],+ ['src/pages/page.compiled', ['@odata.etag', 'filename', 'uxagentprojectfileid']],+ ]);+ assert.deepEqual((await values('/uxagentprojectfiles?$select=filename&$filter=filetype eq 200000001')).map((row) => row.filename), ['src/pages/page.compiled']);+ assert.deepEqual(await values(`/uxagentprojectfiles?$select=filename&$filter=_uxagentprojectid_value eq ${DRAFT_PAGE}`), []);+ // The conversation, in the order it was had; a filter on the sender, a cut, and only the columns asked for.+ const turns = await values(`/agentconversationmessages?$select=message&$filter=_regardingobjectid_value eq ${FOREIGN.page}&$orderby=createdon asc,versionnumber asc`);+ assert.deepEqual(turns.map((row) => [row.message, keysOf(row)]), [['Seeded', ['agentconversationmessageid', 'message']], ['Done', ['agentconversationmessageid', 'message']]]);+ assert.deepEqual((await values(`/agentconversationmessages?$select=message&$filter=_regardingobjectid_value eq ${FOREIGN.page} and messagesender eq 200000001`)).map((row) => row.message), ['Done']);+ assert.deepEqual((await values(`/agentconversationmessages?$select=message&$filter=_regardingobjectid_value eq ${DRAFT_PAGE}&$orderby=versionnumber desc&$top=1`)).map((row) => row.message), ['Done']);+});++test('fake contract: a record read applies its options — $expand by id, values, counts — and a write answers its $select', async () => {+ const org = await populated();+ const single = answered(await send(org, 'GET', `/solutions(${FOREIGN.solution})?$select=solutionid&$expand=publisherid($select=customizationprefix)`));+ assert.deepEqual([keysOf(single), single.publisherid.customizationprefix, keysOf(single.publisherid)], [['@odata.etag', 'publisherid', 'solutionid'], 'fabrikam', ['@odata.etag', 'customizationprefix', 'publisherid']]);+ const values = async (where) => answered(await send(org, 'GET', where)).value;+ assert.deepEqual((await values('/roles?$select=name&$filter=ismanaged eq true&$orderby=name desc&$top=1')).map((row) => row.name), ['System Administrator']);+ assert.deepEqual(await values('/roles?$select=name&$top=0'), []);+ assert.deepEqual((await values("/roles?$select=name&$filter=ismanaged eq false and startswith(name,'Fabrikam')")).map((row) => row.name), ['Fabrikam Reader']);+ // Prefer: return=representation answers the created row narrowed by the write's own $select.+ const created = await send(org, 'POST', '/publishers?$select=uniquename', { uniquename: 'adatum', friendlyname: 'Adatum', customizationprefix: 'adatum', customizationoptionvalueprefix: 30000 }, { Prefer: 'return=representation' });+ assert.equal(created.status, 201);+ assert.deepEqual([keysOf(created.body), created.body.uniquename], [['@odata.etag', 'publisherid', 'uniquename'], 'adatum']);+});++// What a function's arguments and a record's key may be: anything else is refused before any row is resolved — never a 200 that+// ignored an argument, never a 404 that "proved" an absence.+test('fake contract: an unknown or missing function argument, and a key that is not a record id, are refused', async () => {+ const org = await populated();+ refused(await send(org, 'GET', "/RetrieveSetting(SettingName='NewLookAlwaysOn',Unknown='x')"), /the parameter Unknown of RetrieveSetting is not modelled/);+ refused(await send(org, 'GET', "/RetrieveSetting(Unknown='NewLookAlwaysOn')"), /the parameter Unknown of RetrieveSetting is not modelled/);+ refused(await send(org, 'GET', "/RetrieveSetting(AppUniqueName='fabrikam_widgets')"), /RetrieveSetting without its SettingName/);+ refused(await send(org, 'GET', '/RetrieveSetting(SettingName=@p)?@p=1'), /not modelled/);+ refused(await send(org, 'GET', "/solutions(Unknown='FabrikamCore')"), /the key \(Unknown='FabrikamCore'\) on GET \/solutions/);+ refused(await send(org, 'PATCH', "/solutions(Unknown='FabrikamCore')", { description: 'x' }), /the key \(Unknown='FabrikamCore'\)/);+ refused(await send(org, 'GET', '/roles(basic-user)/appmoduleroles_association?$select=appmoduleid'), /the key \(basic-user\)/);+ refused(await send(org, 'GET', "/uxagentprojects(name='Widget Board')"), /the key \(name='Widget Board'\)/);+ refused(await send(org, 'GET', "/systemforms(formid='x')/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=name"), /the key \(formid='x'\)/);+ refused(await send(org, 'POST', '/roles', { name: 'Adatum Reader', '[email protected]': "/businessunits(name='contoso')" }), /the key \(name='contoso'\) on the bind/);+ refused(await send(org, 'GET', "/systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='fabrikam_widget'&@t=2&@u={'@odata.id':'systemusers(44444444-0000-4000-8000-000000000001)'}"), /only the maker is/);+ // The same reads, well formed, are answered.+ assert.equal(answered(await send(org, 'GET', "/RetrieveSetting(SettingName='NewLookAlwaysOn')")).SettingDetail.Value, 'false');+ assert.equal(answered(await send(org, 'GET', "/RetrieveSetting(SettingName='NewLookAlwaysOn',AppUniqueName='fabrikam_widgets')")).SettingDetail.Value, 'false');+ assert.equal(answered(await send(org, 'GET', `/solutions(${FOREIGN.solution})?$select=uniquename`)).uniquename, 'FabrikamCore');+ assert.equal((await send(org, 'GET', '/solutions(44444444-0000-4000-8000-000000000001)?$select=uniquename')).status, 404, 'a well-formed id that names no row is the platform\'s 404');+ assert.deepEqual(answered(await send(org, 'GET', "/systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='fabrikam_widget'&@t=2&@u={'@odata.id':'systemusers(11111111-0000-4000-8000-000000000003)'}")).value.length, 1);+});diff --git a/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.jsindex 8b451f401..dae5aeda9 100644--- a/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.js@@ -24,6 +24,7 @@ const { runSdkBuild } = require('../lib/sdk-build.js');const { buildModelApp } = require('../build-model-app.js');const { createHarness, seedForm, verifyForms } = require('./helpers/form-store-harness.js');const { readLanguageCodeFlag } = require('../lib/dataverse-auth.js');+const { workbookXml, zipOf, exportZip, exportAnswer } = require('./helpers/translation-export.js');const harnesses = [];test.after(() => { for (const h of harnesses) h.cleanup(); });@@ -243,3 +244,139 @@ test('REAL BUNDLE: a {1033, 3082} label map over that form — the English captiassert.doesNotMatch(topology(stale).detail, /3082/, 'a language the read cannot show is not reported missing');assert.match(stale.unverified[0], MAP_ENTRY, 'and it is still listed');});++// --- The same form, read with ONE translation export -------------------------------------------------------------------------------------------+//+// What the form read cannot show a translation export can: it carries every provisioned language, the published layer, and a tab's or a section's captions are the rows whose+// Object ID is the `id` the element has in the FormXML. The harness answers the export for the form it stores (`exportOfStoredForm`: a row per tab and section, with the captions+// the store holds in each language — what the platform would write), and the reader that asks for it is the plugin's own (`readerFor`, over the real SDK's Dataverse client).+const idsOf = (h) => Object.fromEntries([...h.store.row.formxml.matchAll(/<(tab|section)\b([^>]*)>/g)].map((m) => [/\bname="([^"]*)"/.exec(m[2])[1], /\bid="([^"]+)"/.exec(m[2])[1]]));+function exportOfStoredForm(h, { override = {}, languages = [1033, 3082] } = {}) {+ const ids = idsOf(h);+ const captions = [];+ for (const m of h.store.row.formxml.matchAll(/<(tab|section)\b([^>]*)>\s*<labels>([\s\S]*?)<\/labels>/g)) {+ const id = /\bid="([^"]+)"/.exec(m[2])[1];+ const texts = {};+ for (const l of m[3].matchAll(/<label description="([^"]*)" languagecode="(\d+)" \/>/g)) texts[Number(l[2])] = l[1];+ captions.push({ entity: h.entity, id, texts: { ...texts, ...(override[Object.keys(ids).find((name) => ids[name] === id)] || {}) } });+ }+ return exportAnswer(exportZip(workbookXml({ languages, captions })));+}+const EXPORT_URL = /\/api\/data\/v9\.\d\/solutions\/Microsoft\.Dynamics\.CRM\.ExportTranslation$/;++test('REAL BUNDLE: a form built in Spanish in an English organization, whose read shows English only, is VERIFIED from one translation export — after the build, with either flag, and with a spec pin', async () => {+ const { h, spec } = await publishedInSpanish();+ assert.deepStrictEqual(Object.keys(idsOf(h)), ['tab_main', 'sec_main'], 'the SDK gave the tab and the section the ids a translation export keys their captions by');+ h.store.exportTranslation = exportOfStoredForm(h);+ // The same form read as the store holds it: the baseline the export must neither add to nor take from.+ h.store.readLanguages = undefined;+ const whole = await verifyForms(h, spec, { languageCode: 3082 });+ assert.strictEqual(h.exportsAsked.length, 0, 'a read that carries Spanish needs no export');+ h.store.readLanguages = [1033];++ const logs = [];+ let handed;+ const built = await buildModelApp(spec, { apply: true, verify: true, env: 'https://contoso.crm.dynamics.com', languageCode: 3082, preResolvedLanguageCode: 3082 }, {+ log: (m) => logs.push(m),+ runBuild: async () => ({ ok: true, dryRun: false, created: {}, skipped: {} }),+ verify: async (s, options) => { handed = options; return verifyForms(h, s, options); },+ });+ assert.strictEqual(built.ok, true);+ assert.strictEqual(handed.languageCode, 3082);+ assert.deepStrictEqual(built.verify.missing, whole.missing.map(asBuildReports), 'the build\u2019s own verify finds what a read that shows Spanish finds, and no caption more');+ assert.strictEqual(built.verify.unverified, undefined, 'the Spanish captions are no longer left unverified');+ assert.doesNotMatch(logs.join('\n'), /could not be verified/);+ assert.strictEqual(h.exportsAsked.length, 1, 'one export for the two captions of the form');+ assert.match(h.exportsAsked[0].url, EXPORT_URL);+ assert.deepStrictEqual(h.exportsAsked[0].body, { SolutionName: 'FormProbe' });++ for (const [what, options, over] of [+ ['--language-code', { languageCode: readLanguageCodeFlag({ 'language-code': '3082' }) }, {}],+ ['--languageCode', { languageCode: readLanguageCodeFlag({ languageCode: '3082' }) }, {}],+ ['the language the build\u2019s SDK was made for', { preResolvedLanguageCode: 3082 }, {}],+ ['a languageCode the spec pins', undefined, { languageCode: 3082 }],+ ]) {+ h.exportsAsked.length = 0;+ const verification = await verifyForms(h, { ...spec, ...over }, options);+ assert.strictEqual(topology(verification).present, true, `${what}: ${topology(verification).detail}`);+ assert.deepStrictEqual(verification.missing, whole.missing, `${what}: the same failures the whole form has`);+ assert.strictEqual(verification.unverified, undefined, `${what}: settled by the export`);+ assert.strictEqual(h.exportsAsked.length, 1, what);+ }+});++test('REAL BUNDLE: a Spanish caption the export shows stale, or not at all, fails — the tab or the section by name, and the right one beside it passes', async () => {+ const { h, spec } = await publishedInSpanish();+ const opts = { languageCode: 3082 };+ h.store.exportTranslation = exportOfStoredForm(h, { override: { tab_main: { 3082: 'Antiguo' } } });+ const stale = await verifyForms(h, spec, opts);+ assert.strictEqual(topology(stale).present, false);+ assert.match(topology(stale).detail, /tab 'tab_main' is deployed with label "Antiguo" in language 3082 \(the translation export of solution 'FormProbe' shows it; the form read does not carry language 3082\), the spec declares label: "Resumen" in language 3082/);+ assert.doesNotMatch(topology(stale).detail, /section 'sec_main'/, 'the section\u2019s caption is right');+ assert.strictEqual(stale.unverified, undefined, 'the export settled both captions');+ h.store.exportTranslation = exportOfStoredForm(h, { override: { sec_main: { 3082: '' } } });+ const empty = await verifyForms(h, spec, opts);+ assert.strictEqual(topology(empty).present, false);+ assert.match(topology(empty).detail, /section 'sec_main' is deployed with no label in language 3082 \(the translation export of solution 'FormProbe' has none, only "Basics" in 1033; the form read does not carry language 3082\), the spec declares label: "Detalles" in language 3082/);+ assert.doesNotMatch(topology(empty).detail, /tab 'tab_main'/);+ // An export that has the language as a column and nothing in the cells says the same of every caption.+ h.store.exportTranslation = exportOfStoredForm(h, { override: { tab_main: { 3082: '' }, sec_main: { 3082: '' } } });+ assert.strictEqual((topology(await verifyForms(h, spec, opts)).detail.match(/is deployed with no label in language 3082/g) || []).length, 2);+});++test('REAL BUNDLE: an export that fails, or that cannot be read, leaves the Spanish captions unverified with the reason — it never passes them', async () => {+ const { h, spec } = await publishedInSpanish();+ const opts = { languageCode: 3082 };+ const baseline = await verifyForms(h, spec, opts);+ assert.strictEqual(baseline.unverified.length, 1, 'with no export to ask for, the captions are listed as they always were');+ assert.match(baseline.unverified[0], SPANISH_ENTRY);+ assert.strictEqual(h.exportsAsked.length, 0);+ for (const [what, answer, reason] of [+ ['a refusal', { status: 403, headers: {}, body: { error: { code: '0x80040220', message: 'Principal user is missing prvExportTranslation privilege' } } }, /could not be read \(HTTP 403: Principal user is missing prvExportTranslation privilege\)/],+ ['a server error', { status: 500, headers: {}, body: { error: { message: 'An unexpected error occurred' } } }, /could not be read \(HTTP 500: An unexpected error occurred\)/],+ ['an answer that is no export', { status: 200, headers: {}, body: { value: [] } }, /could not be read \(the answer holds no ExportTranslationFile\)/],+ ['bytes that are no zip', exportAnswer(Buffer.from('this is some text that goes on and on and is no zip archive at all')), /could not be read \(the archive of the export is not readable: the archive has no end-of-central-directory record\)/],+ ['an archive without the workbook', exportAnswer(zipOf([{ name: 'Other.xml', data: '<a/>' }])), /could not be read \(the archive of the export is not readable: the archive has no entry named 'CrmTranslations\.xml'\)/],+ ['a workbook that is not the platform\u2019s', exportAnswer(zipOf([{ name: 'CrmTranslations.xml', data: '<html>sign in</html>' }])), /could not be read \(the workbook of the export is not readable: it is not a spreadsheet workbook/],+ ]) {+ h.store.exportTranslation = answer;+ h.exportsAsked.length = 0;+ const res = await verifyForms(h, spec, opts);+ assert.strictEqual(topology(res).present, true, `${what}: nothing says a caption is wrong: ${topology(res).detail}`);+ assert.deepStrictEqual(res.missing, baseline.missing, `${what}: unverified is not a failure`);+ assert.strictEqual(res.ok, baseline.ok, what);+ assert.strictEqual(res.unverified.length, 1, `${what}: ${JSON.stringify(res.unverified)}`);+ assert.match(res.unverified[0], /^form-labels:new_ticket\.Main \(the labels of tab 'tab_main', section 'sec_main' in language 3082 were not compared: the environment's form read returns labels only in 1033, so labels written in 3082 cannot be read back from it\. A translation export of solution 'FormProbe' /, what);+ assert.match(res.unverified[0], reason, what);+ assert.strictEqual(h.exportsAsked.length, 1, `${what}: asked once`);+ }+});++test('REAL BUNDLE: an export without a row for the form, or with the language missing, leaves the captions unverified with what it lacks', async () => {+ const { h, spec } = await publishedInSpanish();+ const opts = { languageCode: 3082 };+ // No caption row for this form: the table has others (the export holds every form of the table), but not this form's.+ h.store.exportTranslation = exportAnswer(exportZip(workbookXml({ captions: [{ entity: h.entity, id: '0a0a0a0a-0000-4000-8000-0000000000ff', texts: { 1033: 'Another form\u2019s tab', 3082: 'La pesta\u00f1a de otro formulario' } }] })));+ const noRow = await verifyForms(h, spec, opts);+ assert.strictEqual(topology(noRow).present, true, topology(noRow).detail);+ assert.strictEqual(noRow.unverified.length, 1);+ assert.match(noRow.unverified[0], /A translation export of solution 'FormProbe' was read, but it cannot settle them: the export has no caption row for tab 'tab_main' \(id [0-9a-f-]{36}, table new_ticket\); the export has no caption row for section 'sec_main' \(id [0-9a-f-]{36}, table new_ticket\)\. Check them in Power Apps/);+ // An environment that has not provisioned Spanish has no column for it, and nothing in the export can say what the form holds in it.+ h.store.exportTranslation = exportOfStoredForm(h, { languages: [1033] });+ const noColumn = await verifyForms(h, spec, opts);+ assert.strictEqual(topology(noColumn).present, true, topology(noColumn).detail);+ assert.match(noColumn.unverified[0], /was read, but it cannot settle them: the export has no column for language 3082\. Check them/);+});++test('REAL BUNDLE: a form whose read carries the Spanish captions asks for no export at all — a wrong caption fails from the read, as before', async () => {+ const { h, spec } = await publishedInSpanish();+ h.store.exportTranslation = exportOfStoredForm(h);+ h.store.readLanguages = [1033, 3082];+ const right = await verifyForms(h, spec, { languageCode: 3082 });+ assert.strictEqual(topology(right).present, true, topology(right).detail);+ h.store.row.formxml = h.store.row.formxml.replace('<label description="Resumen" languagecode="3082" />', '<label description="Antiguo" languagecode="3082" />');+ const stale = await verifyForms(h, spec, { languageCode: 3082 });+ assert.strictEqual(topology(stale).present, false);+ assert.doesNotMatch(topology(stale).detail, /translation export/, 'a caption the read shows is judged by the read');+ assert.strictEqual(h.exportsAsked.length, 0);+});diff --git a/plugins/model-apps/scripts/tests/formxml-layers.test.js b/plugins/model-apps/scripts/tests/formxml-layers.test.jsindex d016f0ecb..9594e95b3 100644--- a/plugins/model-apps/scripts/tests/formxml-layers.test.js+++ b/plugins/model-apps/scripts/tests/formxml-layers.test.js@@ -1,10 +1,12 @@'use strict';// Tests of lib/formxml-layers.js: whether the SAVED FormXML of a systemform (a dashboard's, as verify reads it) is its PUBLISHED one when-// the two reads carry the labels of different languages. What verify does with the answer — the dashboard's tiles, read only when it is-// yes — is tested through the reader itself in verify-model-app.test.js.+// the two reads carry the labels of different languages — by the text of the two reads, and, when the platform's own version token says+// the saved layer is the published row, by the structure alone. What verify does with the answer — the dashboard's tiles, read only when+// it is yes — is tested through the reader itself in verify-model-app.test.js.const test = require('node:test');const assert = require('node:assert');const { sameFormXmlAcrossLayers } = require('../lib/formxml-layers.js');+const reads = require('./helpers/dashboard-two-language-reads.js');// A dashboard's FormXML in the shape the platform answers it: a tab and a section with a caption each, and cells whose captions are// in their <labels>, each followed by the tile's control. `extra` is more labels for that cell, after its 1033 caption.@@ -16,7 +18,7 @@ const form = (cells, tabExtra = '') => '<form><tabs><tab id="{t}" name="General"+ `<label description="" languagecode="1033" /></labels><rows><row>${cells.join('')}</row></rows></section></sections></column></columns></tab></tabs></form>`;const label = (lcid, text = 'Órdenes') => `<label description="${text}" languagecode="${lcid}" />`;const PUBLISHED = form([cell('By Priority'), cell('Open')]);-const same = (published, saved) => sameFormXmlAcrossLayers(published, saved);+const same = (published, saved, versions) => sameFormXmlAcrossLayers(published, saved, versions);test('sameFormXmlAcrossLayers: two equal texts are the same document, as they always were — nothing is parsed', () => {assert.strictEqual(same(PUBLISHED, PUBLISHED), true);@@ -126,3 +128,175 @@ test('sameFormXmlAcrossLayers: what is left is compared as text, byte for byte,// The text of a label set aside is not read at all: its description may hold anything an attribute may.assert.strictEqual(same(PUBLISHED, form([cell('By Priority', label(3082, 'a < b & "c" 😀')), cell('Open')])), true);});++// ── The same dashboard, read by a user whose own language is the organization's second one ──────────────────────────────────────+// What the platform answered live for each kind of user is in helpers/dashboard-two-language-reads.js. For the second-language user the+// published read carries both languages, the user's own first, and words one caption another way than the saved layer does, while the+// published row and the saved layer were at the very same version (`@odata.etag`) and nothing had written either: a read is the platform's+// projection for its reader, and no text can say which of two captions is "the" caption. The version can say that the saved layer IS the row.+const { BASE_LANGUAGE_USER: BASE_USER, SECOND_LANGUAGE_USER: SECOND_USER, ROW_VERSION, MOVED_VERSION } = reads;+const AT_ROW_VERSION = { published: ROW_VERSION, saved: ROW_VERSION };+const AFTER_A_SAVE = { published: ROW_VERSION, saved: MOVED_VERSION };+// The label groups of a read in document order: each <labels> as the list of `lcid:caption` it holds.+const groupsOf = (xml) => [...xml.matchAll(/<labels>(.*?)<\/labels>/g)]+ .map((group) => [...group[1].matchAll(/<label description="([^"]*)" languagecode="(\d+)" \/>/g)].map((l) => `${l[2]}:${l[1]}`));+const withoutLabels = (xml) => xml.replace(/<label\b[^>]*\/>/g, '');+const { cellOf, swapFirstTwoCells: swapCells } = reads;++test('the captured reads of one dashboard: the 3082 user\u2019s two layers differ in the order of two languages and in one caption\u2019s text — and in nothing else', () => {+ // Every caption taken out, the four reads are one document: the tiles are the same.+ for (const xml of [BASE_USER.published, BASE_USER.saved, SECOND_USER.published, SECOND_USER.saved]) assert.strictEqual(withoutLabels(xml), withoutLabels(BASE_USER.published));+ // The 1033 user, the case measured before: the saved read is the published one plus a 3082 caption in each of the four cells.+ assert.strictEqual(BASE_USER.saved.replace(/<label description="Work Orders" languagecode="3082" \/>/g, ''), BASE_USER.published);+ // The 3082 user: both languages in every cell of both layers (the tab and the section are in the user's language, empty).+ assert.deepStrictEqual(groupsOf(SECOND_USER.published), [['3082:'], ['3082:'], ['3082:Work Orders', '1033:By Priority'], ['3082:Work Orders', '1033:By Status'],+ ['3082:Work Orders', '1033:Critical Queue'], ['3082:Customers', '1033:Gold Customers']]);+ assert.deepStrictEqual(groupsOf(SECOND_USER.saved), [['3082:'], ['3082:'], ['1033:By Priority', '3082:Work Orders'], ['1033:By Status', '3082:Work Orders'],+ ['1033:Critical Queue', '3082:Work Orders'], ['1033:Gold Customers', '3082:Work Orders']]);+ // Put in one order, the cells' groups are the same but for the last cell's 3082 text.+ const sorted = (xml) => groupsOf(xml).map((group) => [...group].sort());+ assert.deepStrictEqual(sorted(SECOND_USER.published).slice(0, 5), sorted(SECOND_USER.saved).slice(0, 5));+ assert.deepStrictEqual([sorted(SECOND_USER.published)[5], sorted(SECOND_USER.saved)[5]], [['1033:Gold Customers', '3082:Customers'], ['1033:Gold Customers', '3082:Work Orders']]);+});++test('sameFormXmlAcrossLayers: a user whose own language is the second one reads the published dashboard in another order and with a caption worded another way — at the same row version it is the published dashboard', () => {+ const { published, saved } = SECOND_USER;+ // By the text alone it is not: both languages are carried, so none is set aside, and the reads differ in an order and in a caption.+ assert.strictEqual(same(published, saved), false);+ assert.strictEqual(same(published, saved, undefined), false);+ // The platform's own token says the saved layer has not been written since the publish: the two reads are one row, shown to its reader.+ assert.strictEqual(same(published, saved, AT_ROW_VERSION), true);+ // The 1033 user's reads are the same dashboard by the text, as before, at the same version or not.+ assert.strictEqual(same(BASE_USER.published, BASE_USER.saved), true);+ assert.strictEqual(same(BASE_USER.published, BASE_USER.saved, AT_ROW_VERSION), true);+});++test('sameFormXmlAcrossLayers: only two versions that are the same text excuse the captions — a version that moved, or is missing, blank or not text, excuses nothing', () => {+ const { published, saved } = SECOND_USER;+ for (const [what, versions] of [+ ['a saved layer whose version moved', AFTER_A_SAVE],+ ['a published row whose version is another', { published: MOVED_VERSION, saved: ROW_VERSION }],+ ['no versions', undefined],+ ['an empty object', {}],+ ['null', null],+ ['no published version', { saved: ROW_VERSION }],+ ['no saved version', { published: ROW_VERSION }],+ ['two empty versions', { published: '', saved: '' }],+ ['two versions that are numbers', { published: 1001, saved: 1001 }],+ ['two null versions', { published: null, saved: null }],+ // The token is opaque: a weak validator and the same number without its W/ are two tokens, not one.+ ['two spellings of one number', { published: 'W/"1001"', saved: '"1001"' }],+ ]) {+ assert.strictEqual(same(published, saved, versions), false, what);+ }+});++test('sameFormXmlAcrossLayers: at the same row version a tile, a cell, an element or an attribute that differs is still a difference — only the captions are excused', () => {+ const { published, saved } = SECOND_USER;+ const first = (xml, from, to) => { assert.ok(xml.includes(from), from); return xml.replace(from, to); };+ const extraCell = `<cell id="${reads.dashId(5)}" colspan="1" rowspan="1" showlabel="true"><labels>${reads.label(1033, 'By Region')}</labels></cell>`;+ for (const [what, other] of [+ ['a cell added', first(saved, '</row></rows>', `${extraCell}</row></rows>`)],+ ['a cell removed', saved.replace(cellOf(saved, 4), '')],+ ['two cells swapped', swapCells(saved)],+ ['a tile\u2019s view', first(saved, `<ViewId>${reads.VIEW_CRITICAL}</ViewId>`, `<ViewId>${reads.VIEW_GOLD}</ViewId>`)],+ ['a tile\u2019s table', first(saved, '<TargetEntityType>new_customer</TargetEntityType>', '<TargetEntityType>new_workorder</TargetEntityType>')],+ ['a tile\u2019s chart', first(saved, `<VisualizationId>${reads.CHART_STATUS}</VisualizationId>`, `<VisualizationId>${reads.CHART_PRIORITY}</VisualizationId>`)],+ ['an attribute changed', first(saved, 'columns="2"', 'columns="1"')],+ ['an attribute added', first(saved, 'name="General"', 'name="General" visible="false"')],+ ['an element added', first(saved, '</parameters>', '<RecordsPerPage>5</RecordsPerPage></parameters>')],+ ['a comment added', first(saved, '<rows>', '<!-- x --><rows>')],+ ['white space in a tag', first(saved, 'showlabel="true"><labels>', 'showlabel="true" ><labels>')],+ ['quote style', first(saved, 'name="General"', "name='General'")],+ ['the labels of a cell removed', saved.replace(/(<cell id="[^"]*" colspan="1" rowspan="1" showlabel="true">)<labels>.*?<\/labels>/, '$1')],+ ['a second labels element in a cell', first(saved, '</labels><control id', '</labels><labels></labels><control id')],+ ]) {+ assert.notStrictEqual(other, saved, what);+ assert.strictEqual(same(published, other, AT_ROW_VERSION), false, what);+ }+ // The same holds for the 1033 user's reads, whose text already said "the same": a structure that differs is a difference at any version.+ assert.strictEqual(same(BASE_USER.published, swapCells(BASE_USER.saved), AT_ROW_VERSION), false);+ // A caption the reader\u2019s projection could not have made — one that is no empty tag of a <labels>, or names no language — is no caption to excuse.+ for (const [what, tag] of [+ ['a caption with an end tag', '<label description="x" languagecode="3082"></label>'],+ ['a caption with no language', '<label description="x" />'],+ ['a caption whose language is no LCID', '<label description="x" languagecode="es-ES" />'],+ ]) {+ const other = first(saved, reads.label(3082, 'Work Orders'), tag);+ assert.strictEqual(same(published, other, AT_ROW_VERSION), false, what);+ }+});++test('sameFormXmlAcrossLayers: at the same row version what is excused is what the reads show of the captions, in any order — nothing the row says', () => {+ const { published, saved } = SECOND_USER;+ for (const [what, other] of [+ ['the order of the languages', saved],+ ['a 3082 caption worded another way', saved.replace('description="Work Orders" languagecode="3082"', 'description="Pedidos" languagecode="3082"')],+ ['a 3082 caption left out', saved.replace(reads.label(3082, 'Work Orders'), '')],+ ['a language the published read has none of', saved.replace(reads.label(3082, 'Work Orders'), reads.label(3082, 'Work Orders') + reads.label(1036, 'Ordres'))],+ ]) {+ assert.strictEqual(same(published, other, AT_ROW_VERSION), true, what);+ }+});++test('sameFormXmlAcrossLayers: a published read of one language is judged by the text alone, at any version — the token is for a read that carries more than one', () => {+ // The 1033 user's published read carries 1033 alone: whatever the two tokens say, a 1033 caption that differs is a change, as it always was,+ // and the result for that user is the text rule's, by construction.+ const { published, saved } = BASE_USER;+ for (const [what, other] of [+ ['a 1033 caption changed', saved.replace('description="By Priority"', 'description="By Owner"')],+ ['a 1033 caption removed', saved.replace(reads.label(1033, 'By Status'), '')],+ ['a 1033 caption added', saved.replace(reads.label(1033, 'By Status'), reads.label(1033, 'By Status') + reads.label(1033, 'Second'))],+ ]) {+ for (const [tokens, versions] of [['no tokens', undefined], ['the same token', AT_ROW_VERSION], ['another token', AFTER_A_SAVE]]) {+ assert.strictEqual(same(published, other, versions), false, `${what}, ${tokens}`);+ }+ }+ // A published read of one language that is not the base one is no different: the texts decide.+ const spanishOnly = SECOND_USER.published.replace(/<label description="[^"]*" languagecode="1033" \/>/g, '');+ assert.strictEqual(same(spanishOnly, SECOND_USER.saved, AT_ROW_VERSION), false);+ // The 1033 user's own reads, which the text rule already says are the same, are the same at any version.+ for (const versions of [undefined, AT_ROW_VERSION, AFTER_A_SAVE]) assert.strictEqual(same(published, saved, versions), true);+});++test('sameFormXmlAcrossLayers: after a write to the saved layer the reads are compared by their text, as before — a real change is found for either user', () => {+ // The 1033 user: a saved 3082 caption alone is still not seen (the limit documented since the second-language fix), anything else is.+ assert.strictEqual(same(BASE_USER.published, BASE_USER.saved, AFTER_A_SAVE), true);+ assert.strictEqual(same(BASE_USER.published, BASE_USER.saved.replace('description="Work Orders" languagecode="3082"', 'description="Pedidos" languagecode="3082"'), AFTER_A_SAVE), true);+ for (const [what, saved] of [+ ['a 1033 caption', BASE_USER.saved.replace('description="By Priority"', 'description="By Owner"')],+ ['a 1033 caption removed', BASE_USER.saved.replace(reads.label(1033, 'By Status'), '')],+ ['a tile moved', swapCells(BASE_USER.saved)],+ ['a tile\u2019s view', BASE_USER.saved.replace(`<ViewId>${reads.VIEW_CRITICAL}</ViewId>`, `<ViewId>${reads.VIEW_GOLD}</ViewId>`)],+ ]) {+ assert.strictEqual(same(BASE_USER.published, saved, AFTER_A_SAVE), false, `the 1033 user: ${what}`);+ }+ // The 3082 user: the saved layer was written, so the token excuses nothing and the two reads — which differ — are not the same text.+ // Whatever was saved (a tile, a 1033 caption, a 3082 caption), the dashboard is not the published one: it fails closed.+ for (const [what, saved] of [+ ['nothing that shows', SECOND_USER.saved],+ ['a 1033 caption', SECOND_USER.saved.replace('description="By Priority"', 'description="By Owner"')],+ ['a 3082 caption', SECOND_USER.saved.replace('description="Work Orders" languagecode="3082"', 'description="Pedidos" languagecode="3082"')],+ ['a tile moved', swapCells(SECOND_USER.saved)],+ ]) {+ assert.strictEqual(same(SECOND_USER.published, saved, AFTER_A_SAVE), false, `the 3082 user: ${what}`);+ }+});++test('sameFormXmlAcrossLayers: the version never makes a read that is not one well-formed XML document, or names no language, the published dashboard', () => {+ const { published, saved } = SECOND_USER;+ for (const [what, a, b] of [+ ['a saved read with a label left open', published, saved.replace('languagecode="3082" />', 'languagecode="3082">')],+ ['a saved read with a bare "&"', published, saved.replace('Work Orders', 'Work & Orders')],+ ['a saved read with a second root element', published, `${saved}<form/>`],+ ['a published read cut short', published.slice(0, -1), saved.slice(0, -1)],+ ['a published read that is no XML', 'not xml', saved],+ ['an empty saved read', published, ''],+ ['a published read that names no language', published.replace(/ languagecode="\d+"/g, ''), saved],+ ['a published read with no caption at all', withoutLabels(published), saved],+ ]) {+ assert.strictEqual(same(a, b, AT_ROW_VERSION), false, what);+ }+ // Two equal texts stay the same document at any version, as they always were.+ assert.strictEqual(same('not xml', 'not xml', AFTER_A_SAVE), true);+});diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.jsindex b9eb400e8..67658260f 100644--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js@@ -490,9 +490,12 @@ test('AGENTS.md says a page write whose outcome is not known is never sent againassert.match(agents, /an update's writes carry `If-Match: \*`, and `lib\/sdk-http-client\.js` re-sends a `\$batch` only when it is made of conditional deletes/);assert.match(agents, /The wait is the schedule that client gives every throttled request \(`throttleBackoffMs`: 1 s, 2 s, 4 s, 8 s, 8 s, plus jitter\) or the answer's `Retry-After` when that asks for longer, \*\*waited whole\*\*/);assert.match(agents, /inside \*\*one budget of five minutes for the waiting a throttled page write costs a build run\*\*/);- // What the budget bounds, and what it does not: the waiting the build's OWN layers add — and not the HTTP client's own re-sends of a throttled read or publish, which keep the schedule they always had.- assert.match(agents, /\*\*The budget bounds the waiting the build's OWN layers add — the page backend's resends of a page's `\$batch`, which the HTTP client never re-sends, and the build's phase restarts — and not all the waiting a run does\.\*\*/);- assert.match(agents, /The production HTTP client keeps its own schedule for the requests it re-sends — a read, a publish, a delete, a column create: at most five re-sends, each waiting 1, 2, 4, 8 and 8 s or the answer's `Retry-After` when that asks for longer, up to a minute — exactly as it did before the budget existed, and none of it is drawn from the budget: charging it would halt a throttled build that succeeds today\./);+ // What the budget bounds: all the waiting a run does for a throttle — the HTTP client's own waits too, when it is given the budget — and not the waits that are not for a throttle, which keep the schedule they always had.+ assert.match(agents, /\*\*The budget bounds all the waiting a run does for a throttle — the HTTP client's waits as well as the backend's and the build's\.\*\*/);+ assert.match(agents, /A wait that does not fit is \*\*not taken\*\*: the throttled answer comes back as it came — the SDK reports the 429 it is, a refusal that started nothing, and not a failure of the transport, which it would treat as an unknown outcome — and the client tells the budget what the service asked \(`decline`; the SDK's error holds no headers\), which the build's retry loop reads: the build stops with `throttle-budget-exhausted`, saying what the service asked, on the last run as on the first, and does not run the phases again to meet the same answer\./);+ assert.match(agents, /What is not throttling keeps its own schedule and is not drawn from the budget — a 5xx \(a customization lock or a SQL deadlock victim is a 500, a gateway's hiccup a 502, 503 or 504\) whatever `Retry-After` it carries, a reset connection, the re-send of a deadlock victim — and so does a client that is given no budget/);+ // What the engine's guard lets through: the name column's length a run owes, which no later run can set — in the pass that completes the phase as in the settlement of a halt.+ assert.match(agents, /what pays what the run owes is let through \(`settling`: the name column's length of a table the run created, which no later run can set — a run that finds the table leaves its name column as it is, so a stop would leave the table at the platform's default for good — and which is therefore paid in the settlement of a halted data-model phase and in the pass that completes one, where the refusal of one table's update does not keep the next table's from being set/);assert.match(agents, /a resumed create that brings an earlier payload up to date hands the same budget — the one it was given, or the one it made for itself — on to the update it makes/);assert.match(agents, /which reads an answer only when it is complete and well-formed — its outer boundary closes, every change set in it closes, and every part is a complete response whose first line is a status line — and takes ANYTHING missing or malformed/);assert.match(agents, /takes ANYTHING missing or malformed \(a part with no response in it, a part with no status line or one cut off, a change set that is never closed, one that is declared and never opened, one whose delimiters are not the boundary it declares, a body shorter or longer than the `Content-Length` its response gives, a part that declares a `Transfer-Encoding`\) as proving nothing/);diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.jsindex 1f56b286e..298bdde91 100644--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js@@ -2199,6 +2199,84 @@ test('REAL SDK: a throttle that asks for longer than the budget stops the uploadassert.strictEqual(fs.existsSync(markerPath(file)), false, 'and no base is recorded for a page that was not written');});+// The page server as the transport under the production HTTP client — the one that decides whether a wait fits — with the requests `refuse` answers refused instead.+function serverTransport(server, refuse = () => undefined) {+ const raw = server.http();+ return async ({ url, method, headers, body }) => {+ const refused = refuse(method, new URL(url).pathname);+ if (refused) return refused;+ const answer = method === 'POST' && url.endsWith('/$batch') ? await raw.postRaw(url, body, { headers })+ : method === 'GET' ? await raw.get(url, { headers })+ : method === 'DELETE' ? await raw.delete(url, { headers })+ : method === 'PATCH' && Buffer.isBuffer(body) ? await raw.patchRaw(url, body, { headers })+ : await raw[method.toLowerCase()](url, typeof body === 'string' ? JSON.parse(body) : body, { headers });+ const text = typeof answer.body === 'string' || Buffer.isBuffer(answer.body) ? answer.body : JSON.stringify(answer.body === undefined ? null : answer.body);+ return { statusCode: answer.status, headers: answer.headers || {}, body: text };+ };+}++// A publish the budget has no room to wait for comes AFTER the create has committed, so a run of the same command again would create a second page. The HTTP client's line on stderr is the fact alone — what the service asked, and that the+// request was not sent again — and the way to finish is the result's: the same command with the page that was saved named. These run it as a caller would, against the service once it answers.+test('REAL SDK: a publish the budget has no room to wait for is said on stderr with no advice — the result names the page that was saved, and its advice, run as given, finishes that page and makes no second', async (t) => {+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const server = serverWithAccount();+ let throttled = true;+ const slept = [];+ const written = [];+ t.mock.method(process.stderr, 'write', (chunk) => { written.push(String(chunk)); return true; });+ const refusePublish = (method, requestPath) => {+ if (!(throttled && method === 'POST' && /\/PublishXml$/.test(requestPath))) return undefined;+ throttled = false;+ return { statusCode: 429, headers: { 'retry-after': '600' }, body: '{"error":{"message":"throttled"}}' };+ };+ const backend = (env, fromScript = {}) => {+ const httpClient = createAzHttpClient(env, {+ getToken: () => 'TOK', random: () => 0, throttle: fromScript.throttle, sleep: async (ms) => { slept.push(ms); }, request: serverTransport(server, refusePublish),+ });+ return realBackend(server, { deps: { httpClient, random: () => 0 } })(env, fromScript);+ };+ const file = codeFile(SOURCE);+ const args = ['--env', INSTANCE, '--code-file', file, '--name', 'Throttled publish', ...P, '--agent-message', 'm'];+ const first = await run(args, backend);+ assert.strictEqual(first.ok, false, JSON.stringify(first.payload));+ const id = first.payload.pageId;+ assert.deepStrictEqual(slept, [], 'nothing was waited for: ten minutes do not fit in five');+ assert.deepStrictEqual(written.filter((line) => /^WARNING: /.test(line)), [+ 'WARNING: the service asked to wait 600 s before this request is sent again, which does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service (0 s are spent), so it was not sent again.\n',+ ]);+ assert.doesNotMatch(written.join(''), /same command|again later|Nothing more is sent now/, 'stderr says nothing of what to run: the create has committed');+ assert.deepStrictEqual([...server.state.projects.keys()], [id], 'the page was created');+ assert.deepStrictEqual(server.published, [], 'and not published');+ assert.strictEqual(readMarker(file).unfinished, 'publish');+ const advised = /run the same command again with --page-id (\S+) added and nothing else changed/.exec(first.payload.error);+ assert.ok(advised, first.payload.error);+ assert.strictEqual(advised[1], id, 'the advice names the page that was saved');++ const second = await run([...args, '--page-id', advised[1]], backend);+ assert.strictEqual(second.ok, true, JSON.stringify(second.payload));+ assert.deepStrictEqual([second.payload.pageId, second.payload.unchanged], [id, true]);+ assert.deepStrictEqual([...server.state.projects.keys()], [id], 'one page, the one the first run made');+ assert.deepStrictEqual(server.published, [id], 'and it is published now');+ assert.strictEqual(readMarker(file).unfinished, undefined);+});++// The upload is a run of one write, and the budget that bounds its waiting is one object: the write's resends and the backend's own HTTP client — whose reads and publish wait out a throttle too — draw from the same five minutes, so the+// script hands its backend the budget, with the seam that writes its long waits on stderr as WARNING lines.+test('REAL SDK: the upload hands its backend ONE budget, whose long waits are WARNING lines on stderr — the write and the backend\'s own HTTP client draw from it', async (t) => {+ const server = serverWithAccount();+ const handed = [];+ const written = [];+ t.mock.method(process.stderr, 'write', (chunk) => { written.push(String(chunk)); return true; });+ const backend = realBackend(server);+ const r = await run(['--env', INSTANCE, '--code-file', codeFile(SOURCE), '--name', 'Budgeted page', ...P, '--agent-message', 'm'], (env, fromScript = {}) => { handed.push(fromScript); return backend(env, fromScript); });+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));+ assert.strictEqual(handed.length, 1, 'one backend');+ const { throttle } = handed[0];+ assert.ok(throttle && ['fits', 'spend', 'announce', 'decline', 'declined', 'note'].every((name) => typeof throttle[name] === 'function'), 'with a budget');+ throttle.announce('a long wait', 60000);+ assert.deepStrictEqual(written.filter((line) => /a long wait/.test(line)), ['WARNING: a long wait\n'], 'whose announcements are the WARNING lines the script writes');+});+// The page is normalized once: a file that starts with TWO byte order marks loses the encoding marker only, in the check, the hash and the page.test('REAL SDK: a file that starts with two byte order marks is checked, hashed and stored as the same text — one mark is the encoding, the other is content', async () => {const server = serverWithAccount();diff --git a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js b/plugins/model-apps/scripts/tests/halt-retry-policy.test.jsindex 20fd8eea3..2d3fe2440 100644--- a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js+++ b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js@@ -68,6 +68,8 @@ const POLICY = {'pages-removed': { kinds: ['never'], via: 'sdk-build.test.js' },'pages-requires-app': { kinds: ['never'], via: PAGES },'pages-existence-failed': { kinds: ['by-failure'], via: PAGES },+ // The read of a page a pending create left behind, throttled until the run's budget had no room to wait for it: a run again may find the service ready (the build's loop turns it into the budget's halt).+ 'pages-read-throttled': { kinds: ['by-failure'], via: PAGES },'pages-manifest-corrupt': { kinds: ['never'], via: 'sdk-build.test.js' },'pages-identity-conflict': { kinds: ['never'], via: PAGES },'pages-creation-receipt-failed': { kinds: ['never'], via: PAGES },@@ -90,7 +92,8 @@ const POLICY = {'role-grant-failed': { kinds: ['by-failure'] },'bpf-role-unresolved': { kinds: ['never'] },'bpf-role-grant-failed': { kinds: ['by-failure'] },- // The build's own loop stops with it when the next wait a throttle costs does not fit the run's budget (build-model-app.js); held beside the loop's doubles.+ // The build's own loop stops with it when the next wait a throttle costs does not fit the run's budget (build-model-app.js), and the engine's runner when a step would start after the budget refused a wait (entity-provision.js,+ // makeRunner; throttle-engine-stop.test.js): held beside the loop's doubles.'throttle-budget-exhausted': { kinds: ['by-failure'], via: 'build-model-app.test.js' },};// The sites whose code is an expression, on purpose: the code is decided at run time, so the policy cannot be read off a literal.diff --git a/plugins/model-apps/scripts/tests/helpers/app-access-specs.js b/plugins/model-apps/scripts/tests/helpers/app-access-specs.jsnew file mode 100644index 000000000..345d9e519--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/app-access-specs.js@@ -0,0 +1,80 @@+'use strict';+// App Specs shaped like the two the access checks have to tell apart: a downloaded app extended with one new table (what a maker writes to+// add a table to an app whose security roles somebody else owns), and a spec for an app that does not exist yet.+//+// `personas[]` is left out of the extension ON PURPOSE. A persona's role is converged to exactly the privileges the spec declares (and a role+// the build did not author is refused), so naming an existing role there is the opposite of leaving it alone; an additive grant is planned+// with `roleGrants[]`.++const column = (schemaName, displayName) => ({ schemaName, displayName });++// A table the spec introduces (no `existing`).+const newTable = (schemaName, displayName) => ({+ schemaName,+ displayName,+ primaryAttribute: column(`${schemaName.split('_')[0]}_name`, 'Name'),+ columns: [],+});++// A table the app already holds: a download marks every one it recovers `existing: true`.+const existingTable = (schemaName, displayName) => ({ ...newTable(schemaName, displayName), existing: true });++const navigationTo = (...tables) => ({+ areas: [{ label: 'Work', groups: [{ label: 'Records', subAreas: tables.map((t) => ({ title: t, entity: t })) }] }],+});++// A downloaded app, one new table added. It carries what a download writes: the app's own unique name, and the table it recovered marked existing.+function extensionSpec({ newTables = ['contoso_baseline'] } = {}) {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoPm', publisherPrefix: 'contoso' },+ app: { name: 'Contoso PM', uniqueName: 'contoso_pm' },+ entities: [existingTable('contoso_project', 'Project'), ...newTables.map((t) => newTable(t, t))],+ appShell: navigationTo('contoso_project', ...newTables),+ pages: [],+ views: [],+ forms: [],+ charts: [],+ };+}++// A spec for an app that does not exist yet: nothing in it says otherwise (no unique name, no deployed ids, every table new).+function newAppSpec({ tables = ['contoso_ticket'] } = {}) {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoSupport', publisherPrefix: 'contoso' },+ app: { name: 'Contoso Support' },+ entities: tables.map((t) => newTable(t, t)),+ appShell: navigationTo(...tables),+ pages: [],+ views: [],+ forms: [],+ charts: [],+ };+}++// `roleGrants[]` entry: add privileges on `table` to the existing role `role` (a display name, or a GUID when it looks like one).+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+function grant(role, table, access = ['read'], scope = 'organization') {+ return { ...(GUID.test(role) ? { roleId: role } : { role }), privileges: [{ entity: table, access, scope }] };+}++// A persona whose one job declares `privileges`.+function persona(name, privileges, extra = {}) {+ return { persona: name, jobs: [{ name: `${name} work`, privileges, surfaces: ['Records'] }], ...extra };+}++// What a read of the environment answers for an app that has these roles associated: the shape lib/app-roles.js returns. A role is a name, or+// `{ name, roleId, managed }` when a test needs two roles of one name, or a role of a chosen id.+function appWithRoles(...roles) {+ return {+ state: 'read',+ appUnique: 'contoso_pm',+ roles: roles.map((role, i) => {+ const row = typeof role === 'string' ? { name: role } : role;+ return { roleId: row.roleId || `00000000-0000-4000-8000-00000000000${i + 1}`, name: row.name, managed: row.managed === true };+ }),+ };+}++module.exports = { extensionSpec, newAppSpec, grant, persona, appWithRoles, newTable, existingTable };diff --git a/plugins/model-apps/scripts/tests/helpers/bpf-batch-service.js b/plugins/model-apps/scripts/tests/helpers/bpf-batch-service.jsnew file mode 100644index 000000000..883781840--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/bpf-batch-service.js@@ -0,0 +1,116 @@+'use strict';+// A business process flow whose edit is written in ONE `$batch` change set, over a fake service — for the tests that drive the REAL vendored SDK and the production az-token HTTP client through a change set the+// service refuses as a whole (HTTP 200, with the one part that failed). Shared by the test file and by the child process of helpers/token-boundary-child.js, which is why it requires no test runner.+const assert = require('node:assert');+const { createNodeWorkspaceStorage } = require('../../lib/maker-sdk.js');+const { bpfDef, inspectBpfStages, applyBpfStages } = require('../../lib/sdk-build.js');+const { createAzHttpClient } = require('../../lib/sdk-http-client.js');+const { INSTANCE } = require('./fake-genpage-server.js');+const { TOKEN, NL } = require('./synthetic-token.js');++// The production client over a fake service that speaks the SDK's HttpClient (`http`). `seen` is given every `$batch` answer as the transport handed it over; `rewrite` may change a `$batch` answer first; `token` is the+// access token the client sends (the synthetic one unless a test names another).+function productionClient(http, { rewrite = (text) => text, seen = [], token = TOKEN } = {}) {+ return createAzHttpClient(INSTANCE, {+ getToken: () => token, sleep: async () => {}, random: () => 0,+ request: async ({ url, method, headers, body }) => {+ const batch = method === 'POST' && url.endsWith('/$batch');+ const answer = batch ? await http.postRaw(url, body, { headers })+ : method === 'GET' ? await http.get(url, { headers })+ : method === 'DELETE' ? await http.delete(url, { headers })+ : method === 'PATCH' && Buffer.isBuffer(body) ? await http.patchRaw(url, body, { headers })+ : await http[method.toLowerCase()](url, typeof body === 'string' ? JSON.parse(body) : body, { headers });+ const text = typeof answer.body === 'string' || Buffer.isBuffer(answer.body) ? answer.body : JSON.stringify(answer.body === undefined ? null : answer.body);+ const sent = batch ? rewrite(text) : text;+ if (batch) seen.push(sent);+ return { statusCode: answer.status, headers: answer.headers || {}, body: sent };+ },+ });+}++// A fake of the flow's row: a create stores the row, a GET serves it, a PATCH merges into it and moves its version, and a `$batch` change set applies its PATCHes in order — or, when `state.refuse` is set, is refused as+// a whole: HTTP 200 with the one part that failed, which says why (`state.refusal`) and counts its own bytes. `state.echo` makes a part that succeeds repeat the token.+const stage = (name, ...steps) => ({ name, steps: steps.map((s) => { const [stepName, field] = s.split(':'); return { name: stepName, field }; }) });+const flowOf = (stages) => ({ name: 'Ticket Handling', entity: 'new_ticket', stages });+const DEPLOYED = () => flowOf([stage('Triage', 'Subject:new_subject', 'Priority:new_priority'), stage('Resolve', 'Notes:new_notes'), stage('Close', 'Status:new_status')]);++function workflowsService(state) {+ const rows = new Map();+ const bump = (row) => { row['@odata.etag'] = `W/"${Number(/\d+/.exec(row['@odata.etag'])[0]) + 1}"`; };+ const rowOf = (url) => rows.get(/workflows\(([^)]+)\)/i.exec(String(url))[1].replace(/'/g, ''));+ return {+ get: async (url) => {+ if (!/\/workflows\(/i.test(String(url))) return { status: 200, headers: {}, body: { value: [] } };+ const row = rowOf(url);+ return row ? { status: 200, headers: { etag: row['@odata.etag'] }, body: { ...row } } : { status: 404, headers: {}, body: { error: { message: 'not found' } } };+ },+ post: async (url, body) => {+ rows.set(body.workflowid, { ...body, statecode: 0, statuscode: 1, '@odata.etag': 'W/"1"' });+ return { status: 201, headers: { 'odata-entityid': `${INSTANCE}/api/data/v9.2/workflows(${body.workflowid})` }, body: { workflowid: body.workflowid, '@odata.etag': 'W/"1"' } };+ },+ patch: async (url, body) => {+ const row = rowOf(url);+ Object.assign(row, body);+ bump(row);+ return { status: 200, headers: { etag: row['@odata.etag'] }, body: { '@odata.etag': row['@odata.etag'] } };+ },+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ postRaw: async (url, body) => {+ if (state.refuse) {+ const text = state.refusal;+ const part = ['--changesetresponse_x', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', 'Content-ID: 1', '', 'HTTP/1.1 403 Forbidden', `Content-Type: ${text.startsWith('{') ? 'application/json' : 'text/plain'}`, `Content-Length: ${Buffer.byteLength(text)}`, '', text];+ return { status: 200, headers: {}, body: ['--batchresponse_x', 'Content-Type: multipart/mixed; boundary=changesetresponse_x', '', ...part, '--changesetresponse_x--', '--batchresponse_x--', ''].join(NL) };+ }+ const lines = ['--batchresponse_x', 'Content-Type: multipart/mixed; boundary=changesetresponse_x', ''];+ for (const part of String(body).split(/^--changeset_\S*/m).slice(1).filter((p) => /Content-ID/i.test(p))) {+ const target = /^(?:PATCH|POST|DELETE|GET) (\S+) HTTP/m.exec(part)[1];+ const json = part.slice(part.indexOf('{'), part.lastIndexOf('}') + 1);+ const row = rowOf(target);+ Object.assign(row, json ? JSON.parse(json) : {});+ bump(row);+ const representation = /^Prefer:\s*.*representation/im.test(part);+ lines.push('--changesetresponse_x', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${/Content-ID:\s*(\S+)/i.exec(part)[1]}`, '',+ representation ? 'HTTP/1.1 200 OK' : 'HTTP/1.1 204 No Content', `ETag: ${row['@odata.etag']}`, ...(representation ? ['Content-Type: application/json', '', JSON.stringify({ '@odata.etag': row['@odata.etag'], ...(state.echo ? { echoed: TOKEN } : {}) })] : ['']), '');+ }+ lines.push('--changesetresponse_x--', '--batchresponse_x--', '');+ return { status: 200, headers: { 'content-type': 'multipart/mixed; boundary=batchresponse_x' }, body: lines.join(NL) };+ },+ };+}++// A flow that exists, and an SDK over a workspace that has never seen it, asked to rename a stage: what a rebuild does. `makeSdk` is the factory the SDK is made with, `makeDir` makes a workspace folder, and `state` is the fake+// service's (`refuse`, `refusal`, `echo`). `seen` is every `$batch` answer as the service sent it, `given` every one the SDK was handed. `token` is the access token the client sends.+async function flowEdit(state, makeSdk, makeDir, { token = TOKEN } = {}) {+ const seen = [];+ const client = productionClient(workflowsService(state), { seen, token });+ const given = [];+ const watched = { ...client, postRaw: async (...args) => { const answer = await client.postRaw(...args); given.push(answer.body); return answer; } };+ const open = async () => {+ const sdk = makeSdk({ workspaceStorage: createNodeWorkspaceStorage(makeDir()), instanceUrl: INSTANCE, httpClient: watched });+ await sdk.initWorkspace();+ return sdk;+ };+ const creator = await open();+ const created = await creator.createArtifact('bpf', bpfDef({ ...DEPLOYED(), status: 'Active' }));+ await creator.pushArtifact('bpf', created.id);+ const sdk = await open();+ const deployed = DEPLOYED();+ const want = flowOf([{ ...deployed.stages[0], name: 'Intake' }, deployed.stages[1], deployed.stages[2]]);+ const inspected = await inspectBpfStages(sdk, want, created.id);+ assert.strictEqual(inspected.kind, 'edit', 'the flow has an edit to apply');+ seen.length = 0;+ given.length = 0;+ return { apply: () => applyBpfStages(sdk, want, created.id, inspected.plan, {}), seen, given };+}++// The edit, refused as a whole by a part whose body is `refusal`: the error the SDK raises, and the answers the transport sent and the SDK was handed.+async function refusedEdit(refusal, makeSdk, makeDir, options) {+ const state = { refuse: false, refusal };+ const { apply, seen, given } = await flowEdit(state, makeSdk, makeDir, options);+ state.refuse = true;+ const error = await apply().then(() => null, (e) => e);+ return { error, seen, given };+}++module.exports = { productionClient, workflowsService, flowEdit, refusedEdit, stage, flowOf, DEPLOYED };diff --git a/plugins/model-apps/scripts/tests/helpers/dashboard-two-language-reads.js b/plugins/model-apps/scripts/tests/helpers/dashboard-two-language-reads.jsnew file mode 100644index 000000000..224871f07--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/dashboard-two-language-reads.js@@ -0,0 +1,68 @@+'use strict';+// ONE dashboard, as the platform answered it live in an organization whose base language is English (1033) and which has Spanish+// (3082) provisioned too — the FormXML of its published row (a plain read) and of its saved layer (RetrieveUnpublished), once for a+// user whose own UI language is 1033 and once for a user whose own UI language is 3082. The dashboard had not been written since its+// build published it, and it has one tab, one section and four tiles (two charts and two lists). Ids, tables and names are replaced+// by placeholders; the label groups, which are what the reads differ in, are exactly as read. The one cell this module spells out+// four times, the fourth (a list of customers), read:+// 1033 user, published <labels><label description="Gold Customers" languagecode="1033" /></labels>+// 1033 user, saved <labels><label description="Gold Customers" languagecode="1033" /><label description="Work Orders" languagecode="3082" /></labels>+// 3082 user, published <labels><label description="Customers" languagecode="3082" /><label description="Gold Customers" languagecode="1033" /></labels>+// 3082 user, saved <labels><label description="Gold Customers" languagecode="1033" /><label description="Work Orders" languagecode="3082" /></labels>+// and on both layers, whoever read them, `@odata.etag` was the same token: the published row's and the saved layer's.+//+// A write to the saved layer moves its token and not the published row's; a publish moves both to the same new one. The tests+// that need "the dashboard as the platform's own token says it was published" give both reads `ROW_VERSION`, and "a draft saved+// after the publish" `MOVED_VERSION` for the saved read.+const ROW_VERSION = 'W/"1001"';+const MOVED_VERSION = 'W/"1002"';++const dashId = (n) => `{aaaaaaaa-0000-4000-8000-${String(n).padStart(12, '0')}}`;+const label = (lcid, text) => `<label description="${text}" languagecode="${lcid}" />`;+const TILE_CLASS = '{E7A81278-8635-4D9E-8D4D-59480B391C5B}';+const VIEW_OPEN = '11111111-0000-4000-8000-000000000001';+const VIEW_CRITICAL = '11111111-0000-4000-8000-000000000002';+const VIEW_GOLD = '11111111-0000-4000-8000-000000000003';+const CHART_PRIORITY = '22222222-0000-4000-8000-000000000001';+const CHART_STATUS = '22222222-0000-4000-8000-000000000002';++const chartTile = (n, table, view, chart) => `<control id="${dashId(n + 100)}" classid="${TILE_CLASS}"><parameters><TargetEntityType>${table}</TargetEntityType>`+ + `<ViewId>${view}</ViewId><VisualizationId>${chart}</VisualizationId><ChartGridMode>Chart</ChartGridMode></parameters></control>`;+const listTile = (n, table, view) => `<control id="${dashId(n + 100)}" classid="${TILE_CLASS}"><parameters><TargetEntityType>${table}</TargetEntityType>`+ + `<ViewId>${view}</ViewId><IsUserView>false</IsUserView><ChartGridMode>Grid</ChartGridMode><RecordsPerPage>10</RecordsPerPage></parameters></control>`;+const cell = (n, labels, tile) => `<cell id="${dashId(n)}" colspan="1" rowspan="1" showlabel="true"><labels>${labels}</labels>${tile}</cell>`;+// The text of cell `n` (1 to 4) in a read of the dashboard, and the same read with its first two cells, the two chart tiles, in the other order.+const cellOf = (xml, n) => { const found = new RegExp(`<cell id="${dashId(n)}".*?</cell>`).exec(xml); if (!found) throw new Error(`no cell ${n}`); return found[0]; };+const swapFirstTwoCells = (xml) => xml.replace(cellOf(xml, 1), '\u0000').replace(cellOf(xml, 2), cellOf(xml, 1)).replace('\u0000', cellOf(xml, 2));++// A read of the dashboard: the label groups (the XML inside each <labels>) of its tab, its section and its four cells, in that order.+function dashboardRead({ tab, section, cells }) {+ return `<form><tabs><tab id="${dashId(90)}" name="General" showlabel="true" expanded="true" verticallayout="true"><labels>${tab}</labels>`+ + `<columns><column width="100%"><sections><section id="${dashId(91)}" name="Section 1" showlabel="false" columns="2"><labels>${section}</labels><rows>`+ + `<row>${cell(1, cells[0], chartTile(1, 'new_workorder', VIEW_OPEN, CHART_PRIORITY))}${cell(2, cells[1], chartTile(2, 'new_workorder', VIEW_OPEN, CHART_STATUS))}</row>`+ + `<row>${cell(3, cells[2], listTile(3, 'new_workorder', VIEW_CRITICAL))}${cell(4, cells[3], listTile(4, 'new_customer', VIEW_GOLD))}</row>`+ + '</rows></section></sections></column></columns></tab></tabs></form>';+}++const CAPTIONS = ['By Priority', 'By Status', 'Critical Queue', 'Gold Customers'];+// The saved layer holds a 3082 caption in each cell, "Work Orders" in all four (the platform made them: the SDK writes one caption per cell,+// in the base language). The published read of the 3082 user words the last one as the name of its table, "Customers".+const SAVED_3082 = ['Work Orders', 'Work Orders', 'Work Orders', 'Work Orders'];+const PUBLISHED_3082 = ['Work Orders', 'Work Orders', 'Work Orders', 'Customers'];++// The user whose own language is the organization's base one: the published read carries 1033 alone, the saved read both languages.+const BASE_LANGUAGE_USER = {+ published: dashboardRead({ tab: label(1033, ''), section: label(1033, ''), cells: CAPTIONS.map((caption) => label(1033, caption)) }),+ saved: dashboardRead({ tab: label(1033, ''), section: label(1033, ''), cells: CAPTIONS.map((caption, i) => label(1033, caption) + label(3082, SAVED_3082[i])) }),+};+// The user whose own language is the second one: the published read carries both languages, the user's own first, and the empty captions of+// the tab and the section are in the user's language on both layers; the saved read is in the stored order, base language first.+const SECOND_LANGUAGE_USER = {+ published: dashboardRead({ tab: label(3082, ''), section: label(3082, ''), cells: CAPTIONS.map((caption, i) => label(3082, PUBLISHED_3082[i]) + label(1033, caption)) }),+ saved: dashboardRead({ tab: label(3082, ''), section: label(3082, ''), cells: CAPTIONS.map((caption, i) => label(1033, caption) + label(3082, SAVED_3082[i])) }),+};++module.exports = {+ BASE_LANGUAGE_USER, SECOND_LANGUAGE_USER, ROW_VERSION, MOVED_VERSION, dashboardRead, label, dashId, cellOf, swapFirstTwoCells,+ VIEW_OPEN, VIEW_CRITICAL, VIEW_GOLD, CHART_PRIORITY, CHART_STATUS,+};diff --git a/plugins/model-apps/scripts/tests/helpers/exit-output-child.js b/plugins/model-apps/scripts/tests/helpers/exit-output-child.jsnew file mode 100644index 000000000..78b76f4ef--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/exit-output-child.js@@ -0,0 +1,41 @@+'use strict';+// A REAL PROCESS that prints a result the way every script does — `emitResult`, which exits right after its writes — for tests/result-whole-before-exit.test.js:+// node [--require ./queued-stdio-preload.js] exit-output-child.js <scenario> [<json parameters>]+// `rows` sets the size: 30,000 rows make a text of about 3.5 MB, far more than a pipe holds at once (64 KiB on Linux); 2 rows make one a pipe takes at once. The texts are built by the functions exported here, so the test+// computes the bytes it expects from the same parameters. Only the plugin's own code prints: `emitResult` and, for `fatal`, the output guard's printer of an error that ends the process (lib/output-redaction.js). It+// requires no test runner: a test runner prints its own report on stdout when the process ends.+const { emitResult, getAuthToken } = require('../../lib/dataverse-auth.js');+const { TOKEN } = require('./synthetic-token.js');++const NOTE = 'The platform answered with a diagnostic that says nothing about credentials.';+// A table of `rows` rows, as a listing or a download summary prints one. `accent` puts characters above U+007E into every row, for the `ascii` option.+const table = (rows, accent = '') => Array.from({ length: rows }, (_, i) => ({ id: i, name: `row ${i}${accent}`, note: NOTE }));+// A text of about the same size, as an error that quotes a service's answer is.+const longText = (rows) => Array.from({ length: rows }, (_, i) => `line ${i}: ${NOTE}`).join(' ');+const ACCENT = ' \u2014 caf\u00e9';++const scenarios = {+ ok: ({ rows }) => emitResult(true, table(rows)),+ ascii: ({ rows }) => emitResult(true, table(rows, ACCENT), { ascii: true }),+ 'structured-error': ({ rows }) => emitResult(false, { ok: false, error: longText(rows), rows: table(rows) }),+ 'structured-errors': ({ rows }) => emitResult(false, { ok: false, errors: table(rows) }),+ 'structured-unexplained': ({ rows }) => emitResult(false, { ok: false, rows: table(rows) }),+ error: ({ rows }) => emitResult(false, new Error(longText(rows))),+ text: ({ rows }) => emitResult(false, longText(rows)),+ // A token obtained the way a script obtains one (which puts the output guard on the process), then an error nothing catches whose message quotes an answer — and the token: the guard prints it, cleaned, and exits with 1.+ fatal: ({ rows }) => {+ if (getAuthToken('https://contoso.crm.dynamics.com', { exec: () => `${TOKEN}\n` }) !== TOKEN) throw new Error('the token was not obtained');+ setTimeout(() => { throw new Error(`${longText(rows)} Rejected bearer ${TOKEN}`); }, 0);+ },+};++if (require.main === module) {+ const [, , name, parameters] = process.argv;+ if (!scenarios[name]) {+ process.stderr.write(`unknown scenario ${name}\n`);+ process.exit(2);+ }+ scenarios[name](parameters ? JSON.parse(parameters) : {});+}++module.exports = { table, longText, ACCENT };diff --git a/plugins/model-apps/scripts/tests/helpers/fake-auth-check-preload.js b/plugins/model-apps/scripts/tests/helpers/fake-auth-check-preload.jsnew file mode 100644index 000000000..14e7851d8--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/fake-auth-check-preload.js@@ -0,0 +1,28 @@+'use strict';+// Loaded with `node --require` ahead of check-auth.js, for tests/printers-whole-before-exit.test.js: the Azure CLI and PAC answer as for a signed-in+// [email protected], a Dataverse token is in hand, and WhoAmI is refused with HTTP 500 whose diagnostic is FAKE_WHOAMI_DIAGNOSTIC_SIZE characters long+// (helpers/huge-failure-preload.js hugeFailureText('whoami', size)) — the service's whole message, which the result carries as `whoAmI.message`. No+// process is started and no request is sent; the script and the rest of its helpers are the real ones.+const path = require('node:path');+const { hugeFailureText } = require('./huge-failure-preload.js');++const lib = path.join(__dirname, '..', '..', 'lib');+const authPath = require.resolve(path.join(lib, 'dataverse-auth.js'));+const runnerPath = require.resolve(path.join(lib, 'process-runner.js'));+const auth = require(authPath);+const runner = require(runnerPath);+const diagnostic = hugeFailureText('whoami', Number(process.env.FAKE_WHOAMI_DIAGNOSTIC_SIZE || 0));++require.cache[authPath].exports = {+ ...auth,+ getAuthTokenAsync: async () => 'synthetic-check-auth-token',+ dataverseRequest: async () => ({ status: 500, data: { error: { message: diagnostic } } }),+};+// `az account show` and `pac org who`, as check-auth.js starts them: a callback with the CLI's stdout, and a handle it can cancel.+require.cache[runnerPath].exports = {+ ...runner,+ execFileAsync: (command, args, options, done) => {+ setImmediate(() => done(null, command === 'pac' ? 'Connected as [email protected]\n' : '[email protected]\n', ''));+ return { stdin: { end() {} }, kill() {} };+ },+};diff --git a/plugins/model-apps/scripts/tests/helpers/fake-genpage-server.js b/plugins/model-apps/scripts/tests/helpers/fake-genpage-server.jsindex 0e717b95b..d5a4fb0de 100644--- a/plugins/model-apps/scripts/tests/helpers/fake-genpage-server.js+++ b/plugins/model-apps/scripts/tests/helpers/fake-genpage-server.js@@ -663,4 +663,4 @@ function appTransport(server, { publishFailures = 0, appId = APP_ID, existingPagreturn { http, state };}-module.exports = { FakeGenPageServer, INSTANCE, API, ACCOUNT_TABLE, batchEnvelope, appTransport, APP_ID, APP_EXISTING_PAGE_ID, APP_VIEW_ID };+module.exports = { FakeGenPageServer, INSTANCE, API, ACCOUNT_TABLE, batchEnvelope, appTransport, APP_ID, APP_EXISTING_PAGE_ID, APP_VIEW_ID, sqlGuidOrder };diff --git a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-metadata.js b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-metadata.jsnew file mode 100644index 000000000..2bb214cde--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-metadata.js@@ -0,0 +1,925 @@+'use strict';+// The METADATA half of helpers/fake-lifecycle-org.js: tables (`EntityDefinitions`), their columns (`Attributes`, typed) and alternate keys+// (`Keys`), relationships (`RelationshipDefinitions`) and global option sets (`GlobalOptionSetDefinitions`), stored as the Web API+// returns them and answered with `$select`, `$filter` and `$expand` honoured. The shapes, abridged:+//+// GET EntityDefinitions(LogicalName='contoso_item')?$select=LogicalName,EntitySetName+// -> { "LogicalName": "contoso_item", "EntitySetName": "contoso_items", "MetadataId": "<guid>" } (MetadataId always comes back)+// GET EntityDefinitions(LogicalName='contoso_item')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet+// -> { "value": [ { "@odata.type": "#Microsoft.Dynamics.CRM.PicklistAttributeMetadata", "LogicalName": "contoso_kind", "MetadataId": "<guid>",+// "OptionSet": { "Options": [ { "Value": 100000000, "Label": { "LocalizedLabels": [...], "UserLocalizedLabel": {...} } } ] } } ] }+// a label { "LocalizedLabels": [ { "Label": "Item", "LanguageCode": 1033, "IsManaged": false, "MetadataId": "<guid>", "HasChanged": null } ],+// "UserLocalizedLabel": { "Label": "Item", "LanguageCode": 1033, … } } — the user's language, else the first label+//+// A create is answered as the platform answers it: 204 with `OData-EntityId` naming the new definition by its MetadataId.+// What the platform makes beside what was asked is made here too, because the plugin reads it back and acts on it:+// - a table gets its primary id column (`<table>id`), the ownership and audit columns a user-owned table has, `statecode` and+// `statuscode` with their two states, `versionnumber`, and the `<lookup>name` / `<lookup>yominame` companions of its lookups;+// - a Choice, MultiChoice or Boolean column gets its `<name>name` companion, a lookup its `<name>name` and `<name>yominame` (each+// `AttributeOf` the column, which is how a reader tells them from real columns), and a Money column its `<name>_base` twin — a+// physical column with no AttributeOf, told apart only by `IsBaseCurrency: true` (measured; see companionsOf);+// - a File column gets `<name>_name` (`AttributeOf` the File column, logical); an Image column gets `<name>id`, `<name>_timestamp`+// and `<name>_url` — and here the platform turns it round (MEASURED on a live environment): the Image column is itself the logical+// projection of `<name>id` (`AttributeOf: "<name>id"`, `IsLogical: true`), `<name>id` is a custom Uniqueidentifier with no+// `AttributeOf`, and `_timestamp` / `_url` are `AttributeOf` `<name>id`. The File column is neither logical nor `AttributeOf` anything;+// - the first Image column a table gets becomes its primary image (`IsPrimaryImage: true`, the table's `PrimaryImageAttribute`)+// whatever the create sent — MEASURED: a create sending `false` read back `true` — and a later one does not, `true` sent or not+// (Microsoft Learn: "ignored if set to true when creating a new image column" while another exists). Deleting the primary one+// makes the next the primary (Learn: "another image column for the table is selected automatically");+// - a 1:N relationship creates its lookup column on the referencing table; an N:N its intersect table.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-definitions-using-web-api+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-relationships-using-web-api+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-attributes#update-image-columns+const { randomUUID } = require('node:crypto');+const { compileFilter, describeFilter, evaluateFilter } = require('./odata-filter.js');++const clone = (value) => (value === undefined ? undefined : JSON.parse(JSON.stringify(value)));+const lc = (value) => String(value == null ? '' : value).toLowerCase();+const bare = (id) => lc(id).replace(/[{}]/g, '');+const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++// AttributeType and AttributeTypeName of each typed metadata class the build sends.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/attributetypecode+const TYPE_OF = {+ StringAttributeMetadata: ['String', 'StringType'],+ MemoAttributeMetadata: ['Memo', 'MemoType'],+ IntegerAttributeMetadata: ['Integer', 'IntegerType'],+ BigIntAttributeMetadata: ['BigInt', 'BigIntType'],+ DecimalAttributeMetadata: ['Decimal', 'DecimalType'],+ DoubleAttributeMetadata: ['Double', 'DoubleType'],+ MoneyAttributeMetadata: ['Money', 'MoneyType'],+ BooleanAttributeMetadata: ['Boolean', 'BooleanType'],+ DateTimeAttributeMetadata: ['DateTime', 'DateTimeType'],+ PicklistAttributeMetadata: ['Picklist', 'PicklistType'],+ MultiSelectPicklistAttributeMetadata: ['Virtual', 'MultiSelectPicklistType'],+ LookupAttributeMetadata: ['Lookup', 'LookupType'],+ UniqueIdentifierAttributeMetadata: ['Uniqueidentifier', 'UniqueidentifierType'],+ ImageAttributeMetadata: ['Virtual', 'ImageType'],+ FileAttributeMetadata: ['Virtual', 'FileType'],+ StateAttributeMetadata: ['State', 'StateType'],+ StatusAttributeMetadata: ['Status', 'StatusType'],+ EntityNameAttributeMetadata: ['EntityName', 'EntityNameType'],+};+const classOf = (attribute) => String(attribute['@odata.type'] || '').replace(/^#?Microsoft\.Dynamics\.CRM\./, '');++// THE READ CONTRACT of the metadata half: the properties a read may name, per metadata type, EXPLICITLY. A `$select`, `$filter` or+// `$expand` that names anything else — and a path segment, a key, a cast or a navigation outside the lists below — is refused as+// unmodelled (501, recorded in `org.unexpected`) BEFORE a single definition is looked at, so a changed read can never pass as "nothing+// there". A property on the list that a definition does not hold is answered `null`, as the platform answers an unset property.+// OData types the properties: one a DERIVED type declares (a string column's `MaxLength`) is readable only through a cast to that type+// (`Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=MaxLength`), never on the base collection.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/entitymetadata+const TABLE_PROPS = ['MetadataId', 'LogicalName', 'SchemaName', 'EntitySetName', 'LogicalCollectionName', 'CollectionSchemaName', 'ObjectTypeCode',+ 'IsCustomEntity', 'IsManaged', 'IsActivity', 'IsIntersect', 'TableType', 'OwnershipType', 'HasNotes', 'HasActivities', 'DisplayName',+ 'DisplayCollectionName', 'Description', 'PrimaryIdAttribute', 'PrimaryNameAttribute', 'PrimaryImageAttribute', 'IconVectorName',+ 'IconSmallName', 'IconMediumName', 'IconLargeName', 'ChangeTrackingEnabled', 'IsQuickCreateEnabled', 'Privileges'];+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/attributemetadata+const ATTRIBUTE_BASE = ['MetadataId', 'LogicalName', 'SchemaName', 'EntityLogicalName', 'AttributeType', 'AttributeTypeName', 'DisplayName',+ 'Description', 'RequiredLevel', 'IsCustomAttribute', 'IsCustomizable', 'IsManaged', 'IsPrimaryId', 'IsPrimaryName', 'IsLogical',+ 'IsValidForCreate', 'IsValidForRead', 'IsValidForUpdate', 'AttributeOf', 'SourceType'];+// What each derived column type adds; the enum-valued ones (a choice, a Boolean, a state or status) also navigate to their option set.+const ATTRIBUTE_PROPS = {+ AttributeMetadata: [],+ StringAttributeMetadata: ['MaxLength', 'FormatName', 'Format', 'AutoNumberFormat'],+ MemoAttributeMetadata: ['MaxLength', 'FormatName', 'Format'],+ IntegerAttributeMetadata: ['MinValue', 'MaxValue', 'Format'],+ BigIntAttributeMetadata: ['MinValue', 'MaxValue'],+ DecimalAttributeMetadata: ['MinValue', 'MaxValue', 'Precision'],+ DoubleAttributeMetadata: ['MinValue', 'MaxValue', 'Precision'],+ MoneyAttributeMetadata: ['MinValue', 'MaxValue', 'Precision', 'PrecisionSource', 'IsBaseCurrency'],+ BooleanAttributeMetadata: ['DefaultValue'],+ DateTimeAttributeMetadata: ['Format', 'DateTimeBehavior'],+ PicklistAttributeMetadata: ['DefaultFormValue'],+ MultiSelectPicklistAttributeMetadata: ['DefaultFormValue'],+ LookupAttributeMetadata: ['Targets'],+ UniqueIdentifierAttributeMetadata: [],+ ImageAttributeMetadata: ['MaxSizeInKB', 'CanStoreFullImage', 'IsPrimaryImage'],+ FileAttributeMetadata: ['MaxSizeInKB'],+ StateAttributeMetadata: ['DefaultFormValue'],+ StatusAttributeMetadata: ['DefaultFormValue'],+ EntityNameAttributeMetadata: [],+};+const ENUM_CLASSES = new Set(['BooleanAttributeMetadata', 'PicklistAttributeMetadata', 'MultiSelectPicklistAttributeMetadata', 'StateAttributeMetadata', 'StatusAttributeMetadata']);+const KEY_PROPS = ['MetadataId', 'LogicalName', 'SchemaName', 'EntityLogicalName', 'DisplayName', 'KeyAttributes', 'EntityKeyIndexStatus', 'IsManaged'];+const RELATIONSHIP_BASE = ['MetadataId', 'SchemaName', 'RelationshipType', 'IsCustomRelationship', 'IsManaged', 'IsValidForAdvancedFind'];+const RELATIONSHIP_PROPS = {+ OneToManyRelationshipMetadata: ['ReferencedEntity', 'ReferencingEntity', 'ReferencedAttribute', 'ReferencingAttribute',+ 'ReferencedEntityNavigationPropertyName', 'ReferencingEntityNavigationPropertyName', 'CascadeConfiguration', 'AssociatedMenuConfiguration'],+ ManyToManyRelationshipMetadata: ['Entity1LogicalName', 'Entity2LogicalName', 'Entity1IntersectAttribute', 'Entity2IntersectAttribute',+ 'IntersectEntityName', 'Entity1NavigationPropertyName', 'Entity2NavigationPropertyName', 'Entity1AssociatedMenuConfiguration',+ 'Entity2AssociatedMenuConfiguration'],+};+const OPTIONSET_PROPS = ['MetadataId', 'Name', 'IsGlobal', 'IsCustomOptionSet', 'IsManaged', 'OptionSetType', 'DisplayName', 'Description', 'Options', 'TrueOption', 'FalseOption'];+const OPTIONSET_CASTS = new Set(['OptionSetMetadata', 'BooleanOptionSetMetadata']);+// A table's collection-valued navigations, and the type each leads to.+const TABLE_NAVIGATIONS = {+ Attributes: { kind: 'attribute', cls: null },+ Keys: { kind: 'key' },+ OneToManyRelationships: { kind: 'relationship', cls: 'OneToManyRelationshipMetadata' },+ ManyToOneRelationships: { kind: 'relationship', cls: 'OneToManyRelationshipMetadata' },+ ManyToManyRelationships: { kind: 'relationship', cls: 'ManyToManyRelationshipMetadata' },+};+// The alternate key a path may name a definition by, per collection (beside its MetadataId).+const KEY_NAMES = { EntityDefinitions: 'LogicalName', Attributes: 'LogicalName', Keys: 'LogicalName', RelationshipDefinitions: 'SchemaName', GlobalOptionSetDefinitions: 'Name' };+// The query options each read takes; a nested `$expand` takes `$select` and, on a collection, `$filter`.+const COLLECTION_OPTIONS = ['$select', '$filter', '$expand'];+const SINGLE_OPTIONS = ['$select', '$expand'];++// The properties a type answers, and its single- or collection-valued navigations.+function propsOf(type) {+ if (type.kind === 'table') return TABLE_PROPS;+ if (type.kind === 'attribute') return [...ATTRIBUTE_BASE, ...(type.cls ? ATTRIBUTE_PROPS[type.cls] : [])];+ if (type.kind === 'key') return KEY_PROPS;+ if (type.kind === 'relationship') return [...RELATIONSHIP_BASE, ...(type.cls ? RELATIONSHIP_PROPS[type.cls] : [])];+ if (type.kind === 'optionset') return OPTIONSET_PROPS;+ throw new Error(`fake-lifecycle-metadata: no properties for ${type.kind}`);+}+function navigationsOf(type) {+ if (type.kind === 'table') return TABLE_NAVIGATIONS;+ if (type.kind === 'attribute' && ENUM_CLASSES.has(type.cls)) return { OptionSet: { kind: 'optionset', single: true }, GlobalOptionSet: { kind: 'optionset', single: true } };+ return {};+}+const typeName = (type) => (type.cls || { table: 'EntityMetadata', attribute: 'AttributeMetadata', key: 'EntityKeyMetadata', relationship: 'RelationshipMetadataBase', optionset: 'OptionSetMetadataBase' }[type.kind]);+const listOf = (text) => String(text).split(',').map((x) => x.trim()).filter(Boolean);++// Refuses a read that names anything the type does not have: an option, a property (in `$select` or `$filter`), a navigation (in+// `$expand`, with its own options checked against the type it leads to). The filter is parsed here, once, whatever the collection holds.+function checkMetadataQuery(type, query, options, where) {+ for (const option of Object.keys(query || {})) if (!options.includes(option)) throw new Error(`fake-lifecycle-metadata: the query option ${option} is not modelled on ${where}`);+ const props = propsOf(type);+ const navigations = navigationsOf(type);+ if (query.$select !== undefined) {+ for (const name of listOf(query.$select)) if (!props.includes(name)) throw new Error(`fake-lifecycle-metadata: ${typeName(type)} has no property ${name} ($select on ${where})`);+ }+ if (query.$filter !== undefined) {+ const read = describeFilter(compileFilter(query.$filter));+ if (read.paths.length || read.lambdas.length) throw new Error(`fake-lifecycle-metadata: a navigation in $filter on ${where} is not modelled (${query.$filter})`);+ for (const name of read.fields) if (!props.includes(name)) throw new Error(`fake-lifecycle-metadata: ${typeName(type)} has no property ${name} ($filter on ${where})`);+ }+ if (query.$expand !== undefined) {+ for (const item of parseExpandText(query.$expand)) {+ const target = navigations[item.name];+ if (!target) throw new Error(`fake-lifecycle-metadata: ${typeName(type)} has no navigation ${item.name} ($expand on ${where})`);+ checkMetadataQuery(target, item.opts, target.single ? ['$select'] : ['$select', '$filter'], `${where} $expand=${item.name}`);+ }+ }+}++// `$expand=Attributes($select=LogicalName,AttributeType;$filter=IsCustomAttribute eq true),OptionSet,Keys` -> [{ name, opts }].+function parseExpandText(text) {+ const items = [];+ let depth = 0;+ let start = 0;+ const s = String(text || '');+ for (let i = 0; i <= s.length; i += 1) {+ const ch = s[i];+ if (ch === '(') depth += 1;+ else if (ch === ')') depth -= 1;+ else if ((ch === ',' && depth === 0) || i === s.length) {+ const part = s.slice(start, i).trim();+ if (part) {+ const open = part.indexOf('(');+ const name = open === -1 ? part : part.slice(0, open);+ const inner = open === -1 ? '' : part.slice(open + 1, -1);+ const opts = {};+ let d = 0;+ let from = 0;+ for (let j = 0; j <= inner.length; j += 1) {+ const c = inner[j];+ if (c === '(') d += 1;+ else if (c === ')') d -= 1;+ else if ((c === ';' && d === 0) || j === inner.length) {+ const opt = inner.slice(from, j).trim();+ if (opt) {+ const eq = opt.indexOf('=');+ opts[opt.slice(0, eq)] = opt.slice(eq + 1);+ }+ from = j + 1;+ }+ }+ items.push({ name, opts });+ }+ start = i + 1;+ }+ }+ return items;+}++function createMetadataStore({ baseLanguage = 1033, userLanguage = baseLanguage, solutionOf, addComponent, removeComponents, onTableCreated, onTableDeleted } = {}) {+ const tables = new Map(); // logical -> definition (see makeTable); `Attributes`/`Keys` are Maps+ const relationships = new Map(); // lower-cased SchemaName -> definition+ const optionSets = new Map(); // lower-cased Name -> definition+ let nextObjectTypeCode = 10300;++ // ------------------------------------------------------------------------------------------------------------------------+ // Labels.+ const localized = (label, code) => ({ Label: label, LanguageCode: code, IsManaged: false, MetadataId: randomUUID(), HasChanged: null });+ // A label as sent (`{ LocalizedLabels: [{ Label, LanguageCode }] }`) or plain text, stored as the platform returns it.+ function label(sent) {+ if (sent == null) return { LocalizedLabels: [], UserLocalizedLabel: null };+ const list = typeof sent === 'string' ? [localized(sent, baseLanguage)] : (sent.LocalizedLabels || []).map((l) => localized(l.Label, l.LanguageCode));+ return { LocalizedLabels: list, UserLocalizedLabel: clone(list.find((l) => l.LanguageCode === userLanguage) || list[0] || null) };+ }+ const textOf = (stored) => (stored && stored.UserLocalizedLabel ? stored.UserLocalizedLabel.Label : null);++ // ------------------------------------------------------------------------------------------------------------------------+ // Columns.+ function makeAttribute(table, sent, extra = {}) {+ const cls = classOf(sent) || 'StringAttributeMetadata';+ const [type, typeName] = TYPE_OF[cls] || [null, null];+ if (!type) throw new Error(`fake-lifecycle-metadata: column class ${cls} is not modelled (${sent.SchemaName})`);+ const logical = lc(sent.SchemaName || sent.LogicalName);+ const attribute = {+ ...clone(sent),+ '@odata.type': `#Microsoft.Dynamics.CRM.${cls}`,+ MetadataId: randomUUID(),+ LogicalName: logical,+ SchemaName: sent.SchemaName || logical,+ EntityLogicalName: table.LogicalName,+ AttributeType: type,+ AttributeTypeName: { Value: typeName },+ DisplayName: label(sent.DisplayName),+ Description: label(sent.Description),+ RequiredLevel: { Value: (sent.RequiredLevel && sent.RequiredLevel.Value) || 'None', CanBeChanged: true, ManagedPropertyLogicalName: 'canmodifyrequirementlevelsettings' },+ IsCustomAttribute: extra.IsCustomAttribute !== undefined ? extra.IsCustomAttribute : true,+ IsCustomizable: { Value: true, CanBeChanged: true, ManagedPropertyLogicalName: 'iscustomizable' },+ IsManaged: false,+ IsPrimaryId: false,+ IsPrimaryName: !!sent.IsPrimaryName,+ IsLogical: false,+ IsValidForCreate: sent.IsValidForCreate !== undefined ? sent.IsValidForCreate : true,+ IsValidForRead: sent.IsValidForRead !== undefined ? sent.IsValidForRead : true,+ IsValidForUpdate: sent.IsValidForUpdate !== undefined ? sent.IsValidForUpdate : true,+ AttributeOf: null,+ SourceType: sent.SourceType !== undefined ? sent.SourceType : 0,+ ...extra,+ };+ delete attribute['@odata.context'];+ if (cls === 'StringAttributeMetadata' && attribute.MaxLength === undefined) attribute.MaxLength = 100;+ if (cls === 'StringAttributeMetadata' && !attribute.FormatName) attribute.FormatName = { Value: (sent.FormatName && sent.FormatName.Value) || 'Text' };+ if (cls === 'MemoAttributeMetadata' && attribute.MaxLength === undefined) attribute.MaxLength = 2000;+ // The column a Money column converts is not its base-currency twin (companionsOf makes that one).+ if (cls === 'MoneyAttributeMetadata' && attribute.IsBaseCurrency === undefined) attribute.IsBaseCurrency = false;+ if (attribute.OptionSet) attribute.OptionSet = storedOptionSet(attribute.OptionSet, { local: true });+ // MEASURED: an Image column is the logical projection of its `<name>id` (see companionsOf); `IsPrimaryImage` is decided in addAttribute.+ if (cls === 'ImageAttributeMetadata' && extra.AttributeOf === undefined) Object.assign(attribute, { AttributeOf: `${logical}id`, IsLogical: true });+ return attribute;+ }++ // An option set as stored: every option's labels as labels, the set's own metadata. A global set's bind replaces the local one.+ function storedOptionSet(sent, { local }) {+ const set = clone(sent) || {};+ delete set['@odata.type'];+ const options = (set.Options || []).map((o) => ({+ Value: o.Value,+ Label: label(o.Label),+ Description: label(o.Description),+ Color: o.Color === undefined ? null : o.Color,+ IsManaged: false,+ ExternalValue: o.ExternalValue === undefined ? null : o.ExternalValue,+ ...(o.State !== undefined ? { State: o.State } : {}),+ ...(o.DefaultStatus !== undefined ? { DefaultStatus: o.DefaultStatus } : {}),+ }));+ return {+ MetadataId: set.MetadataId || randomUUID(),+ Name: set.Name || null,+ IsGlobal: !local,+ IsCustomOptionSet: true,+ IsManaged: false,+ OptionSetType: set.OptionSetType || 'Picklist',+ DisplayName: label(set.DisplayName),+ Description: label(set.Description),+ ...(set.TrueOption ? { TrueOption: { Value: 1, Label: label(set.TrueOption.Label) }, FalseOption: { Value: 0, Label: label(set.FalseOption.Label) } } : {}),+ Options: options,+ };+ }++ // The companions the platform makes beside a column: what a reader must tell from a real column. Each is `AttributeOf` the column+ // — but an Image column's are not (MEASURED live): `<name>id` is a custom Uniqueidentifier that is `AttributeOf` nothing and is not+ // logical, `_timestamp` and `_url` are `AttributeOf` `<name>id`, and it is the Image column that is `AttributeOf` `<name>id`.+ function companionsOf(attribute) {+ const name = attribute.LogicalName;+ const cls = classOf(attribute);+ const virtual = (logical, type = 'Virtual', typeName = 'VirtualType', of = name) => ({ '@odata.type': '#Microsoft.Dynamics.CRM.AttributeMetadata', MetadataId: randomUUID(), LogicalName: logical, SchemaName: logical, EntityLogicalName: attribute.EntityLogicalName, AttributeType: type, AttributeTypeName: { Value: typeName }, AttributeOf: of, IsCustomAttribute: attribute.IsCustomAttribute, IsLogical: true, IsPrimaryId: false, IsPrimaryName: false, IsValidForCreate: false, IsValidForRead: true, IsValidForUpdate: false, DisplayName: label(null), Description: label(null), RequiredLevel: { Value: 'None', CanBeChanged: false, ManagedPropertyLogicalName: 'canmodifyrequirementlevelsettings' }, SourceType: 0 });+ if (['PicklistAttributeMetadata', 'MultiSelectPicklistAttributeMetadata', 'BooleanAttributeMetadata', 'StateAttributeMetadata', 'StatusAttributeMetadata'].includes(cls)) return [virtual(`${name}name`)];+ // A Money column's base-currency twin is a PHYSICAL column, not a shadow: it carries no AttributeOf, is not logical and reports+ // IsCustomAttribute like the column it converts — only `IsBaseCurrency: true` tells it apart (measured on stock+ // `opportunity.estimatedvalue_base`; download-model-app.test.js pins the same live shape, and the download filters on it).+ if (cls === 'MoneyAttributeMetadata') {+ return [{ ...virtual(`${name}_base`, 'Money', 'MoneyType'), '@odata.type': '#Microsoft.Dynamics.CRM.MoneyAttributeMetadata', AttributeOf: null, IsLogical: false, IsBaseCurrency: true }];+ }+ if (cls === 'LookupAttributeMetadata') return [virtual(`${name}name`, 'String', 'StringType'), virtual(`${name}yominame`, 'String', 'StringType')];+ if (cls === 'FileAttributeMetadata') return [virtual(`${name}_name`, 'String', 'StringType')];+ if (cls === 'ImageAttributeMetadata') {+ const id = `${name}id`;+ return [+ { ...virtual(id, 'Uniqueidentifier', 'UniqueidentifierType', null), IsLogical: false },+ virtual(`${name}_timestamp`, 'BigInt', 'BigIntType', id),+ virtual(`${name}_url`, 'String', 'StringType', id),+ ];+ }+ return [];+ }++ const isImage = (attribute) => classOf(attribute) === 'ImageAttributeMetadata';++ function addAttribute(table, attribute) {+ // The platform's choice of a table's primary image (see the header): the first Image column it gets, whatever was sent.+ if (isImage(attribute)) {+ const first = ![...table.Attributes.values()].some(isImage);+ attribute.IsPrimaryImage = first;+ if (first) table.PrimaryImageAttribute = attribute.LogicalName;+ }+ table.Attributes.set(attribute.LogicalName, attribute);+ for (const companion of companionsOf(attribute)) if (!table.Attributes.has(companion.LogicalName)) table.Attributes.set(companion.LogicalName, companion);+ return attribute;+ }++ // ------------------------------------------------------------------------------------------------------------------------+ // Tables.+ const systemColumn = (table, logical, cls, extra = {}) => addAttribute(table, makeAttribute(table, { '@odata.type': `Microsoft.Dynamics.CRM.${cls}`, SchemaName: logical, DisplayName: logical }, { IsCustomAttribute: false, IsValidForCreate: false, IsValidForUpdate: false, ...extra }));+ const lookupTo = (targets) => ({ Targets: targets });+ // What a user-owned table holds from its creation, whatever the request said (the columns the platform adds; abridged to the ones a+ // reader meets: ownership, audit, state and the row version).+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/entity-metadata#table-type-and-ownership+ function addSystemColumns(table) {+ const id = `${table.LogicalName}id`;+ addAttribute(table, makeAttribute(table, { '@odata.type': 'Microsoft.Dynamics.CRM.UniqueIdentifierAttributeMetadata', SchemaName: `${table.SchemaName}Id`, DisplayName: table.SchemaName }, { LogicalName: id, IsCustomAttribute: true, IsPrimaryId: true, IsValidForUpdate: false }));+ systemColumn(table, 'createdon', 'DateTimeAttributeMetadata');+ systemColumn(table, 'modifiedon', 'DateTimeAttributeMetadata');+ systemColumn(table, 'overriddencreatedon', 'DateTimeAttributeMetadata', { IsValidForCreate: true });+ systemColumn(table, 'createdby', 'LookupAttributeMetadata', lookupTo(['systemuser']));+ systemColumn(table, 'modifiedby', 'LookupAttributeMetadata', lookupTo(['systemuser']));+ systemColumn(table, 'createdonbehalfby', 'LookupAttributeMetadata', lookupTo(['systemuser']));+ systemColumn(table, 'modifiedonbehalfby', 'LookupAttributeMetadata', lookupTo(['systemuser']));+ systemColumn(table, 'ownerid', 'LookupAttributeMetadata', { AttributeType: 'Owner', AttributeTypeName: { Value: 'OwnerType' }, Targets: ['systemuser', 'team'], IsValidForCreate: true, IsValidForUpdate: true });+ systemColumn(table, 'owningbusinessunit', 'LookupAttributeMetadata', lookupTo(['businessunit']));+ systemColumn(table, 'owninguser', 'LookupAttributeMetadata', lookupTo(['systemuser']));+ systemColumn(table, 'owningteam', 'LookupAttributeMetadata', lookupTo(['team']));+ systemColumn(table, 'statecode', 'StateAttributeMetadata', { IsValidForUpdate: true, OptionSet: storedOptionSet({ OptionSetType: 'State', Options: [{ Value: 0, Label: 'Active', DefaultStatus: 1 }, { Value: 1, Label: 'Inactive', DefaultStatus: 2 }] }, { local: true }) });+ systemColumn(table, 'statuscode', 'StatusAttributeMetadata', { IsValidForCreate: true, IsValidForUpdate: true, OptionSet: storedOptionSet({ OptionSetType: 'Status', Options: [{ Value: 1, Label: 'Active', State: 0 }, { Value: 2, Label: 'Inactive', State: 1 }] }, { local: true }) });+ systemColumn(table, 'versionnumber', 'BigIntAttributeMetadata');+ systemColumn(table, 'importsequencenumber', 'IntegerAttributeMetadata', { IsValidForCreate: true });+ systemColumn(table, 'timezoneruleversionnumber', 'IntegerAttributeMetadata', { IsValidForCreate: true, IsValidForUpdate: true });+ systemColumn(table, 'utcconversiontimezonecode', 'IntegerAttributeMetadata', { IsValidForCreate: true, IsValidForUpdate: true });+ }++ // A table definition from a create request (or a seed). `sent` is the EntityMetadata body: its `Attributes` hold the primary name column.+ function makeTable(sent, { custom = true } = {}) {+ const logical = lc(sent.SchemaName || sent.LogicalName);+ const table = {+ ...clone(sent),+ MetadataId: sent.MetadataId || randomUUID(),+ LogicalName: logical,+ SchemaName: sent.SchemaName || logical,+ EntitySetName: sent.EntitySetName || `${logical}s`,+ LogicalCollectionName: sent.LogicalCollectionName || `${logical}s`,+ CollectionSchemaName: sent.CollectionSchemaName || `${sent.SchemaName || logical}s`,+ ObjectTypeCode: sent.ObjectTypeCode || nextObjectTypeCode++,+ IsCustomEntity: custom,+ IsManaged: false,+ IsActivity: !!sent.IsActivity,+ IsIntersect: !!sent.IsIntersect,+ TableType: 'Standard',+ OwnershipType: sent.OwnershipType || 'UserOwned',+ HasNotes: !!sent.HasNotes,+ HasActivities: !!sent.HasActivities,+ DisplayName: label(sent.DisplayName),+ DisplayCollectionName: label(sent.DisplayCollectionName),+ Description: label(sent.Description),+ PrimaryIdAttribute: `${logical}id`,+ PrimaryNameAttribute: null,+ PrimaryImageAttribute: null,+ IconVectorName: sent.IconVectorName || null,+ IconSmallName: sent.IconSmallName || null,+ IconMediumName: sent.IconMediumName || null,+ IconLargeName: sent.IconLargeName || null,+ ChangeTrackingEnabled: false,+ IsQuickCreateEnabled: !!sent.IsQuickCreateEnabled,+ Attributes: new Map(),+ Keys: new Map(),+ };+ delete table['@odata.type'];+ for (const key of ['Attributes', 'Keys']) if (Array.isArray(sent[key])) table[key] = new Map();+ // The eight privileges the platform makes for a user- or organization-owned table (`prv<Type><SchemaName>`), which a role grants.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/security-roles#privileges+ const ownedByUser = table.OwnershipType === 'UserOwned';+ table.Privileges = ['Create', 'Read', 'Write', 'Delete', 'Append', 'AppendTo', 'Assign', 'Share']+ .filter((type) => ownedByUser || !['Assign', 'Share'].includes(type))+ .map((type) => ({ PrivilegeId: randomUUID(), Name: `prv${type}${table.SchemaName}`, PrivilegeType: type, CanBeBasic: ownedByUser, CanBeLocal: ownedByUser, CanBeDeep: ownedByUser, CanBeGlobal: true, CanBeEntityReference: false, CanBeParentEntityReference: false }));+ addSystemColumns(table);+ for (const attribute of sent.Attributes || []) {+ const made = addAttribute(table, makeAttribute(table, attribute));+ if (made.IsPrimaryName) table.PrimaryNameAttribute = made.LogicalName;+ }+ return table;+ }++ // ------------------------------------------------------------------------------------------------------------------------+ // Relationships. A 1:N is stored with its lookup made on the referencing table; an N:N with its intersect table.+ function makeOneToMany(sent) {+ const referencing = tables.get(lc(sent.ReferencingEntity));+ const referenced = tables.get(lc(sent.ReferencedEntity));+ if (!referencing || !referenced) return { error: `the table ${!referencing ? sent.ReferencingEntity : sent.ReferencedEntity} does not exist` };+ const lookupSent = sent.Lookup || {};+ const lookup = makeAttribute(referencing, { ...lookupSent, '@odata.type': 'Microsoft.Dynamics.CRM.LookupAttributeMetadata' }, { Targets: [referenced.LogicalName] });+ if (referencing.Attributes.has(lookup.LogicalName)) return { error: `Attribute ${lookup.LogicalName} already exists for entity ${referencing.LogicalName}.`, code: '0x80060304' };+ addAttribute(referencing, lookup);+ const relationship = {+ ...clone(sent),+ '@odata.type': '#Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata',+ MetadataId: randomUUID(),+ RelationshipType: 'OneToManyRelationship',+ IsCustomRelationship: true,+ IsManaged: false,+ IsValidForAdvancedFind: true,+ ReferencedEntity: referenced.LogicalName,+ ReferencingEntity: referencing.LogicalName,+ ReferencedAttribute: referenced.PrimaryIdAttribute,+ ReferencingAttribute: lookup.LogicalName,+ ReferencedEntityNavigationPropertyName: sent.ReferencedEntityNavigationPropertyName || sent.SchemaName,+ ReferencingEntityNavigationPropertyName: sent.ReferencingEntityNavigationPropertyName || lookup.LogicalName,+ CascadeConfiguration: clone(sent.CascadeConfiguration) || { Assign: 'NoCascade', Delete: 'RemoveLink', Merge: 'NoCascade', Reparent: 'NoCascade', Share: 'NoCascade', Unshare: 'NoCascade', RollupView: 'NoCascade' },+ AssociatedMenuConfiguration: clone(sent.AssociatedMenuConfiguration) || { Behavior: 'UseCollectionName', Group: 'Details', Label: label(null), Order: 10000 },+ };+ delete relationship.Lookup;+ relationships.set(lc(relationship.SchemaName), relationship);+ return { relationship, lookup };+ }++ function makeManyToMany(sent) {+ const one = tables.get(lc(sent.Entity1LogicalName));+ const two = tables.get(lc(sent.Entity2LogicalName));+ if (!one || !two) return { error: `the table ${!one ? sent.Entity1LogicalName : sent.Entity2LogicalName} does not exist` };+ const intersect = lc(sent.IntersectEntityName || sent.SchemaName);+ const relationship = {+ ...clone(sent),+ '@odata.type': '#Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata',+ MetadataId: randomUUID(),+ RelationshipType: 'ManyToManyRelationship',+ IsCustomRelationship: true,+ IsManaged: false,+ IsValidForAdvancedFind: true,+ Entity1LogicalName: one.LogicalName,+ Entity2LogicalName: two.LogicalName,+ Entity1IntersectAttribute: `${one.LogicalName}id`,+ Entity2IntersectAttribute: one.LogicalName === two.LogicalName ? `${two.LogicalName}idtwo` : `${two.LogicalName}id`,+ IntersectEntityName: intersect,+ Entity1NavigationPropertyName: sent.Entity1NavigationPropertyName || sent.SchemaName,+ Entity2NavigationPropertyName: sent.Entity2NavigationPropertyName || sent.SchemaName,+ Entity1AssociatedMenuConfiguration: clone(sent.Entity1AssociatedMenuConfiguration) || { Behavior: 'UseCollectionName', Group: 'Details', Label: label(null), Order: 10000 },+ Entity2AssociatedMenuConfiguration: clone(sent.Entity2AssociatedMenuConfiguration) || { Behavior: 'UseCollectionName', Group: 'Details', Label: label(null), Order: 10000 },+ };+ relationships.set(lc(relationship.SchemaName), relationship);+ // The intersect table the platform makes (not customizable, no primary name): it exists while the relationship does.+ const table = makeTable({ SchemaName: intersect, EntitySetName: `${intersect}set`, IsIntersect: true, DisplayName: intersect, DisplayCollectionName: intersect }, { custom: true });+ tables.set(intersect, table);+ return { relationship };+ }++ // The relationships a table takes part in, from one side: what `<table>/OneToManyRelationships` (the table is the referenced one),+ // `ManyToOneRelationships` (the referencing one) and `ManyToManyRelationships` (either entity) answer.+ function relationshipsOf(logical, kind) {+ const all = [...relationships.values()];+ if (kind === 'OneToManyRelationships') return all.filter((r) => r.RelationshipType === 'OneToManyRelationship' && r.ReferencedEntity === logical);+ if (kind === 'ManyToOneRelationships') return all.filter((r) => r.RelationshipType === 'OneToManyRelationship' && r.ReferencingEntity === logical);+ return all.filter((r) => r.RelationshipType === 'ManyToManyRelationship' && (r.Entity1LogicalName === logical || r.Entity2LogicalName === logical));+ }++ // ------------------------------------------------------------------------------------------------------------------------+ // Reads: `$select`, `$filter` and `$expand` over the stored definitions, each already checked against the read contract above+ // (checkMetadataQuery) before any definition is looked at.+ const parseExpand = parseExpandText;+ // A filter reads a metadata property's value: an enum-valued one (`AttributeType eq 'Picklist'`) is text, a BooleanManagedProperty its `Value`.+ const flatForFilter = (def) => Object.fromEntries(Object.entries(def).map(([k, v]) => [k, v && typeof v === 'object' && !Array.isArray(v) && 'Value' in v ? v.Value : v]));+ const filtered = (list, text) => (text === undefined ? list : list.filter((def) => evaluateFilter(compileFilter(text), flatForFilter(def), {})));++ // The properties a definition is answered with: with `$select`, exactly those (an unset one as `null`, as the platform answers it) and+ // `MetadataId`; without, every property it holds but its collection-valued navigations, which come back only when expanded. The+ // `@odata.type` of a derived type always comes back.+ function project(def, query, type) {+ const select = query.$select !== undefined ? listOf(query.$select) : null;+ const navigations = navigationsOf(type);+ const out = {};+ if (def['@odata.type']) out['@odata.type'] = def['@odata.type'];+ if (select) {+ for (const name of new Set(['MetadataId', ...select])) out[name] = def[name] === undefined ? null : clone(def[name]);+ } else {+ for (const [key, value] of Object.entries(def)) {+ if (key === '@odata.type' || value instanceof Map) continue;+ if (TABLE_NAVIGATIONS[key] && type.kind === 'table') continue;+ if (key === 'GlobalOptionSet' && type.kind === 'attribute') continue;+ out[key] = clone(value);+ }+ }+ for (const item of parseExpand(query.$expand)) out[item.name] = expandOf(def, type, navigations[item.name], item);+ return out;+ }+ function expandOf(def, type, target, item) {+ if (type.kind === 'table') {+ if (item.name === 'Attributes') return listAttributes(def, item.opts, null);+ if (item.name === 'Keys') return filtered([...def.Keys.values()], item.opts.$filter).map((k) => project(k, item.opts, target));+ return filtered(relationshipsOf(def.LogicalName, item.name), item.opts.$filter).map((r) => project(r, item.opts, target));+ }+ // An enum-valued column's option set: `GlobalOptionSet` is the global set it binds (null for a local one).+ const set = item.name === 'GlobalOptionSet' ? (def.GlobalOptionSet || (def.OptionSet && def.OptionSet.IsGlobal ? def.OptionSet : null)) : def.OptionSet;+ return set ? project(set, item.opts, target) : null;+ }+ // The columns of a table, of one derived type when the path casts (`Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata` —+ // a Customer or Owner lookup is a LookupAttributeMetadata too).+ function listAttributes(table, query, cast) {+ let list = [...table.Attributes.values()];+ if (cast) list = list.filter((a) => classOf(a) === cast);+ return filtered(list, query.$filter).map((a) => project(a, query, { kind: 'attribute', cls: cast || null }));+ }++ // `LogicalName='x'` / `<MetadataId>` / `SchemaName='x'` / `Name='x'`, as the key of a definition in a path. The alternate key a+ // collection takes is its own (KEY_NAMES): any other is unmodelled.+ function keyed(map, key, collection) {+ const named = /^(\w+)='((?:[^']|'')*)'$/.exec(key);+ if (named) {+ if (collection && named[1] !== KEY_NAMES[collection]) throw new Error(`fake-lifecycle-metadata: ${collection} is not keyed by ${named[1]}`);+ const value = lc(named[2].replace(/''/g, "'"));+ return [...map.values()].find((d) => lc(d[named[1]]) === value) || null;+ }+ if (!GUID_RE.test(bare(key))) throw new Error(`fake-lifecycle-metadata: the key (${key}) of ${collection || 'a definition'} is not modelled`);+ const id = bare(key);+ return [...map.values()].find((d) => bare(d.MetadataId) === id) || null;+ }+ const tableAt = (key) => keyed(tables, key, 'EntityDefinitions');++ // ------------------------------------------------------------------------------------------------------------------------+ // The router. `path` is below the API root, decoded, without the query; `query` the query's parameters. Answers+ // `{ status, body, headers }`, or null when the path is not a metadata path. `solution` is the `MSCRM.SolutionUniqueName` header.+ const ok = (body, headers = {}) => ({ status: 200, body, headers });+ const created = (location) => ({ status: 204, body: undefined, headers: { 'odata-entityid': location } });+ const fail = (status, message, code = '0x80040203') => ({ status, body: { error: { code, message } }, headers: {} });+ const missing = (what) => fail(404, `Could not find ${what}.`, '0x80040217');+ const collection = (value) => ok({ value });+ const CAST = /^Microsoft\.Dynamics\.CRM\.(\w+)$/;++ function handle(method, path, query, body, headers, apiRoot) {+ const segments = splitPath(path);+ if (!segments.length) return null;+ const head = segments[0];+ const solution = headers && Object.entries(headers).find(([k]) => k.toLowerCase() === 'mscrm.solutionuniquename');+ const solutionName = solution ? solution[1] : null;+ if (head.name === 'CreateCustomerRelationships' && method === 'POST') return createCustomer(body, solutionName);+ if (!['EntityDefinitions', 'RelationshipDefinitions', 'GlobalOptionSetDefinitions'].includes(head.name)) return null;+ if (head.name === 'EntityDefinitions') return entityDefinitions(method, segments, query, body, solutionName, apiRoot, headers);+ if (head.name === 'RelationshipDefinitions') return relationshipDefinitions(method, segments, query, body, solutionName, apiRoot);+ return optionSetDefinitions(method, segments, query, body, solutionName, apiRoot);+ }++ // `EntityDefinitions(LogicalName='x')/Attributes(LogicalName='y')/Microsoft.Dynamics.CRM.StringAttributeMetadata` ->+ // [{ name: 'EntityDefinitions', key: "LogicalName='x'" }, { name: 'Attributes', key: "LogicalName='y'" }, { name: 'Microsoft.Dynamics.CRM.StringAttributeMetadata' }]+ function splitPath(path) {+ const out = [];+ let i = 1;+ while (i < path.length) {+ let name = '';+ while (i < path.length && path[i] !== '(' && path[i] !== '/') name += path[i++];+ let key = null;+ if (path[i] === '(') {+ let depth = 0;+ let start = i + 1;+ for (; i < path.length; i += 1) {+ if (path[i] === "'") { i += 1; while (i < path.length && !(path[i] === "'" && path[i + 1] !== "'")) i += path[i] === "'" ? 2 : 1; continue; }+ if (path[i] === '(') depth += 1;+ if (path[i] === ')') { depth -= 1; if (depth === 0) break; }+ }+ key = path.slice(start, i);+ i += 1;+ }+ out.push({ name, key });+ if (path[i] === '/') i += 1;+ }+ return out;+ }++ // The paths under EntityDefinitions, every one of them (anything else is refused, naming it):+ // EntityDefinitions GET (collection) · POST+ // EntityDefinitions(K) GET · PUT · DELETE+ // EntityDefinitions(K)/Attributes[/<attribute cast>] GET (collection) · POST (uncast)+ // EntityDefinitions(K)/Attributes(K)[/<attribute cast>] GET · PUT · DELETE (uncast)+ // EntityDefinitions(K)/Attributes(K)/<enum cast>/OptionSet GET (and GlobalOptionSet)+ // EntityDefinitions(K)/Keys · Keys(K) GET · POST · DELETE+ // EntityDefinitions(K)/OneToManyRelationships | ManyToOneRelationships | ManyToManyRelationships GET (collection)+ // K is `LogicalName='x'` or a MetadataId. A cast names a type the fake models (ATTRIBUTE_PROPS); a cast to the wrong type of the+ // column a path names is the platform's 400.+ const castOf = (segment, allowed, where) => {+ const cast = segment && CAST.exec(segment.name);+ if (!cast || segment.key !== null) throw new Error(`fake-lifecycle-metadata: ${where}/${segment ? segment.name : ''} is not modelled`);+ if (!allowed(cast[1])) throw new Error(`fake-lifecycle-metadata: the cast ${cast[1]} on ${where} is not modelled`);+ return cast[1];+ };+ const isAttributeClass = (name) => Object.prototype.hasOwnProperty.call(ATTRIBUTE_PROPS, name);+ const unmodelled = (method, where) => { throw new Error(`fake-lifecycle-metadata: ${method} ${where} is not modelled`); };++ function entityDefinitions(method, segments, query, body, solutionName, apiRoot, headers) {+ const [head, sub, third, fourth, ...rest] = segments;+ const table = { kind: 'table' };+ if (rest.length) unmodelled(method, segments.map((x) => x.name).join('/'));+ if (!head.key) {+ if (sub) unmodelled(method, `EntityDefinitions/${sub.name}`);+ if (method === 'GET') {+ checkMetadataQuery(table, query, COLLECTION_OPTIONS, 'EntityDefinitions');+ return collection(filtered([...tables.values()], query.$filter).map((t) => project(t, query, table)));+ }+ if (method === 'POST') return createTable(body, solutionName, apiRoot);+ unmodelled(method, 'EntityDefinitions');+ }+ const where = `EntityDefinitions(${head.key})`;+ const found = tableAt(head.key);+ if (!sub) {+ if (method === 'GET') { checkMetadataQuery(table, query, SINGLE_OPTIONS, where); return found ? ok(project(found, query, table)) : missing(`entity ${head.key}`); }+ if (method === 'PUT') return found ? updateTable(found, body, headers) : missing(`entity ${head.key}`);+ if (method === 'DELETE') return found ? deleteTable(found) : missing(`entity ${head.key}`);+ unmodelled(method, where);+ }+ if (!TABLE_NAVIGATIONS[sub.name]) unmodelled(method, `${where}/${sub.name}`);+ if (sub.name === 'Attributes') {+ if (!sub.key) {+ if (fourth) unmodelled(method, `${where}/Attributes/${third.name}/${fourth.name}`);+ const cast = third ? castOf(third, isAttributeClass, `${where}/Attributes`) : null;+ if (method === 'GET') {+ checkMetadataQuery({ kind: 'attribute', cls: cast }, query, COLLECTION_OPTIONS, `${where}/Attributes${cast ? `/${cast}` : ''}`);+ return found ? collection(listAttributes(found, query, cast)) : missing(`entity ${head.key}`);+ }+ if (method === 'POST' && !cast) return found ? createColumn(found, body, solutionName, apiRoot) : missing(`entity ${head.key}`);+ unmodelled(method, `${where}/Attributes`);+ }+ const at = `${where}/Attributes(${sub.key})`;+ const cast = third ? castOf(third, isAttributeClass, at) : null;+ if (fourth) {+ // An enum-valued column's option set, through the cast that declares the navigation.+ const navigation = navigationsOf({ kind: 'attribute', cls: cast })[fourth.name];+ if (!navigation || fourth.key !== null || method !== 'GET') unmodelled(method, `${at}/${third.name}/${fourth.name}`);+ checkMetadataQuery(navigation, query, ['$select'], `${at}/${fourth.name}`);+ } else if (method === 'GET') {+ checkMetadataQuery({ kind: 'attribute', cls: cast }, query, SINGLE_OPTIONS, at);+ }+ if (!found) return missing(`entity ${head.key}`);+ const attribute = keyed(found.Attributes, sub.key, 'Attributes');+ if (!attribute) return missing(`attribute ${sub.key} on ${found.LogicalName}`);+ if (cast && classOf(attribute) !== cast) return fail(400, `The attribute ${attribute.LogicalName} is not a ${cast}.`, '0x80060888');+ if (method === 'GET') {+ if (fourth) return ok(expandOf(attribute, { kind: 'attribute', cls: cast }, navigationsOf({ kind: 'attribute', cls: cast })[fourth.name], { name: fourth.name, opts: query }));+ return ok(project(attribute, query, { kind: 'attribute', cls: cast }));+ }+ if (method === 'PUT' && !fourth) return updateColumn(found, attribute, body, headers);+ if (method === 'DELETE' && !cast) return deleteColumn(found, attribute);+ unmodelled(method, at);+ }+ if (third) unmodelled(method, `${where}/${sub.name}/${third.name}`);+ if (sub.name === 'Keys') {+ const keyType = { kind: 'key' };+ if (!sub.key) {+ if (method === 'GET') { checkMetadataQuery(keyType, query, COLLECTION_OPTIONS, `${where}/Keys`); return found ? collection(filtered([...found.Keys.values()], query.$filter).map((k) => project(k, query, keyType))) : missing(`entity ${head.key}`); }+ if (method === 'POST') return found ? createKey(found, body, apiRoot) : missing(`entity ${head.key}`);+ unmodelled(method, `${where}/Keys`);+ }+ if (method === 'GET') checkMetadataQuery(keyType, query, SINGLE_OPTIONS, `${where}/Keys(${sub.key})`);+ if (!found) return missing(`entity ${head.key}`);+ const key = keyed(found.Keys, sub.key, 'Keys');+ if (method === 'GET') return key ? ok(project(key, query, keyType)) : missing(`key ${sub.key}`);+ if (method === 'DELETE') { if (!key) return missing(`key ${sub.key}`); found.Keys.delete(key.LogicalName); return { status: 204, headers: {} }; }+ unmodelled(method, `${where}/Keys(${sub.key})`);+ }+ // OneToManyRelationships / ManyToOneRelationships / ManyToManyRelationships: a collection, read only.+ if (sub.key || method !== 'GET') unmodelled(method, `${where}/${sub.name}${sub.key ? `(${sub.key})` : ''}`);+ const type = TABLE_NAVIGATIONS[sub.name];+ checkMetadataQuery(type, query, COLLECTION_OPTIONS, `${where}/${sub.name}`);+ if (!found) return missing(`entity ${head.key}`);+ return collection(filtered(relationshipsOf(found.LogicalName, sub.name), query.$filter).map((r) => project(r, query, type)));+ }++ function createTable(body, solutionName, apiRoot) {+ const logical = lc(body.SchemaName);+ if (tables.has(logical)) return fail(400, `Entities already exist: ${body.SchemaName}`, '0x80047013');+ const table = makeTable(body);+ if (!table.PrimaryNameAttribute) return fail(400, 'A primary name attribute is required.', '0x80047013');+ tables.set(logical, table);+ if (addComponent) addComponent(solutionName, { objectid: table.MetadataId, componenttype: 1, rootcomponentbehavior: 0 });+ if (onTableCreated) onTableCreated(table, solutionName);+ return created(`${apiRoot}/EntityDefinitions(${table.MetadataId})`);+ }++ // A PUT replaces the definition; `MSCRM.MergeLabels: true` keeps the labels of the languages the request does not carry.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-definitions-using-web-api#update-table-definitions+ function mergeLabels(stored, sent, merge) {+ const next = label(sent);+ if (!merge) return next;+ const kept = stored.LocalizedLabels.filter((l) => !next.LocalizedLabels.some((n) => n.LanguageCode === l.LanguageCode));+ const list = [...kept, ...next.LocalizedLabels];+ return { LocalizedLabels: list, UserLocalizedLabel: clone(list.find((l) => l.LanguageCode === userLanguage) || list[0] || null) };+ }+ const isMerge = (headers) => !!headers && Object.entries(headers).some(([k, v]) => k.toLowerCase() === 'mscrm.mergelabels' && String(v) === 'true');+ const LABEL_KEYS = ['DisplayName', 'DisplayCollectionName', 'Description'];+ function updateTable(table, body, headers) {+ for (const [key, value] of Object.entries(body || {})) {+ if (key.startsWith('@odata') || ['MetadataId', 'LogicalName', 'Attributes', 'Keys'].includes(key)) continue;+ table[key] = LABEL_KEYS.includes(key) ? mergeLabels(table[key], value, isMerge(headers)) : clone(value);+ }+ return { status: 204, headers: {} };+ }++ function createColumn(table, body, solutionName, apiRoot) {+ const logical = lc(body.SchemaName);+ if (table.Attributes.has(logical)) return fail(400, `Attribute ${logical} already exists for entity ${table.LogicalName}.`, '0x80060304');+ const bind = body['[email protected]'];+ const sent = { ...body };+ delete sent['[email protected]'];+ const attribute = makeAttribute(table, sent);+ if (bind) {+ const set = keyed(optionSets, (/GlobalOptionSetDefinitions\((.+)\)$/.exec(bind) || [])[1] || '');+ if (!set) return fail(400, `The global option set ${bind} does not exist.`);+ attribute.OptionSet = clone(set);+ attribute.GlobalOptionSet = clone(set);+ }+ addAttribute(table, attribute);+ if (addComponent) addComponent(solutionName, { objectid: attribute.MetadataId, componenttype: 2, parentTable: table.LogicalName });+ return created(`${apiRoot}/EntityDefinitions(${table.MetadataId})/Attributes(${attribute.MetadataId})`);+ }++ function updateColumn(table, attribute, body, headers) {+ for (const [key, value] of Object.entries(body || {})) {+ if (key.startsWith('@odata') || ['MetadataId', 'LogicalName', 'AttributeType', 'AttributeTypeName'].includes(key)) continue;+ if (LABEL_KEYS.includes(key)) attribute[key] = mergeLabels(attribute[key], value, isMerge(headers));+ else if (key === 'OptionSet') attribute.OptionSet = { ...attribute.OptionSet, ...storedOptionSet(value, { local: !attribute.OptionSet || !attribute.OptionSet.IsGlobal }), MetadataId: attribute.OptionSet ? attribute.OptionSet.MetadataId : randomUUID() };+ else attribute[key] = clone(value);+ }+ if (attribute.IsPrimaryName) table.PrimaryNameAttribute = attribute.LogicalName;+ return { status: 204, headers: {} };+ }++ function deleteColumn(table, attribute) {+ table.Attributes.delete(attribute.LogicalName);+ for (const [name, other] of [...table.Attributes]) if (other.AttributeOf === attribute.LogicalName) table.Attributes.delete(name);+ // The base-currency twin has no AttributeOf to follow (see companionsOf): it goes by its name, as the platform deletes it.+ const twin = table.Attributes.get(`${attribute.LogicalName}_base`);+ if (classOf(attribute) === 'MoneyAttributeMetadata' && attribute.IsBaseCurrency !== true && twin && twin.IsBaseCurrency === true) table.Attributes.delete(twin.LogicalName);+ // An Image column's companions hang off its `<name>id` (companionsOf), which goes with it; and the next Image column becomes the+ // table's primary image when this one was it (see the header).+ if (isImage(attribute)) {+ const id = `${attribute.LogicalName}id`;+ for (const [name, other] of [...table.Attributes]) if (name === id || other.AttributeOf === id) table.Attributes.delete(name);+ if (table.PrimaryImageAttribute === attribute.LogicalName) {+ const next = [...table.Attributes.values()].find(isImage);+ table.PrimaryImageAttribute = next ? next.LogicalName : null;+ if (next) next.IsPrimaryImage = true;+ }+ }+ if (removeComponents) removeComponents([attribute.MetadataId]);+ return { status: 204, headers: {} };+ }++ function createKey(table, body, apiRoot) {+ const logical = lc(body.SchemaName);+ if (table.Keys.has(logical)) return fail(400, `A key with the same name already exists on ${table.LogicalName}.`);+ for (const column of body.KeyAttributes || []) if (!table.Attributes.has(lc(column))) return fail(400, `The key column ${column} does not exist on ${table.LogicalName}.`);+ const key = { ...clone(body), MetadataId: randomUUID(), LogicalName: logical, EntityLogicalName: table.LogicalName, DisplayName: label(body.DisplayName), EntityKeyIndexStatus: 'Active', IsManaged: false };+ delete key['@odata.type'];+ table.Keys.set(logical, key);+ return created(`${apiRoot}/EntityDefinitions(${table.MetadataId})/Keys(${key.MetadataId})`);+ }++ // Deleting a table removes everything that is part of it: its columns, its keys, the relationships it takes part in (with the lookups+ // they made on the other side), its rows and its views, forms and charts (`onTableDeleted`) and its solution components.+ function deleteTable(table) {+ for (const r of [...relationships.values()]) {+ const involved = r.RelationshipType === 'OneToManyRelationship' ? [r.ReferencedEntity, r.ReferencingEntity] : [r.Entity1LogicalName, r.Entity2LogicalName];+ if (involved.includes(table.LogicalName)) removeRelationship(r);+ }+ tables.delete(table.LogicalName);+ if (removeComponents) removeComponents([table.MetadataId, ...[...table.Attributes.values()].map((a) => a.MetadataId)]);+ if (onTableDeleted) onTableDeleted(table);+ return { status: 204, headers: {} };+ }++ function removeRelationship(r) {+ relationships.delete(lc(r.SchemaName));+ if (r.RelationshipType === 'OneToManyRelationship') {+ const referencing = tables.get(r.ReferencingEntity);+ const lookup = referencing && referencing.Attributes.get(r.ReferencingAttribute);+ if (lookup) deleteColumn(referencing, lookup);+ } else {+ const intersect = tables.get(r.IntersectEntityName);+ if (intersect) { tables.delete(intersect.LogicalName); if (onTableDeleted) onTableDeleted(intersect); }+ }+ if (removeComponents) removeComponents([r.MetadataId]);+ }++ // RelationshipDefinitions[/<relationship cast>] (GET; POST uncast) and RelationshipDefinitions(K)[/<cast>] (GET, PUT; DELETE+ // uncast), K being `SchemaName='x'` or a MetadataId.+ const isRelationshipClass = (name) => Object.prototype.hasOwnProperty.call(RELATIONSHIP_PROPS, name);+ function relationshipDefinitions(method, segments, query, body, solutionName, apiRoot) {+ const [head, sub, ...rest] = segments;+ if (rest.length) unmodelled(method, segments.map((x) => x.name).join('/'));+ const cast = sub ? castOf(sub, isRelationshipClass, `RelationshipDefinitions${head.key ? `(${head.key})` : ''}`) : null;+ const type = { kind: 'relationship', cls: cast };+ if (!head.key) {+ if (method === 'GET') {+ checkMetadataQuery(type, query, COLLECTION_OPTIONS, `RelationshipDefinitions${cast ? `/${cast}` : ''}`);+ const list = [...relationships.values()].filter((r) => !cast || r['@odata.type'] === `#Microsoft.Dynamics.CRM.${cast}`);+ return collection(filtered(list, query.$filter).map((r) => project(r, query, type)));+ }+ if (method === 'POST' && !cast) {+ if (relationships.has(lc(body.SchemaName))) return fail(400, `A relationship with the name ${body.SchemaName} already exists.`, '0x80047007');+ const many = /ManyToManyRelationshipMetadata$/.test(String(body['@odata.type']));+ const made = many ? makeManyToMany(body) : makeOneToMany(body);+ if (made.error) return fail(400, made.error, made.code || '0x80040203');+ if (addComponent) addComponent(solutionName, { objectid: made.relationship.MetadataId, componenttype: 10 });+ return created(`${apiRoot}/RelationshipDefinitions(${made.relationship.MetadataId})`);+ }+ unmodelled(method, 'RelationshipDefinitions');+ }+ if (method === 'GET') checkMetadataQuery(type, query, ['$select'], `RelationshipDefinitions(${head.key})`);+ const r = keyed(relationships, head.key, 'RelationshipDefinitions');+ if (!r) return missing(`relationship ${head.key}`);+ if (cast && r['@odata.type'] !== `#Microsoft.Dynamics.CRM.${cast}`) return fail(400, `The relationship ${r.SchemaName} is not a ${cast}.`, '0x80060888');+ if (method === 'GET') return ok(project(r, query, { kind: 'relationship', cls: cast || r['@odata.type'].replace(/^#Microsoft\.Dynamics\.CRM\./, '') }));+ if (method === 'PUT') {+ for (const [key, value] of Object.entries(body || {})) if (!key.startsWith('@odata') && key !== 'MetadataId') r[key] = clone(value);+ return { status: 204, headers: {} };+ }+ if (method === 'DELETE' && !cast) { removeRelationship(r); return { status: 204, headers: {} }; }+ unmodelled(method, `RelationshipDefinitions(${head.key})`);+ }++ // GlobalOptionSetDefinitions (GET, POST) and GlobalOptionSetDefinitions(K)[/<option set cast>] (GET; PUT and DELETE uncast), K being+ // `Name='x'` or a MetadataId. A global option set cannot be deleted while a column binds it (the platform names the dependency).+ function optionSetDefinitions(method, segments, query, body, solutionName, apiRoot) {+ const [head, sub, ...rest] = segments;+ if (rest.length || (sub && !head.key)) unmodelled(method, segments.map((x) => x.name).join('/'));+ const cast = sub ? castOf(sub, (name) => OPTIONSET_CASTS.has(name), `GlobalOptionSetDefinitions(${head.key})`) : null;+ const type = { kind: 'optionset', cls: cast };+ if (!head.key) {+ if (method === 'GET') {+ checkMetadataQuery(type, query, ['$select', '$filter'], 'GlobalOptionSetDefinitions');+ return collection(filtered([...optionSets.values()], query.$filter).map((set) => project(set, query, type)));+ }+ if (method === 'POST') {+ if (optionSets.has(lc(body.Name))) return fail(400, `An option set with the name ${body.Name} already exists.`, '0x80047008');+ const set = { ...storedOptionSet(body, { local: false }), Name: body.Name };+ optionSets.set(lc(body.Name), set);+ if (addComponent) addComponent(solutionName, { objectid: set.MetadataId, componenttype: 9 });+ return created(`${apiRoot}/GlobalOptionSetDefinitions(${set.MetadataId})`);+ }+ unmodelled(method, 'GlobalOptionSetDefinitions');+ }+ if (method === 'GET') checkMetadataQuery(type, query, ['$select'], `GlobalOptionSetDefinitions(${head.key})`);+ const set = keyed(optionSets, head.key, 'GlobalOptionSetDefinitions');+ if (!set) return missing(`option set ${head.key}`);+ if (method === 'GET') return ok(project(set, query, type));+ if (method === 'DELETE' && !cast) {+ const binders = [...tables.values()].flatMap((t) => [...t.Attributes.values()].filter((a) => a.OptionSet && bare(a.OptionSet.MetadataId) === bare(set.MetadataId)));+ if (binders.length) return fail(400, `The OptionSet(${set.MetadataId}) component cannot be deleted because it is referenced by ${binders.length} other components.`, '0x8004f01f');+ optionSets.delete(lc(set.Name));+ if (removeComponents) removeComponents([set.MetadataId]);+ return { status: 204, headers: {} };+ }+ if (method === 'PUT' && !cast) {+ Object.assign(set, storedOptionSet({ ...set, ...body }, { local: false }), { MetadataId: set.MetadataId, Name: set.Name });+ return { status: 204, headers: {} };+ }+ unmodelled(method, `GlobalOptionSetDefinitions(${head.key})`);+ }++ // CreateCustomerRelationships { Lookup: { "@odata.type": "Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata", SchemaName, Targets },+ // OneToManyRelationships: [ { SchemaName, ReferencedEntity: "account", ReferencingEntity }, { … "contact" … } ] }: one Customer lookup+ // on the referencing table (with its `<name>name`, `<name>yominame` and `<name>idtype` companions) and a 1:N from each target, answered+ // `{ "AttributeId": "<guid>", "RelationshipIds": [ "<guid>", "<guid>" ] }`.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/createcustomerrelationships+ function createCustomer(body, solutionName) {+ const rels = body.OneToManyRelationships || [];+ const referencing = tables.get(lc(rels[0] && rels[0].ReferencingEntity));+ if (!referencing) return fail(400, `the table ${rels[0] && rels[0].ReferencingEntity} does not exist`);+ const logical = lc(body.Lookup.SchemaName);+ if (referencing.Attributes.has(logical)) return fail(400, `Attribute ${logical} already exists for entity ${referencing.LogicalName}.`, '0x80060304');+ const lookup = makeAttribute(referencing, { ...body.Lookup, '@odata.type': 'Microsoft.Dynamics.CRM.LookupAttributeMetadata' }, { AttributeType: 'Customer', AttributeTypeName: { Value: 'CustomerType' }, Targets: clone(body.Lookup.Targets) });+ addAttribute(referencing, lookup);+ const idtype = { ...companionsOf(lookup)[0], LogicalName: `${logical}idtype`, SchemaName: `${logical}idtype`, AttributeType: 'EntityName', AttributeTypeName: { Value: 'EntityNameType' }, MetadataId: randomUUID() };+ referencing.Attributes.set(idtype.LogicalName, idtype);+ const ids = [];+ for (const r of rels) {+ const referenced = tables.get(lc(r.ReferencedEntity));+ if (!referenced) return fail(400, `the table ${r.ReferencedEntity} does not exist`);+ const relationship = {+ ...clone(r), '@odata.type': '#Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata', MetadataId: randomUUID(), RelationshipType: 'OneToManyRelationship', IsCustomRelationship: true, IsManaged: false,+ ReferencedEntity: referenced.LogicalName, ReferencingEntity: referencing.LogicalName, ReferencedAttribute: referenced.PrimaryIdAttribute, ReferencingAttribute: logical,+ CascadeConfiguration: { Assign: 'NoCascade', Delete: 'RemoveLink', Merge: 'NoCascade', Reparent: 'NoCascade', Share: 'NoCascade', Unshare: 'NoCascade', RollupView: 'NoCascade' },+ };+ relationships.set(lc(relationship.SchemaName), relationship);+ ids.push(relationship.MetadataId);+ if (addComponent) addComponent(solutionName, { objectid: relationship.MetadataId, componenttype: 10 });+ }+ if (addComponent) addComponent(solutionName, { objectid: lookup.MetadataId, componenttype: 2, parentTable: referencing.LogicalName });+ return ok({ AttributeId: lookup.MetadataId, RelationshipIds: ids });+ }++ return { tables, relationships, optionSets, label, textOf, makeAttribute, storedOptionSet, companionsOf, addAttribute, makeTable, makeOneToMany, makeManyToMany, relationshipsOf, project, listAttributes, parseExpand, keyed, tableAt, flatForFilter, handle, splitPath, deleteTable, removeRelationship };+}++module.exports = { createMetadataStore, TYPE_OF, classOf };diff --git a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.jsnew file mode 100644index 000000000..66a20551b--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js@@ -0,0 +1,1344 @@+'use strict';+// A STATEFUL fake Dataverse that a whole App Spec lifecycle runs against — build, rebuild, download, verify and teardown — over the+// plugin's own az-token HTTP client and the REAL vendored SDK, so a test asserts on what reached the wire and on what the environment+// is left holding, never on which SDK method a mock saw:+//+// const org = createLifecycleOrg();+// const client = createAzHttpClient(org.origin, { getToken: () => TOKEN, request: org.request, sleep: async () => {} });+//+// What it holds, and the platform rules it keeps:+//+// records one store per entity set (`solutions`, `savedqueries`, `systemforms`, `appmodules`, `webresourceset`, `roles`, `workflows`,+// …, and the entity set of every table the build creates, for sample data). Every row carries a row version: its+// `@odata.etag` is `W/"<n>"`, every write moves it, and a conditional write (`If-Match`) on another version answers 412.+// A view, form, chart, dashboard, app module and site map is a SOLUTION-AWARE row with two layers: the SAVED one, which+// every write changes and which `RetrieveUnpublished` / `RetrieveUnpublishedMultiple` read (`componentstate` 1 while it+// holds a change no publish has copied, 0 once one has), and the PUBLISHED one, which a plain read of the COLLECTION+// answers and which a `PublishXml` that names the row — or its table, or its app — copies the saved one to. A row that was+// never published is not in a plain collection read at all (the rule helpers/fake-app-build-org.js and+// helpers/fake-apps-org.js keep, measured).+// metadata tables, columns, keys, relationships and global option sets (helpers/fake-lifecycle-metadata.js). Creating a table makes+// what the platform makes with it: the system columns, the default views ("Active <plural>", "Inactive <plural>",+// Quick Find, Advanced Find, Lookup and Associated) and the Main form "Information". Deleting it removes them, its rows and+// its solution components.+// solution `solutions`, `publishers` and `solutioncomponents`: a component created with the `MSCRM.SolutionUniqueName` header or+// added with AddSolutionComponent is a row of that solution; a view, form or chart of a table the solution holds with all+// its subcomponents has no row of its own (helpers/fake-dataverse.js says why).+// pages the generative pages (`uxagentprojects`, their files and conversation), held by the stateful page fake the SDK's own+// tests drive (helpers/fake-genpage-server.js), which takes their writes, a file's bytes and a `PublishXml`; their reads+// are answered here from its state, so every query option a read carries is applied (pageRows, answerPageRead).+//+// The platform rules it keeps, and where each comes from. MEASURED or DOCUMENTED (the plugin's code or another fake records it):+// - a read BY ID answers the saved row with its current token (the SDK reads a form it just created that way), except an app module,+// whose read by id is its published projection — a draft app answers 404 (helpers/fake-apps-org.js);+// - a publish rotates the token of every row it names, changed or not (helpers/fake-dataverse.js, helpers/fake-genpage-server.js);+// - one default form per table and form type: making one the default takes the flag off the other;+// - an N:N link that exists is refused as a duplicate; an app's settings, and a role's grants, go with it when it is deleted;+// - a File or Image column is `AttributeType: "Virtual"` with `AttributeTypeName` FileType / ImageType (Microsoft Learn); an Image+// column is `AttributeOf` its `<name>id` and logical, and a table's first Image column becomes its primary image whatever the create+// sent (MEASURED on a live environment; helpers/fake-lifecycle-metadata.js has the whole shape);+// - a Money column's `<name>_base` twin has no AttributeOf, is not logical, is custom, and is told apart only by `IsBaseCurrency`+// (live-measured, pinned in download-model-app.test.js);+// - integer columns the SDK sends as text (`type: "0"`) are stored as numbers.+// ASSUMED, because nothing measured says otherwise (a LIVE CHECK can settle each one):+// - the app's publish also publishes the dashboards it holds — a dashboard has no table to publish it through, the build names+// none, and a built dashboard reads back published (helpers/dashboard-two-language-reads.js);+// - the Main form the platform makes for a new table has no form order (no `<DisplayConditions>`);+// - a duplicate status reason value or key name is refused with words that say "already exists" (the plugin matches on them);+// - the environment does not expose the business-rule designer's preview members (CreateProcessWithWfomJson), so the build skips+// business rules as it documents; their success path is not modelled.+//+// Anything it does not model is answered 501 AND recorded in `org.unexpected`, naming the request: a test asserts the list is empty,+// so a new read or write shows up as a loud failure in the test that first sends it — never as a silent empty answer that the code+// under test might read as "nothing there". For a READ that holds before a single row or definition is looked at: the whole path, every+// query option, every column or property it names (in `$select`, `$filter`, `$orderby`, `$expand`), every navigation, cast and filter+// function, every record key (a row is addressed by its id) and every function argument is checked against an explicit schema+// (RECORD_SCHEMA below; the metadata read contract in fake-lifecycle-metadata.js), so a read over an empty collection is refused exactly+// as one over a full one — and every option a read is allowed to carry is APPLIED to the answer, never accepted and ignored.+// fake-lifecycle-org-contract.test.js pins that boundary, and the values and row counts the accepted reads answer.+//+// What a test compares: `inventory()` names what exists (identities: create/delete), `contents()` what each artifact holds (saved and+// published layers, whole definitions, page files) — the proof that a command left everything it did not make as it found it.+//+// Every request is recorded, in order, in `org.requests` as `{ method, path, body, headers, status }` with the path below the API root,+// decoded, query included, and the HTTP status it was answered with; a `$batch` also carries its `operations` (each `{ method, path,+// body, headers }`), which run atomically.+const { randomUUID } = require('node:crypto');+const { compileFilter, describeFilter, evaluateFilter } = require('./odata-filter.js');+const { createMetadataStore } = require('./fake-lifecycle-metadata.js');+const { FakeGenPageServer, API: PAGE_API, sqlGuidOrder } = require('./fake-genpage-server.js');++const API_ROOT = /^\/api\/data\/v9\.\d/;+const GUID_TEXT = '[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}';+const clone = (value) => (value === undefined ? undefined : JSON.parse(JSON.stringify(value)));+const lc = (value) => String(value == null ? '' : value).toLowerCase();+const bare = (id) => lc(id).replace(/[{}]/g, '');++// The system tables whose rows the lifecycle reads or writes, by logical name: entity set, primary id and name columns, object type+// code, the solution component type, and — for a solution-aware row with two layers — the column that names its table.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/about-entity-reference+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent#componenttype-choicesoptions+const SYSTEM_TABLES = {+ solution: { set: 'solutions', id: 'solutionid', name: 'uniquename', otc: 7100 },+ publisher: { set: 'publishers', id: 'publisherid', name: 'uniquename', otc: 7101 },+ solutioncomponent: { set: 'solutioncomponents', id: 'solutioncomponentid', name: null, otc: 7103 },+ savedquery: { set: 'savedqueries', id: 'savedqueryid', name: 'name', otc: 1039, layered: true, tableColumn: 'returnedtypecode', componentType: 26 },+ systemform: { set: 'systemforms', id: 'formid', name: 'name', otc: 1030, layered: true, tableColumn: 'objecttypecode', componentType: 60 },+ savedqueryvisualization: { set: 'savedqueryvisualizations', id: 'savedqueryvisualizationid', name: 'name', otc: 1111, layered: true, tableColumn: 'primaryentitytypecode', componentType: 59 },+ appmodule: { set: 'appmodules', id: 'appmoduleid', name: 'name', otc: 9006, layered: true, componentType: 80 },+ appmodulecomponent: { set: 'appmodulecomponents', id: 'appmodulecomponentid', name: null, otc: 9007 },+ sitemap: { set: 'sitemaps', id: 'sitemapid', name: 'sitemapname', otc: 4709, layered: true, componentType: 62 },+ webresource: { set: 'webresourceset', id: 'webresourceid', name: 'name', otc: 9333, componentType: 61 },+ workflow: { set: 'workflows', id: 'workflowid', name: 'name', otc: 4703, componentType: 29 },+ appaction: { set: 'appactions', id: 'appactionid', name: 'name', otc: 10129 },+ role: { set: 'roles', id: 'roleid', name: 'name', otc: 1036, componentType: 20 },+ roleprivileges: { set: 'roleprivilegescollection', id: 'roleprivilegeid', name: null, otc: 1037 },+ privilege: { set: 'privileges', id: 'privilegeid', name: 'name', otc: 1023 },+ businessunit: { set: 'businessunits', id: 'businessunitid', name: 'name', otc: 10 },+ systemuser: { set: 'systemusers', id: 'systemuserid', name: 'fullname', otc: 8 },+ team: { set: 'teams', id: 'teamid', name: 'name', otc: 9 },+ organization: { set: 'organizations', id: 'organizationid', name: 'name', otc: 1019 },+ settingdefinition: { set: 'settingdefinitions', id: 'settingdefinitionid', name: 'uniquename', otc: 10050 },+ appsetting: { set: 'appsettings', id: 'appsettingid', name: 'uniquename', otc: 10051, layered: true },+ organizationsetting: { set: 'organizationsettings', id: 'organizationsettingid', name: 'uniquename', otc: 10052 },+ uxagentproject: { set: 'uxagentprojects', id: 'uxagentprojectid', name: 'name', otc: 10200, pages: true },+ uxagentprojectfile: { set: 'uxagentprojectfiles', id: 'uxagentprojectfileid', name: 'filename', otc: 10201, pages: true },+ agentconversationmessage: { set: 'agentconversationmessages', id: 'agentconversationmessageid', name: null, otc: 10202, pages: true },+ // The two stock tables a Customer column points at.+ account: { set: 'accounts', id: 'accountid', name: 'name', otc: 1, stock: true },+ contact: { set: 'contacts', id: 'contactid', name: 'fullname', otc: 2, stock: true },+};+const PAGE_PATH = /^\/(uxagentprojects|uxagentprojectfiles|agentconversationmessages)\b/;++// THE READ CONTRACT of the record half: the columns a read may name, per system table, EXPLICITLY — `fields` the platform always fills+// (the fake fills them too, and a row without one is the fake's own modelling gap, refused loudly), `nullable` the ones a row may leave+// empty (answered `null`). A lookup is its `_<name>_value` column; `lookups` names the table a lookup points at (a filter may follow it+// to that row's key, `parentrootroleid/roleid`), `navigations` the collection-valued navigations a read may follow (`$filter` lambdas,+// `/<set>(<id>)/<navigation>`), `expands` the lookups `$expand` may embed. A table the build creates — and the two stock tables a+// Customer column points at — takes its columns from its own definition instead (schemaOfTable). Every read is checked against this+// BEFORE any row is looked at: an unknown column, option, navigation or path is answered 501 and recorded in `org.unexpected`, so an+// empty collection can never stand in for "nothing there" when the read was never modelled.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/about-entity-reference+const AUDIT = ['createdon', 'modifiedon', 'versionnumber'];+const RECORD_SCHEMA = {+ solution: { fields: ['solutionid', 'uniquename', 'friendlyname', 'version', 'ismanaged', 'isvisible', '_publisherid_value', ...AUDIT], nullable: ['description'], lookups: { publisherid: 'publishers' }, expands: { publisherid: 'publishers' } },+ publisher: { fields: ['publisherid', 'uniquename', 'friendlyname', 'customizationprefix', 'customizationoptionvalueprefix', ...AUDIT], nullable: ['description'] },+ solutioncomponent: { fields: ['solutioncomponentid', '_solutionid_value', 'objectid', 'componenttype', ...AUDIT], nullable: ['rootcomponentbehavior'], lookups: { solutionid: 'solutions' } },+ savedquery: { fields: ['savedqueryid', 'name', 'returnedtypecode', 'querytype', 'isdefault', 'isquickfindquery', 'isprivate', 'fetchxml', 'layoutxml', 'statecode', 'statuscode', 'ismanaged', 'iscustomizable', 'canbedeleted', 'componentstate', ...AUDIT], nullable: ['description'] },+ systemform: { fields: ['formid', 'formidunique', 'name', 'objecttypecode', 'type', 'formxml', 'isdefault', 'formactivationstate', 'ismanaged', 'iscustomizable', 'canbedeleted', 'componentstate', ...AUDIT], nullable: ['description', 'formpresentation', 'istabletenabled', 'uniquename'] },+ savedqueryvisualization: { fields: ['savedqueryvisualizationid', 'name', 'primaryentitytypecode', 'datadescription', 'presentationdescription', 'isdefault', 'ismanaged', 'iscustomizable', 'canbedeleted', 'componentstate', ...AUDIT], nullable: ['description', 'charttype', 'type'] },+ appmodule: { fields: ['appmoduleid', 'appmoduleidunique', 'name', 'uniquename', 'clienttype', 'ismanaged', 'statecode', 'statuscode', 'componentstate', ...AUDIT], nullable: ['description', 'aiappdescription', 'webresourceid', 'formfactor', 'navigationtype'], navigations: { appmoduleroles_association: 'roles' } },+ appmodulecomponent: { fields: ['appmodulecomponentid', '_appmoduleidunique_value', 'objectid', 'componenttype', 'rootcomponentbehavior', ...AUDIT], nullable: [] },+ sitemap: { fields: ['sitemapid', 'sitemapidunique', 'sitemapname', 'sitemapnameunique', 'sitemapxml', 'ismanaged', 'componentstate', ...AUDIT], nullable: [] },+ webresource: { fields: ['webresourceid', 'name', 'displayname', 'webresourcetype', 'content', 'ismanaged', 'iscustomizable', 'canbedeleted', ...AUDIT], nullable: ['description'] },+ workflow: { fields: ['workflowid', 'name', 'category', 'type', 'primaryentity', 'statecode', 'statuscode', 'ismanaged', ...AUDIT], nullable: ['description', 'uniquename', 'xaml', 'clientdata', 'businessprocesstype', 'processorder', 'mode', 'scope'] },+ appaction: { fields: ['appactionid', 'name', 'uniquename', 'context', 'contextvalue', 'location', 'type', 'ismanaged', 'statecode', 'statuscode', ...AUDIT], nullable: ['buttonlabeltext', 'sequence', 'onclickeventtype', 'onclickeventjavascriptfunctionname', 'onclickeventjavascriptparameters', 'grouptitle', 'isgrouptitlehidden', '_contextentity_value', '_parentappactionid_value', '_onclickeventjavascriptwebresourceid_value'], lookups: { parentappactionid: 'appactions' } },+ role: { fields: ['roleid', 'name', '_businessunitid_value', '_parentrootroleid_value', 'ismanaged', 'iscustomizable', ...AUDIT], nullable: ['description', '_parentroleid_value', '_roletemplateid_value'], lookups: { businessunitid: 'businessunits', parentrootroleid: 'roles', parentroleid: 'roles' }, navigations: { appmoduleroles_association: 'appmodules' } },+ roleprivileges: { fields: ['roleprivilegeid', 'roleid', 'privilegeid', 'privilegedepthmask', ...AUDIT], nullable: [] },+ privilege: { fields: ['privilegeid', 'name', 'accessright', 'canbebasic', 'canbelocal', 'canbedeep', 'canbeglobal', ...AUDIT], nullable: [] },+ businessunit: { fields: ['businessunitid', 'name', ...AUDIT], nullable: ['_parentbusinessunitid_value'], lookups: { parentbusinessunitid: 'businessunits' } },+ systemuser: { fields: ['systemuserid', 'fullname', 'domainname', '_businessunitid_value', ...AUDIT], nullable: [], lookups: { businessunitid: 'businessunits' } },+ team: { fields: ['teamid', 'name', ...AUDIT], nullable: ['_businessunitid_value'], lookups: { businessunitid: 'businessunits' } },+ organization: { fields: ['organizationid', 'name', 'languagecode', ...AUDIT], nullable: [] },+ settingdefinition: { fields: ['settingdefinitionid', 'uniquename', 'displayname', 'datatype', 'defaultvalue', 'isoverridable', 'overridablelevel', ...AUDIT], nullable: [] },+ appsetting: { fields: ['appsettingid', '_parentappmoduleid_value', '_settingdefinitionid_value', 'value', 'componentstate', ...AUDIT], nullable: ['uniquename'], lookups: { parentappmoduleid: 'appmodules', settingdefinitionid: 'settingdefinitions' } },+ organizationsetting: { fields: ['organizationsettingid', '_settingdefinitionid_value', 'value', 'uniquename', ...AUDIT], nullable: [], lookups: { settingdefinitionid: 'settingdefinitions' } },+ // The page tables are answered by the page fake (helpers/fake-genpage-server.js); their reads are checked here before it sees them.+ uxagentproject: { fields: ['uxagentprojectid', 'name', 'versionnumber', 'componentstate'], nullable: ['description', 'createdon', 'modifiedon'] },+ uxagentprojectfile: { fields: ['uxagentprojectfileid', 'filename', 'filetype', '_uxagentprojectid_value', 'versionnumber'], nullable: ['createdon', 'modifiedon'], lookups: { uxagentprojectid: 'uxagentprojects' } },+ agentconversationmessage: { fields: ['agentconversationmessageid', 'message', 'messagesender', '_regardingobjectid_value', 'createdon', 'versionnumber'], nullable: ['messagecontext', 'modifiedon'], lookups: { regardingobjectid: 'uxagentprojects' } },+};+// The query options each kind of read takes.+const READ_OPTIONS = {+ collection: ['$select', '$filter', '$orderby', '$top', '$expand'],+ single: ['$select', '$expand'],+ navigation: ['$select', '$filter', '$orderby', '$top'],+ unpublished: ['$select'],+ unpublishedMany: ['$select', '$filter', '$orderby', '$top'],+ write: ['$select'],+};++// The fixed ids a fresh environment hands out, so a test can name them.+const IDS = {+ organization: '11111111-0000-4000-8000-000000000001',+ businessUnit: '11111111-0000-4000-8000-000000000002',+ user: '11111111-0000-4000-8000-000000000003',+ defaultPublisher: '11111111-0000-4000-8000-000000000004',+ defaultSolution: '11111111-0000-4000-8000-000000000005',+ systemAdministrator: '11111111-0000-4000-8000-000000000006',+ basicUser: '11111111-0000-4000-8000-000000000007',+};++class Unmodelled extends Error {}++function createLifecycleOrg(options = {}) {+ const origin = options.origin || 'https://contoso.crm.dynamics.com';+ const API = `${origin}/api/data/v9.0`;+ const baseLanguage = options.baseLanguage || 1033;+ const requests = [];+ const unexpected = [];+ let rowVersion = 5000;+ const nextVersion = () => { rowVersion += 1; return rowVersion; };++ // Answers. The transport the plugin's client takes answers `{ statusCode, headers, body }` with the body as TEXT.+ const json = (statusCode, body, headers = {}) => ({ statusCode, headers: { 'content-type': 'application/json; odata.metadata=minimal', 'odata-version': '4.0', ...headers }, body: body === undefined ? '' : JSON.stringify(body) });+ const noContent = (headers = {}) => ({ statusCode: 204, headers: { 'odata-version': '4.0', ...headers }, body: '' });+ const failure = (statusCode, code, message) => json(statusCode, { error: { code, message } });++ // ---------------------------------------------------------------------------------------------------------------------------+ // Rows. `data` is the saved layer; `published` the published layer of a layered kind (null until a publish copies it).+ const sets = new Map(); // entity set -> Map<id, row>+ const associations = []; // { set, id, nav, toSet, toId }+ const publishes = []; // { entities: [], apps: [], other: [] } per PublishXml, PublishAllXml as { all: true }++ const metadata = createMetadataStore({+ baseLanguage,+ addComponent: (solutionName, component) => addComponentByName(solutionName, component),+ removeComponents: (ids) => removeComponents(ids),+ onTableCreated: (table, solutionName) => tableCreated(table, solutionName),+ onTableDeleted: (table) => tableDeleted(table),+ });++ const tableInfo = (logical) => {+ const system = SYSTEM_TABLES[logical];+ if (system) return { logical, ...system };+ const t = metadata.tables.get(logical);+ return t ? { logical, set: t.EntitySetName, id: t.PrimaryIdAttribute, name: t.PrimaryNameAttribute, otc: t.ObjectTypeCode } : null;+ };+ const infoOfSet = (set) => {+ for (const [logical, t] of Object.entries(SYSTEM_TABLES)) if (t.set === set) return { logical, ...t };+ for (const t of metadata.tables.values()) if (t.EntitySetName === set) return tableInfo(t.LogicalName);+ return null;+ };+ const rowsOf = (set) => {+ if (!sets.has(set)) sets.set(set, new Map());+ return sets.get(set);+ };+ function insertRow(set, data, { published = false } = {}) {+ const info = infoOfSet(set);+ const id = bare(data[info.id] || randomUUID());+ const version = nextVersion();+ // Every row carries its creation time; the platform's default views of a table are made together, which is how the SDK tells+ // the generated "Active"/"Inactive" pair from other views (helpers/fake-dataverse.js seedDefaultViews does the same).+ const row = { set, id, data: { createdon: '2026-10-01T00:00:00Z', modifiedon: '2026-10-01T00:00:00Z', ...clone(data), [info.id]: id, versionnumber: version }, version, published: null, publishedVersion: null };+ rowsOf(set).set(id, row);+ if (published) publishRow(row);+ return row;+ }+ // A publish copies the saved layer to the published one and MOVES the row's token (measured: the SDK re-baselines the copies it+ // holds after a publish of its own because the platform rotates them; helpers/fake-dataverse.js `publishBumpsVersion`,+ // helpers/fake-genpage-server.js publishProject) — so a copy held across a publish the SDK did not make is stale.+ function publishRow(row) {+ const info = infoOfSet(row.set);+ if (!info || !info.layered) return;+ // Every row the publish names rotates, changed or not ("it rotates the project's token and EVERY row's", measured for pages; the+ // views, forms and charts of a published table likewise).+ row.version = nextVersion();+ row.data.versionnumber = row.version;+ row.published = clone(row.data);+ row.publishedVersion = row.version;+ }+ const isLayered = (set) => !!(infoOfSet(set) || {}).layered;++ // ---------------------------------------------------------------------------------------------------------------------------+ // Solution components. A table is held with all its subcomponents (rootcomponentbehavior 0) when the build creates it in the+ // solution; its views, forms and charts then have no row of their own (see the header).+ const solutionByName = (name) => [...rowsOf('solutions').values()].find((row) => lc(row.data.uniquename) === lc(name));+ // A component row, as `solutioncomponents` answers it: `{ solutioncomponentid, _solutionid_value, objectid, componenttype,+ // rootcomponentbehavior }` (`rootcomponentbehavior` 0 Include Subcomponents, 1 Do not include, 2 Shell; null on any other kind).+ const componentRows = () => [...rowsOf('solutioncomponents').values()];+ function addComponent(solutionId, { objectid, componenttype, rootcomponentbehavior = null }) {+ const id = bare(objectid);+ if (componentRows().some((c) => bare(c.data._solutionid_value) === solutionId && bare(c.data.objectid) === id && c.data.componenttype === componenttype)) return;+ if ([26, 59, 60].includes(componenttype)) {+ const owner = ownerTableOf(componenttype, id);+ const table = owner && metadata.tables.get(owner);+ if (table && componentRows().some((c) => bare(c.data._solutionid_value) === solutionId && c.data.componenttype === 1 && bare(c.data.objectid) === bare(table.MetadataId) && c.data.rootcomponentbehavior === 0)) return;+ }+ insertRow('solutioncomponents', { _solutionid_value: solutionId, objectid: id, componenttype, rootcomponentbehavior: componenttype === 1 ? rootcomponentbehavior : null });+ }+ function addComponentByName(solutionName, component) {+ if (!solutionName) return;+ const solution = solutionByName(solutionName);+ if (!solution) throw new Unmodelled(`the solution ${solutionName} named by MSCRM.SolutionUniqueName does not exist`);+ addComponent(solution.id, component);+ }+ // A component that is deleted leaves every solution that held it.+ function removeComponents(ids) {+ const gone = new Set(ids.map(bare));+ for (const c of componentRows()) if (gone.has(bare(c.data.objectid))) rowsOf('solutioncomponents').delete(c.id);+ }+ function ownerTableOf(componenttype, id) {+ const set = { 26: 'savedqueries', 59: 'savedqueryvisualizations', 60: 'systemforms' }[componenttype];+ const row = set && rowsOf(set).get(bare(id));+ return row ? row.data[infoOfSet(set).tableColumn] : null;+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // What a new table comes with: its default views and its Main form, published, not deletable (views) — as the platform makes them.+ const labelText = (stored) => (stored && stored.UserLocalizedLabel ? stored.UserLocalizedLabel.Label : '');+ const classIds = { text: '{4273EDBD-AC1D-40d3-9FB2-095C621B552D}', lookup: '{270BD3DB-D9AF-4782-9025-509E298DEC0A}' };+ const braced = () => `{${randomUUID()}}`;+ function tableCreated(table) {+ recordPrivileges(table);+ if (table.IsIntersect) return;+ const logical = table.LogicalName;+ const plural = labelText(table.DisplayCollectionName) || logical;+ const primary = table.PrimaryNameAttribute;+ const fetch = (extra = '') => `<fetch version="1.0" mapping="logical"><entity name="${logical}"><attribute name="${primary}" /><attribute name="createdon" /><order attribute="${primary}" descending="false" />${extra}<attribute name="${table.PrimaryIdAttribute}" /></entity></fetch>`;+ const state = (value) => `<filter type="and"><condition attribute="statecode" operator="eq" value="${value}" /></filter>`;+ const layout = `<grid name="resultset" object="${table.ObjectTypeCode}" jump="${primary}" select="1" icon="1" preview="1"><row name="result" id="${table.PrimaryIdAttribute}"><cell name="${primary}" width="300" /><cell name="createdon" width="125" /></row></grid>`;+ const view = (name, querytype, extra = {}) => insertRow('savedqueries', { name, description: '', returnedtypecode: logical, querytype, isdefault: false, isquickfindquery: querytype === 4, iscustomizable: { Value: true, CanBeChanged: true }, canbedeleted: { Value: false, CanBeChanged: false }, isprivate: false, ismanaged: false, fetchxml: fetch(querytype === 0 || querytype === 4 ? state(extra.state || 0) : ''), layoutxml: layout, statecode: 0, statuscode: 1, ...extra.data }, { published: true });+ view(`Active ${plural}`, 0, { data: { isdefault: true } });+ view(`Inactive ${plural}`, 0, { state: 1 });+ view(`Quick Find Active ${plural}`, 4, { data: { isdefault: true } });+ view(`${plural} Advanced Find View`, 1, { data: { isdefault: true } });+ view(`${plural} Lookup View`, 64, { data: { isdefault: true } });+ view(`${plural} Associated View`, 2, { data: { isdefault: true } });+ const cell = (column, text, classid) => `<row><cell id="${braced()}"><labels><label description="${text}" languagecode="${baseLanguage}" /></labels><control id="${column}" classid="${classid}" datafieldname="${column}" /></cell></row>`;+ // The Main form the platform makes has no form order (no `<DisplayConditions>`), so a form the build orders is served before it+ // (lib/form-order.js). Were it to carry `Order="0"`, every build that declares a Main form for a new table would warn that the+ // stock form may open first.+ const formxml = `<form><tabs><tab verticallayout="true" id="${braced()}" IsUserDefined="1"><labels><label description="General" languagecode="${baseLanguage}" /></labels><columns><column width="100%"><sections><section showlabel="false" showbar="false" IsUserDefined="0" id="${braced()}"><labels><label description="General" languagecode="${baseLanguage}" /></labels><rows>${cell(primary, labelText((table.Attributes.get(primary) || {}).DisplayName) || 'Name', classIds.text)}${cell('ownerid', 'Owner', classIds.lookup)}</rows></section></sections></column></columns></tab></tabs></form>`;+ insertRow('systemforms', { name: 'Information', description: 'A form for this entity.', objecttypecode: logical, type: 2, isdefault: true, formactivationstate: 1, formpresentation: 1, ismanaged: false, formidunique: randomUUID(), iscustomizable: { Value: true, CanBeChanged: true }, canbedeleted: { Value: true, CanBeChanged: true }, formxml }, { published: true });+ }+ // Deleting a table takes its rows, views, forms, charts and privileges (and every role's grant of them) with it.+ function tableDeleted(table) {+ const logical = table.LogicalName;+ const privilegeIds = new Set((table.Privileges || []).map((p) => bare(p.PrivilegeId)));+ for (const id of privilegeIds) rowsOf('privileges').delete(id);+ for (const [id, row] of [...rowsOf('roleprivilegescollection')]) if (privilegeIds.has(bare(row.data.privilegeid))) rowsOf('roleprivilegescollection').delete(id);+ for (const set of ['savedqueries', 'systemforms', 'savedqueryvisualizations']) {+ const column = infoOfSet(set).tableColumn;+ for (const [id, row] of [...rowsOf(set)]) if (row.data[column] === logical) { rowsOf(set).delete(id); removeComponents([id]); }+ }+ sets.delete(table.EntitySetName);+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // PublishXml: the rows it names go live. `<entities>` publishes a table's views, forms and charts; `<appmodules>` an app, its site map+ // and its settings; `<sitemaps>` and `<dashboards>` the rows they name. Web resources, option sets and relationships have no second+ // layer here: nothing to copy.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/publishxml+ function publishXml(xml) {+ const names = (outer, inner) => [...String(xml).matchAll(new RegExp(`<${outer}>([\\s\\S]*?)</${outer}>`, 'g'))]+ .flatMap((m) => [...m[1].matchAll(new RegExp(`<${inner}>([^<]+)</${inner}>`, 'g'))].map((x) => x[1].trim()));+ const entities = names('entities', 'entity').map(lc);+ const apps = names('appmodules', 'appmodule').map(bare);+ const sitemaps = names('sitemaps', 'sitemap').map(bare);+ const dashboards = names('dashboards', 'dashboard').map(bare);+ publishes.push({ entities, apps, sitemaps, dashboards, xml: String(xml) });+ for (const set of ['savedqueries', 'systemforms', 'savedqueryvisualizations']) {+ const column = infoOfSet(set).tableColumn;+ for (const row of rowsOf(set).values()) if (entities.includes(lc(row.data[column]))) publishRow(row);+ }+ for (const id of dashboards) { const row = rowsOf('systemforms').get(id); if (row) publishRow(row); }+ for (const id of sitemaps) { const row = rowsOf('sitemaps').get(id); if (row) publishRow(row); }+ for (const id of apps) {+ const app = rowsOf('appmodules').get(id);+ if (!app) continue;+ publishRow(app);+ for (const c of appComponentsOf(app)) {+ if (c.data.componenttype === 62) { const sm = rowsOf('sitemaps').get(bare(c.data.objectid)); if (sm) publishRow(sm); }+ // A dashboard is a form of no table (`objecttypecode` none), so no table's publish can name it, and the build names none+ // itself: the app's publish publishes the dashboards the app holds. (Measured around it: a PublishXml that names only the+ // app changes what the app's forms publish — publish-scope-real-bundle.test.js — and a dashboard the build made reads back+ // published afterwards — helpers/dashboard-two-language-reads.js.)+ if (c.data.componenttype === 60) { const form = rowsOf('systemforms').get(bare(c.data.objectid)); if (form && Number(form.data.type) === 0) publishRow(form); }+ }+ for (const s of rowsOf('appsettings').values()) if (bare(s.data._parentappmoduleid_value) === id) publishRow(s);+ }+ }+ function publishAll() {+ publishes.push({ all: true });+ for (const set of sets.keys()) for (const row of rowsOf(set).values()) publishRow(row);+ }+ const appComponentsOf = (app) => [...rowsOf('appmodulecomponents').values()].filter((c) => bare(c.data._appmoduleidunique_value) === bare(app.data.appmoduleidunique));++ // ---------------------------------------------------------------------------------------------------------------------------+ // The read contract (RECORD_SCHEMA above): what a set's rows hold, and the check every read passes before a row is looked at.+ const listOf = (text) => String(text).split(',').map((x) => x.trim()).filter(Boolean);+ // A row is addressed by its id. An alternate-key expression (`/accounts(accountnumber='x')`, `/solutions(Unknown='x')`) or any other+ // text in a key's place is not modelled: it is refused, never resolved as an id that "does not exist" (a 404 would prove an absence+ // nothing measured).+ const GUID_KEY = new RegExp(`^${GUID_TEXT}$`);+ const idOf = (key, where) => {+ if (!GUID_KEY.test(String(key))) throw new Unmodelled(`the key (${key}) on ${where} is not modelled: a row is addressed by its id`);+ return bare(key);+ };+ function schemaOf(set) {+ const info = infoOfSet(set);+ if (!info) throw new Unmodelled(`no table has the entity set ${set}`);+ const explicit = RECORD_SCHEMA[info.logical];+ if (explicit) {+ return { info, fields: new Set(explicit.fields), nullable: new Set(explicit.nullable), lookups: explicit.lookups || {}, navigations: explicit.navigations || {}, expands: explicit.expands || {} };+ }+ const table = metadata.tables.get(info.logical);+ if (!table) throw new Unmodelled(`the table of ${set} has no definition`);+ return schemaOfTable(table, info);+ }+ // A table's columns come from its own definition: a lookup (a Customer and an Owner too) is read as `_<name>_value`; a companion+ // (`AttributeOf`, e.g. a lookup's `<name>name`) is an annotation, not a column a read selects. What the platform always fills on a+ // row of it: its key, the audit columns, its state and status.+ function schemaOfTable(table, info) {+ const fields = new Set([table.PrimaryIdAttribute, 'createdon', 'modifiedon', 'versionnumber', 'statecode', 'statuscode']);+ const nullable = new Set();+ const lookups = {};+ for (const a of table.Attributes.values()) {+ if (a.AttributeOf) continue;+ const isLookup = ['Lookup', 'Customer', 'Owner'].includes(a.AttributeType);+ const name = isLookup ? `_${a.LogicalName}_value` : a.LogicalName;+ if (isLookup && Array.isArray(a.Targets) && a.Targets.length === 1) {+ const target = tableInfo(a.Targets[0]);+ if (target) lookups[a.LogicalName] = target.set;+ }+ if (!fields.has(name)) nullable.add(name);+ }+ return { info, fields, nullable, lookups, navigations: {}, expands: {} };+ }+ const knows = (schema, name) => schema.fields.has(name) || schema.nullable.has(name);+ // Refuses — before any row is enumerated — a read that names anything the set does not have: an option, a column (in `$select`,+ // `$orderby` or `$filter`), a navigation (a lambda, a path to a lookup's row, an `$expand`), a filter function. The filter is parsed+ // here, once, so an empty collection checks it exactly as a full one does. Answers what the read then needs: the schema, the parsed+ // filter with the columns it reads that the platform always fills, and the expands.+ function checkRead(set, query, kind, where) {+ const schema = schemaOf(set);+ for (const option of Object.keys(query || {})) if (!READ_OPTIONS[kind].includes(option)) throw new Unmodelled(`the query option ${option} is not modelled on ${where}`);+ const column = (name, clause) => { if (!knows(schema, name)) throw new Unmodelled(`${schema.info.logical} has no column ${name} (${clause} on ${where})`); };+ if (query.$select !== undefined) for (const name of listOf(query.$select)) column(name, '$select');+ if (query.$orderby !== undefined) {+ for (const item of listOf(query.$orderby)) {+ const [name, dir, ...extra] = item.split(/\s+/);+ if (extra.length || (dir && !/^(asc|desc)$/i.test(dir))) throw new Unmodelled(`$orderby=${query.$orderby} on ${where}`);+ column(name, '$orderby');+ }+ }+ if (query.$top !== undefined && !/^\d+$/.test(query.$top)) throw new Unmodelled(`$top=${query.$top} on ${where}`);+ const expands = query.$expand !== undefined ? expandsOf(schema, query.$expand, where) : [];+ let filter = null;+ if (query.$filter !== undefined) {+ const ast = compileFilter(query.$filter);+ const read = describeFilter(ast);+ for (const name of read.fields) column(name, '$filter');+ for (const path of read.paths) {+ const target = schema.lookups[path.navigation];+ if (!target || !knows(schema, `_${path.navigation}_value`) || path.field !== infoOfSet(target).id) throw new Unmodelled(`the navigation path ${path.navigation}/${path.field} is not modelled on ${where}`);+ }+ for (const lambda of read.lambdas) {+ const target = schema.navigations[lambda.navigation];+ if (!target) throw new Unmodelled(`${schema.info.logical} has no navigation ${lambda.navigation} ($filter on ${where})`);+ const related = schemaOf(target);+ for (const name of lambda.fields) if (!knows(related, name)) throw new Unmodelled(`${related.info.logical} has no column ${name} (${lambda.navigation}/${lambda.op} on ${where})`);+ }+ filter = { ast, required: read.fields.filter((name) => !schema.nullable.has(name)) };+ }+ return { schema, filter, expands };+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // Rows as a read answers them: `$select` narrows the columns (the primary key and `@odata.etag` always come back); a lookup is read+ // as `_<name>_value`. A plain read of a layered row answers its published layer; RetrieveUnpublished* its saved one, with+ // `componentstate`: 0 when no publish is owed, 1 when one is. A selected column the row does not hold is `null` when the platform+ // lets it be empty, and refused otherwise: the platform would have filled it, and the fake does not model how.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/select-columns+ function shape(row, data, query, info, { saved = false } = {}) {+ const full = { ...data, '@odata.etag': etagOf(saved ? row.version : (row.publishedVersion || row.version)) };+ if (info.layered) full.componentstate = saved ? (row.publishedVersion === row.version ? 0 : 1) : 0;+ if (!query.$select) return full;+ return selectColumns(schemaOf(row.set), full, query, { '@odata.etag': full['@odata.etag'], [info.id]: full[info.id] });+ }+ // `$select` over one row: `extra` (the key, the token) always comes back, then each selected column — `null` when the platform lets it+ // be empty and the row holds none, refused when the platform always fills it (the fake does not model how it would be set).+ function selectColumns(schema, full, query, extra) {+ const out = { ...extra };+ for (const name of listOf(query.$select)) {+ if (full[name] !== undefined && full[name] !== null) out[name] = full[name];+ else if (schema.nullable.has(name)) out[name] = null;+ else throw new Unmodelled(`${schema.info.logical} ${full[schema.info.id]} holds no ${name}, which the platform always fills`);+ }+ return out;+ }+ // The checked `$filter`, `$orderby` and `$top` over a list (each item read as `dataOf(item)`), the same for records and page rows:+ // a column the filter reads that the platform always fills must be there; the order is stable, so rows that tie keep the order the+ // list came in (the platform's own order for its set).+ function applyQuery(items, dataOf, query, checked, where, navigate) {+ const { schema, filter } = checked;+ let list = items;+ if (filter) {+ list = list.filter((item) => {+ const data = dataOf(item);+ for (const name of filter.required) if (data[name] === undefined || data[name] === null) throw new Unmodelled(`${schema.info.logical} ${data[schema.info.id]} holds no ${name}, which the platform always fills ($filter on ${where})`);+ return evaluateFilter(filter.ast, data, { navigate });+ });+ }+ if (query.$orderby !== undefined) {+ const keys = listOf(query.$orderby).map((item) => { const [field, dir] = item.split(/\s+/); return { field, sign: lc(dir) === 'desc' ? -1 : 1 }; });+ list = [...list].sort((a, b) => {+ for (const { field, sign } of keys) {+ const x = dataOf(a)[field];+ const y = dataOf(b)[field];+ if (x !== y) return (x == null ? -1 : y == null ? 1 : x > y ? 1 : -1) * sign;+ }+ return 0;+ });+ }+ if (query.$top !== undefined) list = list.slice(0, Number(query.$top));+ return list;+ }+ const etagOf = (version) => `W/"${version}"`;+ const readRows = (set, query, options = {}) => answerRows(set, [...rowsOf(set).values()], query, options);+ // The rows a read answers, out of `candidates` (a whole set, or the rows a navigation links): checked, filtered, ordered, cut, shaped.+ function answerRows(set, candidates, query, { saved = false, kind = 'collection', where = `/${set}` } = {}) {+ const checked = checkRead(set, query, kind, where);+ const { info } = checked.schema;+ const layered = !!info.layered;+ // A lambda over an N:N navigation (`appmoduleroles_association/any(x:x/roleid eq <id>)`) follows the row's links.+ const navigate = (data, nav) => {+ const id = bare(data[info.id]);+ const out = [];+ for (const a of associations) {+ if (a.nav !== nav) continue;+ if (a.set === set && a.id === id) out.push((rowsOf(a.toSet).get(a.toId) || {}).data);+ else if (a.toSet === set && a.toId === id) out.push((rowsOf(a.set).get(a.id) || {}).data);+ }+ return out.filter(Boolean);+ };+ const items = candidates+ .map((row) => ({ row, data: layered && !saved ? row.published : row.data }))+ .filter((x) => x.data)+ .map((x) => ({ ...x, read: layered ? { ...x.data, componentstate: saved && x.row.publishedVersion !== x.row.version ? 1 : 0 } : x.data }));+ return applyQuery(items, (x) => x.read, query, checked, where, navigate)+ .map((x) => withExpands(shape(x.row, x.data, query, info, { saved }), x.data, checked.expands));+ }++ // `$expand` of a single-valued navigation — a lookup — embeds the row it points at, with its own `$select`:+ // /solutions?$select=solutionid,uniquename&$expand=publisherid($select=publisherid,customizationprefix)+ // -> { "solutionid": "…", "uniquename": "…", "publisherid": { "publisherid": "…", "customizationprefix": "contoso" } }+ // The navigations modelled are the lookups the lifecycle expands (RECORD_SCHEMA `expands`); any other is refused by name.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/join-tables#expand-many-to-one-relationships+ function expandsOf(schema, text, where) {+ return metadata.parseExpand(text).map((item) => {+ const target = schema.expands[item.name];+ if (!target) throw new Unmodelled(`$expand=${item.name} on ${where} is not modelled`);+ for (const option of Object.keys(item.opts)) if (option !== '$select') throw new Unmodelled(`$expand=${item.name}(${option}) on ${where} is not modelled`);+ const related = schemaOf(target);+ if (item.opts.$select !== undefined) for (const name of listOf(item.opts.$select)) if (!knows(related, name)) throw new Unmodelled(`${related.info.logical} has no column ${name} ($expand=${item.name} on ${where})`);+ return { ...item, target };+ });+ }+ function withExpands(out, data, expands) {+ for (const e of expands) {+ const id = data[`_${e.name}_value`];+ const row = id && rowsOf(e.target).get(bare(id));+ out[e.name] = row ? shape(row, row.data, e.opts, infoOfSet(e.target), { saved: true }) : null;+ }+ return out;+ }++ // `"[email protected]": "/appmodules(<id>)"` -> `_parentappmoduleid_value: <id>`. The name before `@odata.bind` is the+ // lookup's navigation property: the lookup's own name for a single-target lookup (`[email protected]` sets+ // `contoso_parentid`), and `<lookup>_<table>` for a polymorphic one (`[email protected]` sets `regardingobjectid`).+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/associate-disassociate-entities-using-web-api#associate-entity-records-on-create+ function bindLookups(set, body) {+ const info = infoOfSet(set);+ const table = info && metadata.tables.get(info.logical);+ const out = {};+ for (const [key, value] of Object.entries(body || {})) {+ const bind = /^(.+)@odata\.bind$/.exec(key);+ if (!bind) { out[key] = clone(value); continue; }+ const target = /\/?([A-Za-z_]\w*)\(([^)]+)\)$/.exec(String(value || ''));+ if (!target) throw new Unmodelled(`cannot read the bind ${key}: ${value}`);+ const targetId = idOf(target[2], `the bind ${key}`);+ let name = lc(bind[1]);+ if (table && !table.Attributes.has(name)) {+ const poly = /^(.+)_[a-z0-9]+$/.exec(name);+ if (poly && table.Attributes.has(poly[1])) name = poly[1];+ }+ out[`_${name}_value`] = targetId;+ }+ return out;+ }++ const ifMatchOf = (headers) => Object.entries(headers || {}).find(([k]) => lc(k) === 'if-match');+ // The option-set and whole-number columns of the system tables the SDK writes with a TEXT value (a dashboard's `type` comes as "0"):+ // the platform stores the number, so a filter `type eq 0` finds it.+ const INTEGER_COLUMNS = new Set(['type', 'formactivationstate', 'formpresentation', 'querytype', 'statecode', 'statuscode', 'category', 'mode', 'scope', 'webresourcetype', 'componenttype', 'rootcomponentbehavior', 'location', 'clienttype', 'navigationtype', 'charttype', 'businessprocesstype', 'processorder', 'datatype']);+ const coerce = (data) => Object.fromEntries(Object.entries(data).map(([k, v]) => [k, INTEGER_COLUMNS.has(k) && typeof v === 'string' && /^-?\d+$/.test(v) ? Number(v) : v]));+ const ifNoneMatchOf = (headers) => Object.entries(headers || {}).find(([k]) => lc(k) === 'if-none-match');+ const preferOf = (headers) => (Object.entries(headers || {}).find(([k]) => lc(k) === 'prefer') || [])[1] || '';+ const solutionHeader = (headers) => (Object.entries(headers || {}).find(([k]) => lc(k) === 'mscrm.solutionuniquename') || [])[1] || null;++ // The columns the platform fills in on a create, by entity set: a solution-aware row's unique-layer id and managed state, a form's+ // activation state, a view's and a form's managed properties and default flag (false until one is made the default).+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule#BKMK_AppModuleIdUnique+ const CREATE_DEFAULTS = {+ appmodules: () => ({ appmoduleidunique: randomUUID(), ismanaged: false, statecode: 0, statuscode: 1 }),+ sitemaps: () => ({ sitemapidunique: randomUUID(), ismanaged: false }),+ savedqueries: () => ({ ismanaged: false, iscustomizable: { Value: true, CanBeChanged: true }, canbedeleted: { Value: true, CanBeChanged: true }, statecode: 0, statuscode: 1, isprivate: false, isdefault: false, isquickfindquery: false }),+ systemforms: () => ({ ismanaged: false, iscustomizable: { Value: true, CanBeChanged: true }, canbedeleted: { Value: true, CanBeChanged: true }, formactivationstate: 1, formidunique: randomUUID(), isdefault: false }),+ savedqueryvisualizations: () => ({ ismanaged: false, iscustomizable: { Value: true, CanBeChanged: true }, canbedeleted: { Value: true, CanBeChanged: true } }),+ webresourceset: () => ({ ismanaged: false, iscustomizable: { Value: true, CanBeChanged: true }, canbedeleted: { Value: true, CanBeChanged: true } }),+ workflows: () => ({ ismanaged: false, statecode: 0, statuscode: 1 }),+ roles: () => ({ ismanaged: false, iscustomizable: { Value: true, CanBeChanged: true } }),+ solutions: () => ({ ismanaged: false, isvisible: true }),+ appactions: () => ({ ismanaged: false, statecode: 0, statuscode: 1 }),+ };++ function createRow(set, body, headers, query = {}) {+ const info = infoOfSet(set);+ if (!info) throw new Unmodelled(`no table has the entity set ${set}`);+ const data = { ...(CREATE_DEFAULTS[set] ? CREATE_DEFAULTS[set]() : {}), ...coerce(bindLookups(set, body)) };+ // A dashboard is a form of no table: the platform stores `objecttypecode` "none" for it.+ if (set === 'systemforms' && Number(data.type) === 0 && !data.objecttypecode) data.objecttypecode = 'none';+ const id = bare(data[info.id] || randomUUID());+ if (rowsOf(set).has(id)) return failure(412, '0x80040237', 'A record with matching key values already exists.');+ // A role of the root business unit is its own `parentrootroleid` (the stock roles are seeded so); a row of a table with a state+ // starts Active (statecode 0) with that state's default status (1) unless the request names another.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/role#BKMK_ParentRootRoleId+ if (set === 'roles' && data._parentrootroleid_value === undefined) data._parentrootroleid_value = id;+ const definition = (!SYSTEM_TABLES[info.logical] || SYSTEM_TABLES[info.logical].stock) && metadata.tables.get(info.logical);+ if (definition && definition.Attributes.has('statecode')) {+ if (data.statecode === undefined) data.statecode = 0;+ if (data.statuscode === undefined) data.statuscode = 1;+ }+ const row = insertRow(set, { ...data, [info.id]: id, createdon: '2026-10-01T00:00:00Z', modifiedon: '2026-10-01T00:00:00Z' });+ const solution = solutionHeader(headers);+ if (solution && info.componentType) addComponentByName(solution, { objectid: id, componenttype: info.componentType });+ const location = `${API}/${set}(${id})`;+ // `Prefer: return=representation` answers the row as created — narrowed by the request's `$select`, as a read would be.+ if (/return=representation/i.test(preferOf(headers))) return json(201, shape(row, row.data, query, info, { saved: true }), { 'odata-entityid': location, etag: etagOf(row.version) });+ return noContent({ 'odata-entityid': location, etag: etagOf(row.version) });+ }++ function updateRow(set, id, body, headers, query = {}) {+ const info = infoOfSet(set);+ if (!info) throw new Unmodelled(`no table has the entity set ${set}`);+ const row = rowsOf(set).get(bare(id));+ const ifMatch = ifMatchOf(headers);+ const ifNoneMatch = ifNoneMatchOf(headers);+ if (!row) {+ if (ifMatch) return failure(404, '0x80040217', `${info.logical} With Id = ${id} Does Not Exist`);+ // A PATCH without a precondition is an UPSERT: it creates the row it names.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api#prevent-create-in-upsert+ return createRow(set, { ...body, [info.id]: bare(id) }, headers, query);+ }+ if (ifNoneMatch && ifNoneMatch[1] === '*') return failure(412, '0x80040237', 'A record with matching key values already exists.');+ if (ifMatch && ifMatch[1] !== '*' && ifMatch[1] !== etagOf(row.version)) return failure(412, '0x80060882', "The version of the existing record doesn't match the RowVersion property provided.");+ Object.assign(row.data, coerce(bindLookups(set, body)), { modifiedon: '2026-10-01T00:00:01Z' });+ row.version = nextVersion();+ row.data.versionnumber = row.version;+ // A table has ONE default form of each type: making a form the default takes the flag off the one that had it (the teardown's+ // restore of the stock Main form relies on that to demote the build's form — sdk-teardown.js restoreStockMainForm).+ if (set === 'systemforms' && body && body.isdefault === true) {+ for (const other of rowsOf('systemforms').values()) {+ if (other.id === row.id || other.data.objecttypecode !== row.data.objecttypecode || Number(other.data.type) !== Number(row.data.type) || other.data.isdefault !== true) continue;+ other.data.isdefault = false;+ other.version = nextVersion();+ other.data.versionnumber = other.version;+ }+ }+ if (/return=representation/i.test(preferOf(headers))) return json(200, shape(row, row.data, query, info, { saved: true }), { etag: etagOf(row.version) });+ return noContent({ 'odata-entityid': `${API}/${set}(${row.id})`, etag: etagOf(row.version) });+ }++ function deleteRow(set, id) {+ const info = infoOfSet(set);+ if (!info) throw new Unmodelled(`no table has the entity set ${set}`);+ const row = rowsOf(set).get(bare(id));+ if (!row) return failure(404, '0x80040217', `${info.logical} With Id = ${id} Does Not Exist`);+ rowsOf(set).delete(row.id);+ removeComponents([row.id]);+ for (const c of [...rowsOf('appmodulecomponents').values()]) if (bare(c.data.objectid) === row.id) rowsOf('appmodulecomponents').delete(c.id);+ for (let i = associations.length - 1; i >= 0; i -= 1) if (associations[i].id === row.id || associations[i].toId === row.id) associations.splice(i, 1);+ // A role's grants (`roleprivileges` rows) go with it.+ if (set === 'roles') for (const [rid, grant] of [...rowsOf('roleprivilegescollection')]) if (bare(grant.data.roleid) === row.id) rowsOf('roleprivilegescollection').delete(rid);+ // Deleting an unmanaged solution deletes the container and its component rows; the components themselves stay.+ if (set === 'solutions') for (const c of componentRows()) if (bare(c.data._solutionid_value) === row.id) rowsOf('solutioncomponents').delete(c.id);+ if (set === 'appmodules') {+ for (const c of [...rowsOf('appmodulecomponents').values()]) if (bare(c.data._appmoduleidunique_value) === bare(row.data.appmoduleidunique)) rowsOf('appmodulecomponents').delete(c.id);+ // An app's settings are part of it (`appsetting.parentappmoduleid` is a parental relationship): they go with it.+ for (const s of [...rowsOf('appsettings').values()]) if (bare(s.data._parentappmoduleid_value) === row.id) { rowsOf('appsettings').delete(s.id); removeComponents([s.id]); }+ }+ return noContent();+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // The environment before anything is built: its organization, root business unit and user, the default publisher and solution,+ // the two stock roles, the setting definitions the app settings bind, and the definitions of the system tables.+ function seedSystemTable(logical, info) {+ const table = metadata.makeTable({ SchemaName: logical, EntitySetName: info.set, ObjectTypeCode: info.otc, OwnershipType: 'OrganizationOwned', DisplayName: logical, DisplayCollectionName: logical, Attributes: info.name ? [{ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata', SchemaName: info.name, IsPrimaryName: true, DisplayName: info.name }] : [] }, { custom: false });+ table.PrimaryIdAttribute = info.id;+ if (!info.name) table.PrimaryNameAttribute = null;+ for (const a of table.Attributes.values()) a.IsCustomAttribute = false;+ metadata.tables.set(logical, table);+ recordPrivileges(table);+ }+ // The privileges of a table are rows too (`privileges`), which a role's grant names by id.+ function recordPrivileges(table) {+ for (const p of table.Privileges || []) insertRow('privileges', { privilegeid: p.PrivilegeId, name: p.Name, accessright: p.PrivilegeType, canbebasic: p.CanBeBasic, canbelocal: p.CanBeLocal, canbedeep: p.CanBeDeep, canbeglobal: p.CanBeGlobal });+ }+ for (const [logical, info] of Object.entries(SYSTEM_TABLES)) seedSystemTable(logical, info);+ insertRow('organizations', { organizationid: IDS.organization, name: 'Contoso', languagecode: baseLanguage });+ insertRow('businessunits', { businessunitid: IDS.businessUnit, name: 'contoso', _parentbusinessunitid_value: null });+ insertRow('systemusers', { systemuserid: IDS.user, fullname: 'Maker', domainname: '[email protected]', _businessunitid_value: IDS.businessUnit });+ insertRow('publishers', { publisherid: IDS.defaultPublisher, uniquename: 'DefaultPublisherContoso', friendlyname: 'Default Publisher for Contoso', customizationprefix: 'new', customizationoptionvalueprefix: 10000 });+ insertRow('solutions', { solutionid: IDS.defaultSolution, uniquename: 'Default', friendlyname: 'Default Solution', version: '1.0', ismanaged: false, isvisible: false, _publisherid_value: IDS.defaultPublisher });+ // The two stock roles of the root business unit. A root role is its own `parentrootroleid`; System Administrator carries its fixed+ // role template id, which is how the SDK finds it to associate it with a new app.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/role#BKMK_RoleTemplateId+ for (const [id, name, template] of [[IDS.systemAdministrator, 'System Administrator', '627090ff-40a3-4053-8790-584edc5be201'], [IDS.basicUser, 'Basic User', null]]) {+ insertRow('roles', { roleid: id, name, description: null, _businessunitid_value: IDS.businessUnit, _parentrootroleid_value: id, _parentroleid_value: null, _roletemplateid_value: template, ismanaged: true, iscustomizable: { Value: false } });+ }+ for (const name of options.settingDefinitions || ['NewLookAlwaysOn', 'HeaderAndNavigationRefresh']) {+ insertRow('settingdefinitions', { settingdefinitionid: randomUUID(), uniquename: name, displayname: name, datatype: name === 'HeaderAndNavigationRefresh' ? 0 : 2, defaultvalue: name === 'HeaderAndNavigationRefresh' ? '0' : 'false', isoverridable: true, overridablelevel: 0 });+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // The page tables are served by the page fake, over the SDK's own HttpClient shape (`{ status, headers, body }`).+ const pageServer = new FakeGenPageServer();+ pageServer.languages = { base: baseLanguage, provisioned: options.provisionedLanguages || [baseLanguage], available: options.provisionedLanguages || [baseLanguage] };+ // The page tables. The page fake owns their state and takes their writes, and a file's bytes (`/uxagentprojectfiles(<id>)/filecontent/$value`);+ // their READS are answered here, from that state, so every option a read may carry is APPLIED — `$filter` (any expression the+ // checker admits), `$orderby`, `$top` and `$select` — where the page fake's routes match only the reads the SDK sends today. Which+ // rows a read sees is the page fake's rule (FakeGenPageServer.execute, measured there):+ // - a plain read is the PUBLISHED layer: each page and file as its last publish left it, with the `versionnumber` the row has NOW;+ // `MSCRM.IncludeUnpublished: true` shows the saved rows, drafts included, instead;+ // - RetrieveUnpublishedMultiple() is the saved layer, `componentstate` 1 while a page holds a draft no publish has copied;+ // - conversation messages have one layer, kept in the platform's order: by `createdon`, then — the turns of one change set share a+ // second — by primary key in SQL uniqueidentifier order (both measured); a requested `$orderby` sorts over that order.+ // The reads a page table takes (anything else is refused):+ // /uxagentprojects · /uxagentprojects(<id>) · /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple() ·+ // /uxagentprojectfiles · /uxagentprojectfiles(<id>)/filecontent/$value · /agentconversationmessages+ function checkPageRead(p, query) {+ const m = /^\/(uxagentprojects|uxagentprojectfiles|agentconversationmessages)(?:\(([^)]*)\))?(?:\/(.+))?$/.exec(p);+ if (!m) throw new Unmodelled(`GET ${p}`);+ const [, set, key, rest] = m;+ const read = (kind) => ({ set, kind, where: p, key: key === undefined ? null : idOf(key, `GET ${p}`) });+ if (key === undefined && !rest) return { ...read('collection'), checked: checkRead(set, query, 'collection', p) };+ if (key !== undefined && !rest && set === 'uxagentprojects') return { ...read('single'), checked: checkRead(set, query, 'single', p) };+ if (key === undefined && set === 'uxagentprojects' && rest === 'Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()') return { ...read('unpublishedMany'), checked: checkRead(set, query, 'unpublishedMany', p) };+ if (key !== undefined && set === 'uxagentprojectfiles' && rest === 'filecontent/$value') { noQuery(query, p); return read('content'); }+ throw new Unmodelled(`GET ${p}`);+ }+ // A page table's rows, whole, as the layer a read sees holds them (`saved`: drafts included).+ function pageRows(set, saved) {+ const pages = pageServer.state;+ const published = pageServer.publishedPages;+ if (set === 'uxagentprojects') {+ if (saved) return [...pages.projects.values()].map((p) => ({ uxagentprojectid: p.id, name: p.name, versionnumber: p.version, componentstate: p.draft || !published.has(p.id) ? 1 : 0, '@odata.etag': `W/"${p.etag}"` }));+ return [...published.values()].map(({ project }) => ({ uxagentprojectid: project.id, name: project.name, versionnumber: pages.projects.has(project.id) ? pages.projects.get(project.id).version : project.version, componentstate: 0, '@odata.etag': `W/"${project.etag}"` }));+ }+ if (set === 'uxagentprojectfiles') {+ const row = (file, projectId, version) => ({ uxagentprojectfileid: file.id, filename: file.filename, filetype: file.filetype, versionnumber: version, _uxagentprojectid_value: projectId, '@odata.etag': `W/"${file.etag}"` });+ if (saved) return [...pages.files.values()].map((file) => row(file, file.projectId, file.version));+ return [...published.entries()].flatMap(([id, page]) => (page.files || []).map((file) => row(file, id, pages.files.has(file.id) ? pages.files.get(file.id).version : file.version)));+ }+ return [...pages.messages.values()]+ .sort((a, b) => a.createdon.localeCompare(b.createdon) || sqlGuidOrder(a.id, b.id))+ .map((x) => ({ agentconversationmessageid: x.id, message: x.message, messagesender: x.sender, messagecontext: x.context, createdon: x.createdon, versionnumber: x.version, _regardingobjectid_value: x.regarding }));+ }+ function answerPageRead({ set, kind, key, where, checked }, query, headers) {+ const unpublished = Object.entries(headers || {}).some(([name, value]) => lc(name) === 'mscrm.includeunpublished' && String(value) === 'true');+ const rows = pageRows(set, kind === 'unpublishedMany' || unpublished);+ const { schema } = checked;+ const id = schema.info.id;+ const answer = (row) => (query.$select ? selectColumns(schema, row, query, { ...(row['@odata.etag'] ? { '@odata.etag': row['@odata.etag'] } : {}), [id]: row[id] }) : row);+ if (kind === 'single') {+ const row = rows.find((r) => r[id] === key);+ if (!row) return failure(404, '0x80040217', `${schema.info.logical} With Id = ${key} Does Not Exist`);+ return json(200, answer(row), { etag: row['@odata.etag'] });+ }+ return json(200, { value: applyQuery(rows, (row) => row, query, checked, where).map(answer) });+ }+ async function pageRequest(method, where, body, headers) {+ if (method === 'GET') {+ const read = checkPageRead(pathOf(where), queryOf(where));+ if (read.kind !== 'content') return answerPageRead(read, queryOf(where), headers);+ }+ const res = await pageServer.receive(method, `${PAGE_API}${where}`, body, { headers }, false, {});+ // The page fake answers what it does not route with a 404/405 "no route": that is a request this fake does not model either.+ const routeless = res.body && res.body.error && /^no route for /.test(String(res.body.error.message || ''));+ if (routeless) throw new Unmodelled(`${method} ${where} (the page fake has no route for it)`);+ const lowered = Object.fromEntries(Object.entries(res.headers || {}).map(([name, value]) => [name.toLowerCase(), value]));+ const bytes = Buffer.isBuffer(res.body) || res.body instanceof Uint8Array;+ return { statusCode: res.status, headers: bytes ? lowered : { 'content-type': 'application/json', ...lowered }, body: bytes ? Buffer.from(res.body) : (res.body === undefined ? '' : JSON.stringify(res.body)) };+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // The router. `where` is the path below the API root with its query; `body` the parsed JSON body.+ const queryOf = (where) => {+ const at = where.indexOf('?');+ const out = {};+ if (at === -1) return out;+ // Split on `&` only outside quotes and parentheses: a filter's text may hold either.+ let depth = 0;+ let quoted = false;+ let start = at + 1;+ const s = where;+ for (let i = at + 1; i <= s.length; i += 1) {+ const ch = s[i];+ if (ch === "'") quoted = !quoted;+ else if (!quoted && ch === '(') depth += 1;+ else if (!quoted && ch === ')') depth -= 1;+ if (i === s.length || (ch === '&' && !quoted && depth === 0)) {+ const part = s.slice(start, i);+ const eq = part.indexOf('=');+ if (eq > 0) out[part.slice(0, eq)] = part.slice(eq + 1);+ start = i + 1;+ }+ }+ return out;+ };+ const pathOf = (where) => (where.indexOf('?') === -1 ? where : where.slice(0, where.indexOf('?')));++ async function dispatch(method, where, body, headers) {+ const p = pathOf(where);+ const query = queryOf(where);+ if (PAGE_PATH.test(p)) return pageRequest(method, where, body, headers);+ const meta = metadata.handle(method, p, query, body, headers, API);+ if (meta) return meta.status === 204 ? noContent(meta.headers) : json(meta.status, meta.body, meta.headers);+ const action = await actions(method, p, query, body, headers, where);+ if (action) return action;+ return records(method, p, query, body, headers);+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // Actions and functions (unbound and bound). Each answers as the platform does; null when the path is not one.+ // An action or function takes the parameters in its body or its path, never a query option — but for the ones that read rows+ // (RetrieveUnpublished*: the options of a read) and RetrieveFilteredForms (its `@e`, `@t`, `@u` parameter aliases).+ const ACTIONS = /^\/(WhoAmI|RetrieveProvisionedLanguages\(\)|RetrieveAvailableLanguages\(\)|PublishXml|PublishAllXml|AddSolutionComponent|AddAppComponents|RemoveAppComponents|InsertStatusValue|InsertOptionValue|SaveSettingValue|RetrieveSetting\(.*\)|\$batch|[A-Za-z_]\w*\([^)]+\)\/Microsoft\.Dynamics\.CRM\.(AddPrivilegesRole|ReplacePrivilegesRole)|[A-Za-z_]\w*\/Microsoft\.Dynamics\.CRM\.CreateMultiple)$/;+ async function actions(method, p, query, body, headers, where) {+ if (ACTIONS.test(p)) noQuery(query, p);+ if (method === 'GET' && p === '/WhoAmI') return json(200, { UserId: IDS.user, BusinessUnitId: IDS.businessUnit, OrganizationId: IDS.organization });+ if (method === 'GET' && p === '/RetrieveProvisionedLanguages()') return json(200, { RetrieveProvisionedLanguages: pageServer.languages.provisioned });+ if (method === 'GET' && p === '/RetrieveAvailableLanguages()') return json(200, { LocaleIds: pageServer.languages.available });+ if (method === 'POST' && p === '/PublishXml') {+ publishXml(body.ParameterXml);+ await pageServer.receive('POST', `${PAGE_API}/PublishXml`, body, { headers }, false, {});+ return noContent();+ }+ if (method === 'POST' && p === '/PublishAllXml') { publishAll(); return noContent(); }+ if (method === 'POST' && p === '/AddSolutionComponent') {+ const solution = solutionByName(body.SolutionUniqueName);+ if (!solution) return failure(400, '0x8004f01e', `Solution ${body.SolutionUniqueName} does not exist.`);+ addComponent(solution.id, { objectid: body.ComponentId, componenttype: Number(body.ComponentType), rootcomponentbehavior: body.DoNotIncludeSubcomponents ? 1 : 0 });+ return json(200, { id: randomUUID() });+ }+ // AddAppComponents { AppId, Components: [{ "@odata.type": "Microsoft.Dynamics.CRM.systemform", "formid": "<id>" }, …] }: one+ // appmodulecomponent row per component, bound to the app's unique layer (`appmoduleidunique`), as the platform keeps them.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/addappcomponents+ if (method === 'POST' && (p === '/AddAppComponents' || p === '/RemoveAppComponents')) {+ const app = rowsOf('appmodules').get(bare(body.AppId));+ if (!app) return failure(404, '0x80040217', `appmodule With Id = ${body.AppId} Does Not Exist`);+ for (const c of body.Components || []) {+ const ref = componentRef(c);+ const held = appComponentsOf(app).find((x) => bare(x.data.objectid) === ref.id && x.data.componenttype === ref.type);+ if (p === '/RemoveAppComponents') { if (held) rowsOf('appmodulecomponents').delete(held.id); continue; }+ if (!held) insertRow('appmodulecomponents', { objectid: ref.id, componenttype: ref.type, rootcomponentbehavior: 0, _appmoduleidunique_value: app.data.appmoduleidunique });+ }+ app.version = nextVersion();+ app.data.versionnumber = app.version;+ return noContent();+ }+ // A bound action on a role: AddPrivilegesRole / ReplacePrivilegesRole { Privileges: [{ PrivilegeId, Depth, BusinessUnitId }] }.+ // The intersect rows carry the depth as a mask (1 Basic, 2 Local, 4 Deep, 8 Global).+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/addprivilegesrole+ const roleAction = /^\/roles\(([^)]+)\)\/Microsoft\.Dynamics\.CRM\.(AddPrivilegesRole|ReplacePrivilegesRole)$/.exec(p);+ if (method === 'POST' && roleAction) {+ const role = rowsOf('roles').get(idOf(roleAction[1], p));+ if (!role) return failure(404, '0x80040217', `role With Id = ${roleAction[1]} Does Not Exist`);+ const mask = { Basic: 1, Local: 2, Deep: 4, Global: 8 };+ const held = rowsOf('roleprivilegescollection');+ if (roleAction[2] === 'ReplacePrivilegesRole') for (const [id, row] of [...held]) if (bare(row.data.roleid) === role.id) held.delete(id);+ for (const grant of body.Privileges || []) {+ const existing = [...held.values()].find((row) => bare(row.data.roleid) === role.id && bare(row.data.privilegeid) === bare(grant.PrivilegeId));+ const depth = mask[grant.Depth] || Number(grant.Depth) || 1;+ if (existing) existing.data.privilegedepthmask = Math.max(existing.data.privilegedepthmask, depth);+ else insertRow('roleprivilegescollection', { roleid: role.id, privilegeid: bare(grant.PrivilegeId), privilegedepthmask: depth });+ }+ return noContent();+ }+ const unpublished = /^\/([A-Za-z_]\w*)\(([^)]+)\)\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublished\(\)$/.exec(p);+ if (method === 'GET' && unpublished) {+ const { info } = checkRead(unpublished[1], query, 'unpublished', p).schema;+ if (!info.layered) throw new Unmodelled(`${unpublished[1]} has no unpublished layer (${p})`);+ const row = rowsOf(unpublished[1]).get(idOf(unpublished[2], p));+ if (!row) return failure(404, '0x80040217', `${unpublished[1]} With Id = ${unpublished[2]} Does Not Exist`);+ const shaped = shape(row, row.data, query, info, { saved: true });+ return json(200, shaped, { etag: shaped['@odata.etag'] });+ }+ const unpublishedMany = /^\/([A-Za-z_]\w*)\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)$/.exec(p);+ if (method === 'GET' && unpublishedMany) {+ if (!(infoOfSet(unpublishedMany[1]) || {}).layered) throw new Unmodelled(`${unpublishedMany[1]} has no unpublished layer (${p})`);+ return json(200, { value: readRows(unpublishedMany[1], query, { saved: true, kind: 'unpublishedMany', where: p }) });+ }+ // The business-rule designer's bound members (`CreateProcessWithWfomJson`, `RetrieveProcessWithWfomJson`) are a preview that most+ // environments do not expose; this one does not, and answers as Dataverse answers a member it does not declare. The SDK reads that+ // 404 as "business-rule authoring is not enabled here" (WFOM_API_UNAVAILABLE) and the build skips the rules with a warning+ // (references/app-spec-schema-advanced.md, businessRules[]). The success path of that preview is not modelled.+ const wfom = /^\/workflows\([^)]+\)\/Microsoft\.Dynamics\.CRM\.(CreateProcessWithWfomJson|RetrieveProcessWithWfomJson|UpdateProcessWithWfomJson)$/.exec(p);+ if (wfom) return failure(404, '0x8006088a', `Resource not found for the segment 'Microsoft.Dynamics.CRM.${wfom[1]}'.`);+ // RetrieveFilteredForms: the forms of one type a user may open, first to last — answered with ids only:+ // { "value": [ { "@odata.type": "#Microsoft.Dynamics.CRM.systemform", "formid": "<guid>" }, … ] }+ // The user here holds System Administrator, which may open every form, so only the order is modelled, as lib/form-order.js+ // records it measured: by the published `<DisplayConditions Order>`, a form with conditions but no Order after those with one, a+ // form with no conditions after every form that has them; forms that tie come in the order they were created.+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrievefilteredforms+ if (method === 'GET' && /^\/systemforms\/Microsoft\.Dynamics\.CRM\.RetrieveFilteredForms\(EntityLogicalName=@e,FormType=@t,User=@u\)$/.test(p)) {+ // Its three parameter aliases, each as the SDK sends it: `@e='contoso_task'`, `@t=2`, and the user as a reference,+ // `@u={'@odata.id':'systemusers(<id>)'}`. The one user modelled is the maker (System Administrator, who may open every form).+ for (const option of Object.keys(query)) if (!['@e', '@t', '@u'].includes(option)) throw new Unmodelled(`the parameter ${option} is not modelled on ${p}`);+ const named = /^'([A-Za-z_]\w*)'$/.exec(String(query['@e'] || ''));+ const user = new RegExp(`^\\{'@odata\\.id':'systemusers\\((${GUID_TEXT})\\)'\\}$`).exec(String(query['@u'] || ''));+ if (!named || !/^\d+$/.test(String(query['@t'] || ''))) throw new Unmodelled(`the parameters @e=${query['@e']}, @t=${query['@t']} of ${p} are not modelled`);+ if (!user || bare(user[1]) !== IDS.user) throw new Unmodelled(`the user @u=${query['@u']} of ${p} is not modelled: only the maker is`);+ const entity = lc(named[1]);+ const type = Number(query['@t']);+ const rank = (xml) => {+ const conditions = /<DisplayConditions\b([^>]*)>/i.exec(String(xml || ''));+ if (!conditions) return [2, 0];+ const order = /\bOrder="(-?\d+)"/i.exec(conditions[1]);+ return order ? [0, Number(order[1])] : [1, 0];+ };+ const forms = [...rowsOf('systemforms').values()]+ .filter((row) => row.published && lc(row.published.objecttypecode) === entity && Number(row.published.type) === type && row.published.formactivationstate === 1)+ .map((row, at) => ({ id: row.id, at, rank: rank(row.published.formxml) }))+ .sort((a, b) => a.rank[0] - b.rank[0] || a.rank[1] - b.rank[1] || a.at - b.at);+ return json(200, { value: forms.map((f) => ({ '@odata.type': '#Microsoft.Dynamics.CRM.systemform', formid: f.id })) });+ }+ if (method === 'POST' && p === '/$batch') return batch(body, headers);+ // CreateMultiple on a table's entity set: { "Targets": [ { "@odata.type": "Microsoft.Dynamics.CRM.contoso_project", …columns } ] } ->+ // { "Ids": [ "<guid>", … ] }, in the order of the targets. It is one transaction: a target that fails creates none of them.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/createmultiple+ const createMultiple = /^\/([A-Za-z_]\w*)\/Microsoft\.Dynamics\.CRM\.CreateMultiple$/.exec(p);+ if (method === 'POST' && createMultiple) {+ const saved = snapshotState();+ const ids = [];+ for (const target of body.Targets || []) {+ const record = { ...target };+ delete record['@odata.type'];+ const res = createRow(createMultiple[1], record, headers);+ if (res.statusCode >= 300) { restoreState(saved); return res; }+ ids.push(/\(([^)]+)\)$/.exec(res.headers['odata-entityid'])[1]);+ }+ return json(200, { Ids: ids });+ }+ // InsertStatusValue { EntityLogicalName, AttributeLogicalName: "statuscode", Label, StateCode, Value? } adds a status reason under a state,+ // and InsertOptionValue { EntityLogicalName, AttributeLogicalName, Label, Value? } an option; each answers the value it was given (or+ // the next free one): `{ "NewOptionValue": 100000000 }`. A value that is already an option is refused.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/insertstatusvalue+ if (method === 'POST' && (p === '/InsertStatusValue' || p === '/InsertOptionValue')) {+ const table = metadata.tables.get(lc(body.EntityLogicalName));+ const attribute = table && table.Attributes.get(lc(body.AttributeLogicalName));+ if (!attribute || !attribute.OptionSet) return failure(404, '0x80040217', `attribute ${body.EntityLogicalName}.${body.AttributeLogicalName} Does Not Exist`);+ const options = attribute.OptionSet.Options;+ const value = body.Value !== undefined && body.Value !== null ? Number(body.Value) : Math.max(100000000 - 1, ...options.map((o) => o.Value)) + 1;+ if (options.some((o) => o.Value === value)) return failure(400, '0x80047007', `An option with the value ${value} already exists.`);+ options.push({ Value: value, Label: metadata.label(body.Label), Description: metadata.label(null), Color: null, IsManaged: false, ExternalValue: null, ...(p === '/InsertStatusValue' ? { State: Number(body.StateCode) } : {}) });+ return json(200, { NewOptionValue: value });+ }+ // SaveSettingValue { SettingName, Value, AppUniqueName?, SolutionUniqueName? }: an app-scoped value is the `appsettings` row of that+ // app and definition, written to the app's SAVED layer (a publish of the app makes it effective — the build's AI step relies on that,+ // sdk-build.js 8b); without an app it is the organization's value. RetrieveSetting(SettingName='x',AppUniqueName='y') answers the+ // EFFECTIVE value — the published app override, else the organization's, else the definition's default — as+ // `{ "SettingDetail": { "Value": "true", "DataType": 2 } }`.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/savesettingvalue+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/retrievesetting+ if (method === 'POST' && p === '/SaveSettingValue') {+ const definition = settingDefinition(body.SettingName);+ if (!definition) return failure(404, '0x80040217', `settingdefinition With Name = ${body.SettingName} Does Not Exist`);+ if (body.AppUniqueName) {+ const app = [...rowsOf('appmodules').values()].find((row) => lc(row.data.uniquename) === lc(body.AppUniqueName));+ if (!app) return failure(404, '0x80040217', `appmodule With UniqueName = ${body.AppUniqueName} Does Not Exist`);+ const held = [...rowsOf('appsettings').values()].find((row) => bare(row.data._parentappmoduleid_value) === app.id && bare(row.data._settingdefinitionid_value) === definition.id);+ if (held) { held.data.value = String(body.Value); held.version = nextVersion(); held.data.versionnumber = held.version; } else insertRow('appsettings', { _parentappmoduleid_value: app.id, _settingdefinitionid_value: definition.id, value: String(body.Value), uniquename: `${app.data.uniquename}_${definition.data.uniquename}` });+ } else {+ const held = [...rowsOf('organizationsettings').values()].find((row) => bare(row.data._settingdefinitionid_value) === definition.id);+ if (held) held.data.value = String(body.Value); else insertRow('organizationsettings', { _settingdefinitionid_value: definition.id, value: String(body.Value), uniquename: definition.data.uniquename });+ }+ return noContent();+ }+ const setting = /^\/RetrieveSetting\((.*)\)$/.exec(p);+ if (method === 'GET' && setting) {+ // SettingName is required, AppUniqueName optional; nothing else is a parameter of the function.+ const args = functionParameters(setting[1], ['SettingName', 'AppUniqueName'], ['SettingName'], 'RetrieveSetting');+ const definition = settingDefinition(args.SettingName);+ if (!definition) return failure(404, '0x80040217', `settingdefinition With Name = ${args.SettingName} Does Not Exist`);+ const appUnique = args.AppUniqueName;+ const app = appUnique && [...rowsOf('appmodules').values()].find((row) => lc(row.data.uniquename) === lc(appUnique));+ const override = app && [...rowsOf('appsettings').values()].find((row) => row.published && bare(row.published._parentappmoduleid_value) === app.id && bare(row.published._settingdefinitionid_value) === definition.id);+ const org = [...rowsOf('organizationsettings').values()].find((row) => bare(row.data._settingdefinitionid_value) === definition.id);+ const value = override ? override.published.value : org ? org.data.value : definition.data.defaultvalue;+ return json(200, { SettingDetail: { Name: definition.data.uniquename, Value: value, DataType: definition.data.datatype } });+ }+ return null;+ }+ const settingDefinition = (name) => [...rowsOf('settingdefinitions').values()].find((row) => lc(row.data.uniquename) === lc(name));+ // A function's parameters in its path, `Name='text'` pairs (a quote inside doubled: 'O''Neil') separated by commas, checked against+ // the ones it takes BEFORE anything is resolved: an unknown, repeated or missing required parameter, or a value that is not a text+ // literal (an alias, a number), is not modelled — never answered as though the parameter were simply not given.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/use-web-api-functions#passing-parameters-to-a-function+ function functionParameters(text, allowed, required, where) {+ const params = {};+ const pair = /\s*(\w+)\s*=\s*'((?:[^']|'')*)'\s*(,|$)/y;+ let at = 0;+ while (at < text.length) {+ pair.lastIndex = at;+ const m = pair.exec(text);+ if (!m || (m[3] === ',' && pair.lastIndex === text.length)) throw new Unmodelled(`the parameters (${text}) of ${where} are not modelled`);+ if (!allowed.includes(m[1]) || Object.prototype.hasOwnProperty.call(params, m[1])) throw new Unmodelled(`the parameter ${m[1]} of ${where} is not modelled`);+ params[m[1]] = m[2].replace(/''/g, "'");+ at = pair.lastIndex;+ }+ for (const name of required) if (!Object.prototype.hasOwnProperty.call(params, name)) throw new Unmodelled(`${where} without its ${name} is not modelled`);+ return params;+ }++ // A component of AddAppComponents, by its type: `{ "@odata.type": "Microsoft.Dynamics.CRM.savedquery", "savedqueryid": "<id>" }` or+ // the older `{ "@odata.id": "savedqueries(<id>)" }`. An app component's type is the solution component type of its kind.+ const APP_COMPONENT_TYPES = { systemform: 60, savedquery: 26, savedqueryvisualization: 59, sitemap: 62, appaction: 10129, entity: 1, uxagentproject: 10200 };+ function componentRef(c) {+ const typed = /Microsoft\.Dynamics\.CRM\.(\w+)$/.exec(String(c['@odata.type'] || ''));+ if (typed) {+ const kind = typed[1];+ if (kind === 'entity') return { id: bare(c.entityid || c.MetadataId), type: 1 };+ const info = SYSTEM_TABLES[kind];+ if (!info || !APP_COMPONENT_TYPES[kind]) throw new Unmodelled(`an app component of type ${kind}`);+ return { id: bare(c[info.id]), type: APP_COMPONENT_TYPES[kind] };+ }+ const ref = /^([A-Za-z_]\w*)\(([^)]+)\)$/.exec(String(c['@odata.id'] || ''));+ if (!ref) throw new Unmodelled(`an app component ${JSON.stringify(c)}`);+ const info = infoOfSet(ref[1]);+ return { id: bare(ref[2]), type: (info && APP_COMPONENT_TYPES[info.logical]) || 1 };+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // Rows: `/<set>`, `/<set>(<id>)`, `/<set>(<id>)/<navigation>` and `/<set>(<id>)/<navigation>/$ref` — and nothing else. A read is checked+ // against the set's schema first (checkRead); a write may carry only the `$select` of the row it answers with; a navigation must be one+ // the set declares.+ const noQuery = (query, where) => { const options = Object.keys(query || {}); if (options.length) throw new Unmodelled(`the query option ${options[0]} is not modelled on ${where}`); };+ function records(method, p, query, body, headers) {+ const m = /^\/([A-Za-z_]\w*)(?:\(([^)]*)\))?(?:\/(.+))?$/.exec(p);+ if (!m) throw new Unmodelled(`${method} ${p}`);+ const [, set, key, rest] = m;+ const info = infoOfSet(set);+ if (!info) throw new Unmodelled(`${method} ${p}: no table has the entity set ${set}`);+ if (key !== undefined) idOf(key, `${method} ${p}`);+ if (!key && !rest) {+ if (method === 'GET') return json(200, { value: readRows(set, query, { kind: 'collection', where: p }) });+ if (method === 'POST') { checkRead(set, query, 'write', p); return createRow(set, body, headers, query); }+ }+ if (key && !rest) {+ if (method === 'GET') {+ const { expands } = checkRead(set, query, 'single', p);+ // A read by id answers the row as saved, with its current version — the SDK reads a form right after it creates it+ // (`systemforms(<id>)?$select=formid`, for the token of its next write) and the platform answers it (fake-dataverse.js models the+ // same). Only a plain read of the COLLECTION is the published layer.+ const row = rowsOf(set).get(bare(key));+ if (!row) return failure(404, '0x80040217', `${info.logical} With Id = ${key} Does Not Exist`);+ // An app module is the exception: its read by id is the PUBLISHED projection, so a draft that was never published answers 404+ // (measured; helpers/fake-apps-org.js) — which is why the download tells the maker to publish a new app first.+ if (set === 'appmodules' && !row.published) return failure(404, '0x80040217', `appmodule With Id = ${key} Does Not Exist`);+ const data = set === 'appmodules' ? row.published : row.data;+ const shaped = shape(row, data, query, info, { saved: true });+ if (info.layered && !listOf(query.$select || '').includes('componentstate')) delete shaped.componentstate;+ // The checked `$expand` is applied as on a collection read: the lookup's row embedded, narrowed by its own `$select`.+ return json(200, withExpands(shaped, data, expands), { etag: shaped['@odata.etag'] });+ }+ if (method === 'PATCH') { checkRead(set, query, 'write', p); return updateRow(set, key, body, headers, query); }+ if (method === 'DELETE') { noQuery(query, p); return deleteRow(set, key); }+ }+ if (key && rest) {+ const schema = schemaOf(set);+ const ref = /^([A-Za-z_]\w*)(?:\(([^)]+)\))?\/\$ref$/.exec(rest);+ if (ref && !schema.navigations[ref[1]]) throw new Unmodelled(`${info.logical} has no navigation ${ref[1]} (${method} ${p})`);+ if (ref && method === 'POST') {+ noQuery(query, p);+ const target = /\/([A-Za-z_]\w*)\(([^)]+)\)$/.exec(String(body['@odata.id'] || ''));+ if (!target || target[1] !== schema.navigations[ref[1]]) throw new Unmodelled(`cannot read the reference ${JSON.stringify(body)} for ${ref[1]}`);+ idOf(target[2], `the reference of ${p}`);+ // An N:N link that exists already is refused as a duplicate, as Dataverse does (sdk-build.js ensureAppAvailableToRole relies on it+ // and treats the refusal as "already linked").+ if (associations.some((a) => a.id === bare(key) && a.nav === ref[1] && a.toId === bare(target[2]))) return failure(400, '0x80040237', 'Cannot insert duplicate key.');+ associations.push({ set, id: bare(key), nav: ref[1], toSet: target[1], toId: bare(target[2]) });+ return noContent();+ }+ if (ref && method === 'DELETE') {+ for (const option of Object.keys(query)) if (option !== '$id') throw new Unmodelled(`the query option ${option} is not modelled on ${p}`);+ const toId = idOf(ref[2] || (/\(([^)]+)\)$/.exec(String(query.$id || '')) || [])[1], `DELETE ${p}`);+ const at = associations.findIndex((a) => a.id === bare(key) && a.nav === ref[1] && a.toId === toId);+ if (at === -1) return failure(404, '0x80040217', 'The association does not exist.');+ associations.splice(at, 1);+ return noContent();+ }+ const nav = /^([A-Za-z_]\w*)$/.exec(rest);+ if (nav && method === 'GET') {+ const target = schema.navigations[nav[1]];+ if (!target) throw new Unmodelled(`${info.logical} has no navigation ${nav[1]} (GET ${p})`);+ // The related rows, by the link either side made, answered as rows of the related set (its own schema, its own options).+ const linked = associations+ .filter((a) => a.nav === nav[1] && ((a.set === set && a.id === bare(key)) || (a.toSet === set && a.toId === bare(key))))+ .map((a) => rowsOf(target).get(a.set === set && a.id === bare(key) ? a.toId : a.id))+ .filter(Boolean);+ return json(200, { value: answerRows(target, linked, query, { saved: true, kind: 'navigation', where: p }) });+ }+ }+ throw new Unmodelled(`${method} ${p}`);+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // `$batch`: one change set, run atomically — every operation is applied to a copy of the state, and the copy is kept only when all+ // of them succeed; the answer then names every operation's status, or only the one that failed. Change sets of page rows go to the+ // page fake whole.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#change-sets+ async function batch(text) {+ const operations = parseBatch(String(text));+ if (operations.length && operations.every((op) => PAGE_PATH.test(pathOf(op.path)))) {+ const res = await pageServer.receiveBatch(`${PAGE_API}/$batch`, String(text));+ return { statusCode: res.status, headers: { 'content-type': 'multipart/mixed; boundary=batchresponse_00000000-0000-0000-0000-000000000001', ...(res.headers || {}) }, body: typeof res.body === 'string' ? res.body : JSON.stringify(res.body) };+ }+ const saved = snapshotState();+ const statuses = [];+ for (const op of operations) {+ // eslint-disable-next-line no-await-in-loop+ const res = await dispatch(op.method, op.path, op.body, op.headers);+ if (res.statusCode < 200 || res.statusCode >= 300) {+ restoreState(saved);+ return batchAnswer([{ contentId: op.contentId, status: res.statusCode, body: res.body }]);+ }+ statuses.push({ contentId: op.contentId, status: res.statusCode, headers: res.headers });+ }+ return batchAnswer(statuses);+ }++ // The operations of a `$batch` request, as the SDK renders it (boundaries differ per request):+ // --batch_<id>+ // Content-Type: multipart/mixed;boundary=changeset_<id>+ //+ // --changeset_<id>+ // Content-Type: application/http+ // Content-Transfer-Encoding: binary+ // Content-ID: 1+ //+ // POST https://contoso.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='contoso_item')/Attributes HTTP/1.1+ // Content-Type: application/json;type=entry+ // MSCRM.SolutionUniqueName: ContosoKitchen+ //+ // {"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",…}+ // --changeset_<id>--+ // --batch_<id>--+ // RFC 2046: the CRLF before a delimiter belongs to the delimiter, not to the body.+ function parseBatch(text) {+ const outer = (/^--(\S+)/.exec(text) || [])[1];+ const inner = (/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(text) || [])[1];+ const boundary = inner || outer;+ if (!boundary) throw new Unmodelled('a $batch body without a boundary');+ return text.split(`--${boundary}`).slice(1).filter((segment) => !segment.startsWith('--')).map((segment) => {+ const mimeEnd = segment.search(/\r?\n\r?\n/);+ const mime = segment.slice(0, mimeEnd);+ const http = segment.slice(mimeEnd).replace(/^\r?\n\r?\n/, '');+ const headEnd = http.search(/\r?\n\r?\n/);+ const head = (headEnd === -1 ? http : http.slice(0, headEnd)).split(/\r?\n/);+ const [, method, url] = /^(\w+) (\S+) HTTP\/1\.1$/.exec(head[0]) || [];+ if (!method) throw new Unmodelled(`a $batch part without a request line: ${JSON.stringify(head[0])}`);+ const headers = {};+ for (const line of head.slice(1)) {+ const colon = line.indexOf(':');+ if (colon > 0) headers[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();+ }+ const payload = headEnd === -1 ? '' : http.slice(headEnd).replace(/^\r?\n\r?\n/, '').replace(/\r?\n$/, '');+ const parsed = new URL(url, origin);+ const where = decodeURIComponent(parsed.pathname + parsed.search).replace(API_ROOT, '');+ // A part's body is JSON when its Content-Type says so; a file's content (a page's source) is kept as the text it is.+ const contentType = (Object.entries(headers).find(([k]) => lc(k) === 'content-type') || [])[1] || '';+ const body = !payload ? undefined : /json/i.test(contentType) ? JSON.parse(payload) : payload;+ return { contentId: (/^Content-ID:\s*(\S+)/im.exec(mime) || [])[1], method, path: where, headers, body };+ });+ }+ // The answer to a change set: the platform's own boundaries, one part per operation (or only the one that failed), Content-ID echoed.+ function batchAnswer(parts) {+ const outer = `batchresponse_${randomUUID()}`;+ const inner = `changesetresponse_${randomUUID()}`;+ const text = [+ `--${outer}`,+ `Content-Type: multipart/mixed; boundary=${inner}`,+ '',+ ...parts.map((part) => [+ `--${inner}`,+ 'Content-Type: application/http',+ 'Content-Transfer-Encoding: binary',+ `Content-ID: ${part.contentId}`,+ '',+ `HTTP/1.1 ${part.status} ${part.status < 300 ? (part.status === 204 ? 'No Content' : 'OK') : 'Bad Request'}`,+ ...Object.entries(part.headers || {}).filter(([k]) => /^(odata-entityid|location|etag)$/i.test(k)).map(([k, v]) => `${k === 'odata-entityid' ? 'OData-EntityId' : k}: ${v}`),+ 'OData-Version: 4.0',+ ...(part.status >= 300 && part.body ? ['Content-Type: application/json; odata.metadata=minimal', '', String(part.body)] : ['']),+ '',+ ].join('\r\n')),+ `--${inner}--`,+ `--${outer}--`,+ '',+ ].join('\r\n');+ return { statusCode: 200, headers: { 'content-type': `multipart/mixed; boundary=${outer}`, 'odata-version': '4.0' }, body: text };+ }+ // The whole environment, for a change set to roll back to.+ const snapshotState = () => structuredClone({ sets, associations, tables: metadata.tables, relationships: metadata.relationships, optionSets: metadata.optionSets });+ function restoreState(saved) {+ for (const [target, source] of [[sets, saved.sets], [metadata.tables, saved.tables], [metadata.relationships, saved.relationships], [metadata.optionSets, saved.optionSets]]) {+ target.clear();+ for (const [k, v] of source) target.set(k, v);+ }+ associations.splice(0, associations.length, ...saved.associations);+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // The transport: `request({ url, method, headers, body })` -> `{ statusCode, headers, body }`, as lib/dataverse-auth.js makeRequest.+ async function request({ url, method, headers, body }) {+ const parsed = new URL(url);+ if (parsed.origin !== origin) throw new Error(`fake-lifecycle-org: a request to another origin: ${url}`);+ const where = decodeURIComponent(parsed.pathname + parsed.search).replace(API_ROOT, '');+ const type = (Object.entries(headers || {}).find(([k]) => lc(k) === 'content-type') || [])[1] || '';+ let parsedBody;+ if (body !== undefined && body !== null && body !== '') {+ if (Buffer.isBuffer(body) && !/json/i.test(type)) parsedBody = body;+ else if (/json/i.test(type) || !type) parsedBody = JSON.parse(String(body));+ else parsedBody = String(body);+ }+ const recorded = { method, path: where, body: parsedBody, headers };+ if (method === 'POST' && pathOf(where) === '/$batch') {+ try { recorded.operations = parseBatch(String(body)); } catch { /* recorded as sent; the dispatch below names the failure */ }+ }+ requests.push(recorded);+ try {+ const answer = await dispatch(method, where, parsedBody, headers);+ recorded.status = answer && answer.statusCode;+ return answer;+ } catch (error) {+ unexpected.push(`${method} ${where}: ${error && error.message}`);+ return failure(501, '0x80040265', `fake-lifecycle-org does not model ${method} ${where}: ${error && error.message}`);+ }+ }++ // ---------------------------------------------------------------------------------------------------------------------------+ // What a test reads.+ const resourceOf = (path) => pathOf(path).replace(/^\//, '').replace(/\((?:[^()']|'[^']*')*\)/g, '');+ // Every request that changed something since `mark`, a `$batch` as its operations.+ function writes(since = 0) {+ return requests.slice(since).flatMap((r) => {+ if (r.method === 'GET') return [];+ if (r.operations) return r.operations.filter((op) => op.method !== 'GET').map((op) => ({ ...op, batched: true }));+ return [r];+ });+ }+ // `METHOD resource` per write ("POST EntityDefinitions/Attributes", "PATCH savedqueries", "POST PublishXml").+ const writeNames = (since = 0) => writes(since).map((w) => `${w.method} ${resourceOf(w.path)}`);+ const countBy = (list) => list.reduce((acc, name) => { acc[name] = (acc[name] || 0) + 1; return acc; }, {});+ // Reads by `GET resource`, for a budget.+ const readNames = (since = 0) => requests.slice(since).filter((r) => r.method === 'GET').map((r) => `GET ${resourceOf(r.path)}`);++ // Everything the environment holds, by IDENTITY, named so two inventories can be compared: what was made and what was deleted (a+ // teardown must take it back to the seed). What each artifact HOLDS is contents()'s to compare.+ function inventory() {+ const label = (t) => t.LogicalName;+ const out = {+ tables: [...metadata.tables.values()].map(label).sort(),+ columns: Object.fromEntries([...metadata.tables.values()].map((t) => [t.LogicalName, [...t.Attributes.keys()].sort()])),+ keys: Object.fromEntries([...metadata.tables.values()].filter((t) => t.Keys.size).map((t) => [t.LogicalName, [...t.Keys.keys()].sort()])),+ relationships: [...metadata.relationships.values()].map((r) => r.SchemaName).sort(),+ optionSets: [...metadata.optionSets.values()].map((s) => s.Name).sort(),+ rows: {},+ solutionComponents: componentRows().map((c) => `${c.data._solutionid_value} ${c.data.componenttype} ${c.data.objectid}`).sort(),+ associations: associations.map((a) => `${a.set}(${a.id}) ${a.nav} ${a.toSet}(${a.toId})`).sort(),+ pages: [...pageServer.state.projects.keys()].sort(),+ pageFiles: [...pageServer.state.files.keys()].sort(),+ pageMessages: [...pageServer.state.messages.keys()].sort(),+ };+ // A row is named by its id and name; the rows that have no name of their own — a role's grant, a component of a solution or of an+ // app — by what they link, so two inventories compare what the environment holds and not the ids a replace minted.+ const describe = {+ roleprivilegescollection: (d) => `${d.roleid} ${d.privilegeid} ${d.privilegedepthmask}`,+ solutioncomponents: (d) => `${d._solutionid_value} ${d.componenttype} ${d.objectid}`,+ appmodulecomponents: (d) => `${d._appmoduleidunique_value} ${d.componenttype} ${d.objectid}`,+ appsettings: (d) => `${d._parentappmoduleid_value} ${d._settingdefinitionid_value} ${d.value}`,+ };+ for (const [set, rows] of sets) {+ if (!rows.size) continue;+ const info = infoOfSet(set);+ out.rows[set] = [...rows.values()].map((row) => (describe[set] ? describe[set](row.data) : `${row.id} ${info && info.name ? row.data[info.name] : ''}`.trim())).sort();+ }+ return out;+ }++ // Everything the environment holds BY CONTENT, keyed by identity — the proof that a command left another maker's work (and the+ // system's own rows and definitions) as it found it, where `inventory()` only proves what exists:+ // `row <set> <id>` a row's saved AND published layers, whole: a view's FetchXML and LayoutXML, a form's XML, a web resource's+ // content, a setting's value, a role's grant, a sample row's columns+ // `table <logical>` a definition whole: its columns (with their lengths, formats, ranges and option sets), keys and privileges+ // `relationship <schema>` · `optionset <name>` (with its options) · `link <set>(<id>) <navigation> <set>(<id>)` (an N:N link)+ // `page <id>` · `page file <id>` · `page message <id>` · `page published <id>` a generative page, its files' content, its+ // conversation, and what its last publish made live+ // Each entry is `{ label, content }`, the content canonical (keys sorted, Maps as objects, bytes as base64). Nothing is normalized:+ // a row's `versionnumber` and `modifiedon` move on every write, and a publish that names a row moves its version — either is touching it.+ function contents() {+ const canon = (value) => {+ if (value instanceof Map) return canon(Object.fromEntries(value));+ if (value instanceof Set) return [...value].map(canon).sort();+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) return { base64: Buffer.from(value).toString('base64') };+ if (Array.isArray(value)) return value.map(canon);+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canon(value[key])]));+ return value;+ };+ const out = {};+ for (const [set, rows] of sets) {+ const info = infoOfSet(set);+ for (const row of rows.values()) {+ const name = info && info.name ? row.data[info.name] : null;+ out[`row ${set} ${row.id}`] = { label: `${set} ${row.id}${name ? ` "${name}"` : ''}`, content: canon({ saved: row.data, published: row.published }) };+ }+ }+ for (const table of metadata.tables.values()) out[`table ${table.LogicalName}`] = { label: `table ${table.LogicalName}`, content: canon(table) };+ for (const r of metadata.relationships.values()) out[`relationship ${r.SchemaName}`] = { label: `relationship ${r.SchemaName}`, content: canon(r) };+ for (const set of metadata.optionSets.values()) out[`optionset ${set.Name}`] = { label: `global option set ${set.Name}`, content: canon(set) };+ for (const a of associations) {+ const key = `link ${a.set}(${a.id}) ${a.nav} ${a.toSet}(${a.toId})`;+ out[key] = { label: key, content: true };+ }+ const pages = pageServer.state;+ for (const [id, project] of pages.projects) out[`page ${id}`] = { label: `page ${id} "${project.name}"`, content: canon(project) };+ for (const [id, file] of pages.files) out[`page file ${id}`] = { label: `page file ${id} "${file.filename}"`, content: canon(file) };+ for (const [id, message] of pages.messages) out[`page message ${id}`] = { label: `page message ${id}`, content: canon(message) };+ for (const [id, published] of pageServer.publishedPages) out[`page published ${id}`] = { label: `the published page ${id}`, content: canon(published) };+ return out;+ }++ return {+ origin,+ API,+ request,+ requests,+ unexpected,+ publishes,+ metadata,+ pageServer,+ associations,+ solutionComponents: () => componentRows().map((c) => clone(c.data)),+ rowsOf,+ infoOfSet,+ IDS,+ mark: () => requests.length,+ since: (mark) => requests.slice(mark),+ writes,+ writeNames,+ writeCounts: (since = 0) => countBy(writeNames(since)),+ readNames,+ readCounts: (since = 0) => countBy(readNames(since)),+ inventory,+ contents,+ // Rows whose saved layer holds a change no publish has copied.+ unpublished: () => [...sets].flatMap(([set, rows]) => (isLayered(set) ? [...rows.values()].filter((row) => row.publishedVersion !== row.version).map((row) => `${set} ${row.data.name || row.id}`) : [])),+ // A row by name, saved layer: what the platform holds whatever is published.+ find: (set, predicate) => [...rowsOf(set).values()].map((row) => row.data).filter(predicate),+ };+}++module.exports = { createLifecycleOrg, SYSTEM_TABLES, IDS };diff --git a/plugins/model-apps/scripts/tests/helpers/fake-verify-preload.js b/plugins/model-apps/scripts/tests/helpers/fake-verify-preload.jsnew file mode 100644index 000000000..9c2501fa6--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/fake-verify-preload.js@@ -0,0 +1,21 @@+'use strict';+// A `node --require` preload for END-TO-END runs of scripts/verify-model-app.js that need no environment. It replaces the four things that would reach one — the az-token HTTP+// client, the SDK factory, the page backend and the verification itself — so a real child process runs the real script, the real spec validation, the real throwaway workspace and+// the real `emitResult`, and the test sees what the process printed: its stdout bytes, its stderr and its exit status.+//+// The fake comes from the environment variable FAKE_VERIFY, a JSON object:+// result what the verification answers: { ok, checks: [{ kind, name, present }], missing: [{ kind, name, detail }], unverified: [text] }+// left the folders the page backend's `dispose()` says it could not remove (its `{ left }`)+//+// The script takes these by destructuring when it loads (the SDK factory, when it first needs one), which is after this preload, so replacing the exports here is what it receives.+const path = require('node:path');++const lib = path.resolve(__dirname, '..', '..', 'lib');+const options = JSON.parse(process.env.FAKE_VERIFY || '{}');++require(path.join(lib, 'sdk-http-client.js')).createAzHttpClient = (env) => ({ env });+const makerSdk = require(path.join(lib, 'maker-sdk.js'));+makerSdk.createNodeWorkspaceStorage = (root) => ({ root });+makerSdk.createMakerSdk = () => ({ initWorkspace: async () => {} });+require(path.join(lib, 'genpage-sdk.js')).makeGenpageSdk = () => ({ dispose: async () => ({ left: options.left || [] }) });+require(path.join(lib, 'verify-spec.js')).verifySpec = async () => options.result;diff --git a/plugins/model-apps/scripts/tests/helpers/form-store-harness.js b/plugins/model-apps/scripts/tests/helpers/form-store-harness.jsindex f738c3c93..55f557a8d 100644--- a/plugins/model-apps/scripts/tests/helpers/form-store-harness.js+++ b/plugins/model-apps/scripts/tests/helpers/form-store-harness.js@@ -12,6 +12,7 @@ const path = require('node:path');const { createMakerSdk, createNodeWorkspaceStorage } = require('../../vendor/cds-maker-sdk.cjs');const { verifySpec } = require('../../lib/verify-spec.js');const { readerFor } = require('../../verify-model-app.js');+const { EXPORT_PATH } = require('./translation-export.js');const guid = (n) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;const clone = (v) => JSON.parse(JSON.stringify(v));@@ -28,14 +29,17 @@ const onlyLanguages = (formxml, languages) => String(formxml).replace(/<label\b[// `languageCode` is the organization's base language, what a read of the organization answers. `sdkLanguageCode` is the language the SDK is MADE// for — the one the build writes its labels in, which `--language-code` can set apart from the organization's — and is the SDK's own default-// when it is left out.-function createHarness({ formId = guid(1), entity = 'new_ticket', formName = 'Main', attributes = DEFAULT_ATTRIBUTES, languageCode = 1033, sdkLanguageCode } = {}) {+// when it is left out. `createSdk` makes the SDK (the raw bundle's factory unless a test names another: the production factory over the production HTTP client, say).+function createHarness({ formId = guid(1), entity = 'new_ticket', formName = 'Main', attributes = DEFAULT_ATTRIBUTES, languageCode = 1033, sdkLanguageCode, createSdk = createMakerSdk } = {}) {const dirs = [];const store = { row: { formid: formId, name: formName, objecttypecode: entity, type: 2, isdefault: true } };// A form as a read returns it: whole, unless `store.readLanguages` (a list of LCIDs) limits the languages its labels are shown in.const shown = (row) => (store.readLanguages && row.formxml ? { ...clone(row), formxml: onlyLanguages(row.formxml, store.readLanguages) } : clone(row));const writes = [];const reads = [];+ // The translation exports a verify asked for. `store.exportTranslation` is what the platform answers one with — an `{ status, headers, body }`, or a function of the request body+ // that gives one — and a verify is given the reader's translationLabels only when it is set (see verifyForms), so a test that does not configure an export never reaches it.+ const exportsAsked = [];let revision = 1;const response = (body, status = 200) => ({ status, headers: { etag: `W/"${revision}"` }, body });const httpClient = {@@ -58,6 +62,11 @@ function createHarness({ formId = guid(1), entity = 'new_ticket', formName = 'Maassert.fail(`unexpected GET: ${url}`);},post: async (url, body) => {+ if (EXPORT_PATH.test(url)) {+ exportsAsked.push({ url, body: clone(body) });+ assert.ok(store.exportTranslation, 'a translation export was asked for, and this harness has none to answer with');+ return typeof store.exportTranslation === 'function' ? store.exportTranslation(body) : store.exportTranslation;+ }writes.push({ method: 'post', url, body: clone(body) });if (/\/systemforms(?:\?|$)/i.test(url)) {store.row = { ...store.row, ...body, formid: formId };@@ -80,7 +89,7 @@ function createHarness({ formId = guid(1), entity = 'new_ticket', formName = 'Maconst freshSdk = async (workspaceDir) => {const dir = workspaceDir || fs.mkdtempSync(path.join(os.tmpdir(), 'form-layout-rt-'));if (!workspaceDir) dirs.push(dir);- const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir),+ const sdk = createSdk({ workspaceStorage: createNodeWorkspaceStorage(dir),instanceUrl: 'https://contoso.crm.dynamics.com', httpClient, ...(sdkLanguageCode ? { languageCode: sdkLanguageCode } : {}) });await sdk.initWorkspace();const mutations = [];@@ -99,7 +108,7 @@ function createHarness({ formId = guid(1), entity = 'new_ticket', formName = 'Mareturn { sdk, mutations, dir };};const cleanup = () => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); };- return { store, writes, reads, freshSdk, cleanup, formId, entity, attributes };+ return { store, writes, reads, exportsAsked, freshSdk, cleanup, formId, entity, attributes };}// Put a form on the server the way the engine's create does — a minimal artifact, each compiled tab added@@ -114,7 +123,8 @@ async function seedForm(h, tabs, { name = 'Main', entity = h.entity } = {}) {return h.formId;}-// `--verify` over what the server holds, through the plugin's own reader (the published formxml query). `opts` are verifySpec's own.+// `--verify` over what the server holds, through the plugin's own reader (the published formxml query). `opts` are verifySpec's own. The reader also asks for a translation+// export (its translationLabels) when the harness has one to answer with (`store.exportTranslation`).async function verifyForms(h, spec, opts) {const fetched = await h.freshSdk();const live = readerFor(fetched.sdk, spec.app.uniqueName);@@ -124,6 +134,7 @@ async function verifyForms(h, spec, opts) {sitemapXml: async () => '',queryRecords: live.queryRecords,formTopology: live.formTopology,+ ...(h.store.exportTranslation ? { translationLabels: live.translationLabels } : {}),};return verifySpec(spec, read, opts);}diff --git a/plugins/model-apps/scripts/tests/helpers/huge-failure-preload.js b/plugins/model-apps/scripts/tests/helpers/huge-failure-preload.jsnew file mode 100644index 000000000..b0825417f--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/huge-failure-preload.js@@ -0,0 +1,29 @@+'use strict';+// Loaded with `node --require` ahead of a script, for tests/printers-whole-before-exit.test.js: makes a script's OWN failure printers print a text of+// HUGE_FAILURE_SIZE characters — with no command line that long (Windows allows 32,767 characters, Linux 128 KiB per argument):+// HUGE_FAILURE=flag validateFlags (lib/dataverse-auth.js) answers every call with a message that long, which each script prints as its usage error+// (check-auth.js as the message of its usage blocker, on stdout);+// HUGE_FAILURE=throw parseArgs throws an error with that message, which a script whose main rejects prints from its last-resort handler.+// Everything else is the real module, and the code that prints the text and ends the process is the script's own. A test requires this file for+// hugeFailureText (HUGE_FAILURE is not set in the test's own process, so nothing is replaced there).+const path = require('node:path');++// The text, recognisable at both ends so that a test can tell a whole one from one cut short.+function hugeFailureText(kind, size) {+ return `${kind}-failure<${'0123456789'.repeat(Math.ceil(size / 10)).slice(0, size)}>`;+}++module.exports = { hugeFailureText };++if (process.env.HUGE_FAILURE) {+ const target = require.resolve(path.join(__dirname, '..', '..', 'lib', 'dataverse-auth.js'));+ const real = require(target);+ const kind = process.env.HUGE_FAILURE;+ const text = hugeFailureText(kind, Number(process.env.HUGE_FAILURE_SIZE || 0));+ // A script takes its helpers from the module cache when it is loaded, so it is handed this object.+ require.cache[target].exports = {+ ...real,+ ...(kind === 'flag' ? { validateFlags: () => text } : {}),+ ...(kind === 'throw' ? { parseArgs: () => { throw new Error(text); } } : {}),+ };+}diff --git a/plugins/model-apps/scripts/tests/helpers/import-job-logs.js b/plugins/model-apps/scripts/tests/helpers/import-job-logs.jsnew file mode 100644index 000000000..10f6b592c--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/import-job-logs.js@@ -0,0 +1,129 @@+'use strict';+// Import-job logs and rows, in the shapes the platform was measured to write them — made up here, not copied: every name is `contoso_…` and nothing in+// a log is an environment's. `importjobs(<id>)` has a `data` column holding the import's log, an XML document the platform writes as the import goes:+//+// running <importexportxml><solutionManifests><solutionManifest languagecode="1033"> … <results /> … (no attribute on the root, no `processed` anywhere,+// `completedon` null)+// finished <importexportxml start=… stop=… progress=… processed="true" errorcode="0" succeeded="success" status=""> … every node processed="true" …+// refused <importexportxml … processed="true" errorcode="-2147020463" succeeded="failure" status="Cannot start another [Import] because there is a previous+// [Import] running at this moment. …"> — `errorcode` is 0x80071151 as a signed 32-bit integer — with `solutionManifest` and every component+// processed="false" and only the package's own checks (`upgradeHandler`, `validateHandler`) processed="true": the import stopped at the lock+// before it applied anything+// failed the same root with errorcode="-2147188685" (0x80048033) and `solutionManifest processed="true"`: an import that failed AFTER it began+//+// Used by tests/import-job-proof.test.js (the rule), tests/solution-settings.test.js and tests/solution-settings-real-bundle.test.js (the resend).++const LOCK_ERRORCODE = '-2147020463';+const FAILED_AFTER_START_ERRORCODE = '-2147188685';+const REFUSAL_STATUS = 'Cannot start another [Import] because there is a previous [Import] running at this moment. Use Solution History for more details. -- The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later.';++const esc = (value) => String(value).replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');+// ` name="value"` for every attribute that is set: an attribute left `undefined` is not written, which is how a log that has not got to it yet looks.+const attrs = (values) => Object.entries(values || {}).filter(([, value]) => value !== undefined).map(([name, value]) => ` ${name}="${esc(value)}"`).join('');+const node = (name, values, inner) => (inner === undefined ? `<${name}${attrs(values)} />` : `<${name}${attrs(values)}>${inner}</${name}>`);++// What the platform writes under a node it has applied.+const STEP = '<result result="success" errorcode="0" errortext="" datetime="12:00:00.00" datetimeticks="639000000000000000" />';++function manifestNode(processed, finished) {+ return node('solutionManifest', { languagecode: '1033', id: 'contoso_sol', LocalizedName: 'Contoso solution', processed },+ '<UniqueName>contoso_sol</UniqueName><LocalizedNames><LocalizedName description="Contoso solution" languagecode="1033" /></LocalizedNames>'+ + '<Descriptions><Description description="A solution" languagecode="1033" /></Descriptions><Version>1.0.0.0</Version><Managed>0</Managed>'+ + '<Publisher><UniqueName>contoso</UniqueName><LocalizedNames><LocalizedName description="Contoso" languagecode="1033" /></LocalizedNames><EMailAddress /><SupportingWebsiteUrl />'+ + '<Addresses><Address><City /><Country /><Line1 /><Line2 /><PostalCode /><StateOrProvince /><Telephone1 /></Address></Addresses></Publisher>'+ + (finished ? `<results>${STEP}</results>` : '<results />'));+}++/**+ * The log of an import, as text.+ * root the attributes of `<importexportxml>`; `null` for the bare element of a running import+ * manifest `processed` of `<solutionManifest>` (`undefined`: the attribute is not written)+ * components `processed` of every table and of what is imported with it (`savedQuery`, `formXml`, `entityRibbon`, `rootComponent`, `dependency`, …);+ * `undefined` for the skeleton of a running import, which lists the tables and nothing else+ * handlers `processed` of the package's own checks — `upgradeHandler` ×5 and `validateHandler` — or `null` when they have not run yet+ * finished write a `<result>` under the manifest and each component, as an import that applied them does+ * tables how many tables the package holds+ * extra XML added at the end of the root element+ */+function importLog({ root = null, manifest, components, handlers = null, finished = false, tables = 3, extra = '' } = {}) {+ const ids = Array.from({ length: tables }, (_, i) => `contoso_alpha${i + 1}`);+ const under = finished ? STEP : '';+ const named = (name, id) => node(name, { LocalizedName: `Alpha ${id}`, ExistingLocalizedName: `Alpha ${id}`, OriginalName: `Alpha ${id}`, Description: 'A table', id, processed: components }, under);+ const entities = ids.map((id) => named('entity', id)).join('');+ const subhandlers = ids.map((id) => ['savedQuery', 'formXml', 'entityRibbon'].map((name) => named(name, id)).join('')).join('');+ const checks = handlers === null ? ''+ : `<upgradeHandlers>${['UpdateRolesDepthLevel', 'RemoveContactParentContactRelationship', 'RemoveParentContactIdAttribute', 'RemoveParentContactMissingDependencyNode', 'UpdateMacrosCategoryAttribute']+ .map((id) => node('upgradeHandler', { id, LocalizedName: 'Transform Package', Description: 'Transform Package', processed: handlers }, STEP)).join('')}</upgradeHandlers>`+ + `<skuHandlers /><validateHandlers>${node('validateHandler', { id: 'XSDValidationHandler', LocalizedName: 'Package Validation', Description: 'Validates solution package schema.', processed: handlers }, STEP)}</validateHandlers>`;+ const inner = `<solutionManifests>${manifestNode(manifest, finished)}</solutionManifests>`+ + '<upgradeSolutionPackageInformation><upgradeRequired>1</upgradeRequired><upgradeValid>1</upgradeValid><fileVersion>9.2.0.0</fileVersion><currentVersion>9.2.1.1</currentVersion></upgradeSolutionPackageInformation>'+ + `<entities>${entities}</entities><AppModules /><AppModuleSiteMaps /><workflows /><webResources /><customControls /><reports /><languages><language /></languages>`+ + (components === undefined ? '' : `<entitySubhandlers>${subhandlers}</entitySubhandlers>`+ + `<rootComponents>${node('rootComponent', { processed: components }, finished ? STEP : undefined)}</rootComponents>`+ + `<dependencies>${node('dependency', { processed: components }, finished ? STEP : undefined)}</dependencies>`+ + `<workflowAndStepActivations>${node('workflowAndStepActivation', { processed: components }, finished ? STEP : undefined)}</workflowAndStepActivations>`)+ + checks + extra;+ return node('importexportxml', root || undefined, inner);+}++const rootOf = ({ errorcode, succeeded, status, progress = '17.1428571428571', processed = 'true' }) => ({ start: '639280238592671053', stop: '639280238604238275', progress, processed, errorcode, succeeded, status });++// Each kind of state the measurement captured, as a log.+const LOGS = {+ // The skeleton a running import starts with: nothing is processed, and the root has no attribute.+ running: (options) => importLog({ tables: 1, ...options }),+ // An import that applied the package: everything processed, the root says it succeeded.+ succeeded: (options) => importLog({ root: rootOf({ errorcode: '0', succeeded: 'success', status: '', progress: '100' }), manifest: 'true', components: 'true', handlers: 'true', finished: true, ...options }),+ // An import the platform refused at its customization lock before it applied anything: what the rule accepts.+ refused: (options) => importLog({ root: rootOf({ errorcode: LOCK_ERRORCODE, succeeded: 'failure', status: REFUSAL_STATUS }), manifest: 'false', components: 'false', handlers: 'true', ...options }),+ // An import that failed after it began (a managed package over an unmanaged solution, a missing dependency): the manifest was processed.+ failedAfterStart: (options) => importLog({ root: rootOf({ errorcode: FAILED_AFTER_START_ERRORCODE, succeeded: 'failure', status: 'The import failed.', progress: '43.75' }), manifest: 'true', components: 'false', handlers: 'true', ...options }),+ // A log caught between two writes: the row is complete but the root has not been given its verdict yet.+ unfinishedRoot: (options) => importLog({ root: { start: '639280238592671053', stop: '639280238604238275', progress: '17.1428571428571', processed: 'true' }, manifest: 'false', components: 'false', handlers: 'true', ...options }),+};++const COMPLETED_ON = '2026-01-01T12:00:03Z';+const ORIGIN = 'https://contoso.crm.dynamics.com';+/**+ * The answer of `GET importjobs(<id>)?$select=importjobid,completedon,data` for a log: `completedon` is set when the job is `completed` (the default) and null while it runs.+ * Anything else of the row is overridden by what is passed.+ */+function jobRow(data, { id = '44444444-4444-4444-8444-444444444444', completed = true, ...rest } = {}) {+ return {+ '@odata.context': `${ORIGIN}/api/data/v9.2/$metadata#importjobs(importjobid,completedon,data)/$entity`,+ importjobid: id,+ completedon: completed ? COMPLETED_ON : null,+ data,+ ...rest,+ };+}+// A Web API answer — what a transport returns and the platform fake's `jobLogAnswer` is — carrying a row.+const jobAnswer = (row, statusCode = 200) => ({ statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify(row) });++/**+ * The 347 states of an import job's row that the measurement captured — twenty imports, each read every 250–500 ms until nothing changed — as fourteen kinds. `count` is how many of+ * the 347 were of the kind, `completed` whether the row had `completedon` set, and `group` which of the measurement's five groups it belongs to:+ * running-or-early-success 308 a running import's skeleton, and a finished one's row between two writes+ * success-final 17 an import that applied the package, final row+ * refused-early 9 a refused import's row before its final write (the platform had not answered yet)+ * failed-after-start 5 an import that began and failed (a managed package over an unmanaged solution, a missing dependency)+ * refused-final 8 a refused import's FINAL row: the only states the rule may accept+ */+const CAPTURED_STATES = [+ { name: 'a running import of a 6-table package: the skeleton', count: 190, completed: false, group: 'running-or-early-success', data: () => LOGS.running({ tables: 6 }) },+ { name: 'a running import of a 1-table package: the skeleton', count: 117, completed: false, group: 'running-or-early-success', data: () => LOGS.running({ tables: 1 }) },+ { name: 'an import of a 1-table package that applied it: the final row', count: 10, completed: true, group: 'success-final', data: () => LOGS.succeeded({ tables: 1 }) },+ { name: 'an import of a 6-table package that applied it: the final row', count: 7, completed: true, group: 'success-final', data: () => LOGS.succeeded({ tables: 6 }) },+ { name: 'a refused import of a 6-table package, read before its final write', count: 5, completed: false, group: 'refused-early', data: () => LOGS.running({ tables: 6 }) },+ { name: 'a refused import of a 6-table package: the FINAL row', count: 5, completed: true, group: 'refused-final', data: () => LOGS.refused({ tables: 6 }) },+ { name: 'a refused import of a 1-table package, read before its final write', count: 3, completed: false, group: 'refused-early', data: () => LOGS.running({ tables: 1 }) },+ { name: 'a refused import of a 1-table package: the FINAL row', count: 3, completed: true, group: 'refused-final', data: () => LOGS.refused({ tables: 1 }) },+ { name: 'a managed package over an unmanaged solution, early', count: 2, completed: false, group: 'failed-after-start', data: () => LOGS.running({ tables: 1 }) },+ { name: 'a managed package over an unmanaged solution: the final row', count: 1, completed: true, group: 'failed-after-start', data: () => LOGS.failedAfterStart({ tables: 1 }) },+ { name: 'a package with a missing dependency, early', count: 1, completed: false, group: 'failed-after-start', data: () => LOGS.running({ tables: 1 }) },+ { name: 'a package with a missing dependency: the final row', count: 1, completed: true, group: 'failed-after-start', data: () => LOGS.failedAfterStart({ tables: 1 }) },+ { name: 'an import that applied a package, row complete but its root not yet written', count: 1, completed: true, group: 'running-or-early-success', data: () => LOGS.unfinishedRoot({ manifest: 'true', components: 'true', finished: true, tables: 1 }) },+ { name: 'a refused import, row complete but its root not yet written', count: 1, completed: true, group: 'refused-early', data: () => LOGS.unfinishedRoot({ tables: 6 }) },+];++module.exports = { importLog, LOGS, rootOf, jobRow, jobAnswer, CAPTURED_STATES, LOCK_ERRORCODE, FAILED_AFTER_START_ERRORCODE, REFUSAL_STATUS, COMPLETED_ON, ORIGIN };diff --git a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.jsnew file mode 100644index 000000000..c32ef222f--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js@@ -0,0 +1,400 @@+'use strict';+// The harness the lifecycle tests share (lifecycle-matrix-real-bundle.test.js, lifecycle-scenarios-real-bundle.test.js): the+// kitchen-sink App Spec, and each command of the lifecycle run the way its CLI runs it — over the REAL vendored SDK, the plugin's own+// az-token HTTP client and a stateful fake Dataverse (helpers/fake-lifecycle-org.js) — so a test reads what reached the wire and what+// the environment holds afterwards. Nothing here is a stand-in for plugin code: build, download, verify and teardown are the scripts' own+// entry points, given the seams their CLIs give them (the SDK instances, the page backend, the auth probe).+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 { buildModelApp } = require('../../build-model-app.js');+const { verifySpec } = require('../../lib/verify-spec.js');+const { readerFor } = require('../../verify-model-app.js');+const { appUniqueName } = require('../../lib/sdk-build.js');+const { makeGenpageSdk } = require('../../lib/genpage-sdk.js');+const { PHASES } = require('../../lib/stages.js');+const download = require('../../download-model-app.js');+const { teardownModelApp } = require('../../teardown-model-app.js');++// A token long enough for the client's scrubber, never sent anywhere: the transport is the fake.+const TOKEN = 'lifecycle-matrix-token-0123456789';+const PAGE_SOURCE = "import * as React from 'react';\nexport default function KitchenPage() { return <div>Kitchen</div>; }\n";+const ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M2 2h12v12H2z"/></svg>';++// Every feature the fake models faithfully (see the header of lifecycle-matrix-real-bundle.test.js for what is left out, and why).+function kitchenSinkSpec() {+ return {+ schemaVersion: 2,+ minimumPluginVersion: '2.13.0',+ solution: { uniqueName: 'ContosoKitchen', displayName: 'Contoso Kitchen', publisherPrefix: 'contoso', description: 'Every App Spec feature in one app.' },+ app: { name: 'Kitchen Sink', description: 'One app that uses every feature.', headerNavigationRefresh: false, newLook: true, tables: ['contact'] },+ globalChoices: [{ name: 'contoso_stage', displayName: 'Stage', options: ['Planned', 'Active', 'Done'] }],+ entities: [+ {+ schemaName: 'contoso_project', displayName: 'Project', pluralName: 'Projects', description: 'A unit of work.', vectorIcon: 'contoso_projecticon.svg',+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },+ statusReasons: [{ label: 'In Review', state: 'Active' }],+ alternateKeys: [{ schemaName: 'contoso_emailkey', displayName: 'Email Key', columns: ['contoso_email'] }],+ columns: [+ { schemaName: 'contoso_email', displayName: 'Contact Email', type: 'Text', format: 'Email', maxLength: 200 },+ { schemaName: 'contoso_notes', displayName: 'Notes', type: 'Memo' },+ { schemaName: 'contoso_priority', displayName: 'Priority', type: 'Choice', options: ['Low', 'Medium', 'High'] },+ { schemaName: 'contoso_stage', displayName: 'Stage', type: 'Choice', globalChoice: 'contoso_stage' },+ { schemaName: 'contoso_labels', displayName: 'Labels', type: 'MultiChoice', options: ['Red', 'Green', 'Blue'] },+ { schemaName: 'contoso_billable', displayName: 'Billable', type: 'Boolean', trueLabel: 'Yes', falseLabel: 'No' },+ { schemaName: 'contoso_budget', displayName: 'Budget', type: 'Money' },+ { schemaName: 'contoso_due', displayName: 'Due', type: 'DateTime', dateFormat: 'DateOnly' },+ { schemaName: 'contoso_headcount', displayName: 'Headcount', type: 'Integer', minValue: 0, maxValue: 500 },+ { schemaName: 'contoso_bytes', displayName: 'Bytes', type: 'BigInt' },+ { schemaName: 'contoso_rate', displayName: 'Rate', type: 'Decimal', precision: 2 },+ { schemaName: 'contoso_score', displayName: 'Score', type: 'Double' },+ { schemaName: 'contoso_ref', displayName: 'Reference', type: 'AutoNumber', autoNumberFormat: 'P-{SEQNUM:5}' },+ { schemaName: 'contoso_contract', displayName: 'Contract', type: 'File', maxSizeKb: 1024 },+ { schemaName: 'contoso_logo', displayName: 'Logo', type: 'Image' },+ ],+ },+ {+ schemaName: 'contoso_task', displayName: 'Task Item', pluralName: 'Task Items', description: 'A step of a project.',+ primaryAttribute: { schemaName: 'contoso_title', displayName: 'Title' },+ columns: [+ { schemaName: 'contoso_hours', displayName: 'Hours', type: 'Integer' },+ { schemaName: 'contoso_done', displayName: 'Done', type: 'Boolean' },+ { schemaName: 'contoso_customer', displayName: 'Customer', type: 'Customer' },+ ],+ },+ // A plural that is not "<displayName>s": the round trip has to carry it, since a rebuild elsewhere cannot derive it.+ { schemaName: 'contoso_tag', displayName: 'Tag', pluralName: 'Tag Catalog', description: 'A label for tasks.', primaryAttribute: { schemaName: 'contoso_label', displayName: 'Label' }, columns: [] },+ ],+ relationships: [+ { type: 'OneToMany', referenced: 'contoso_project', referencing: 'contoso_task', lookup: { schemaName: 'contoso_ProjectId', displayName: 'Project' } },+ { type: 'OneToMany', referenced: 'contoso_project', referencing: 'contoso_project', lookup: { schemaName: 'contoso_ParentProjectId', displayName: 'Parent Project' } },+ { type: 'ManyToMany', entity1: 'contoso_task', entity2: 'contoso_tag' },+ ],+ webResources: [+ { name: 'contoso_project.js', displayName: 'Project Scripts', type: 'js', content: 'var Project={onLoad:function(ctx){},escalate:function(ctx){}};' },+ { name: 'contoso_projecticon.svg', displayName: 'Project Icon', type: 'svg', content: ICON_SVG },+ ],+ views: [+ { entity: 'contoso_project', name: 'Open Projects', description: 'Projects still running.', columns: ['contoso_name', 'contoso_priority', 'contoso_stage', 'contoso_due'], sort: [{ attr: 'contoso_name', dir: 'asc' }], filters: [{ attr: 'contoso_priority', op: 'eq', value: 'High' }] },+ { entity: 'contoso_task', name: 'Open Tasks', columns: ['contoso_title', 'contoso_hours'] },+ { entity: 'contoso_task', name: 'My Open Tasks', columns: ['contoso_title', 'contoso_hours'], filters: [{ attr: 'ownerid', op: 'eq-userid' }, { attr: 'contoso_done', op: 'eq', value: 0 }] },+ ],+ charts: [{ entity: 'contoso_project', name: 'Projects by Priority', chartType: 'Pie', groupBy: 'contoso_priority', measure: 'count', description: 'Workload by priority.' }],+ forms: [+ {+ entity: 'contoso_project', name: 'Project', layout: 'auto', description: 'The project record.', notes: true,+ subgrids: [{ childEntity: 'contoso_task', view: 'Open Tasks', label: 'Tasks' }],+ events: [{ event: 'onload', library: 'contoso_project.js', function: 'Project.onLoad' }],+ securityRoles: { personas: ['Kitchen Planner'], fallbackForm: true, order: 0 },+ },+ { entity: 'contoso_task', name: 'Task Quick Create', formType: 'QuickCreate', layout: 'auto' },+ { entity: 'contoso_project', name: 'Project Card', formType: 'QuickView', layout: 'auto' },+ { entity: 'contoso_task', name: 'Task', layout: 'auto', quickViews: [{ lookup: 'contoso_projectid', targetEntity: 'contoso_project', form: 'Project Card', label: 'Project' }] },+ ],+ commands: [+ { entity: 'contoso_project', label: 'Escalate', location: 'MainTab', library: 'contoso_project.js', function: 'Project.escalate' },+ { entity: 'contoso_project', label: 'More', type: 'FlyoutAnchor', children: [{ label: 'Approve', library: 'contoso_project.js', function: 'Project.escalate' }] },+ ],+ dashboards: [{+ name: 'Kitchen Overview', description: 'Project health.', tiles: [+ { type: 'chart', chart: 'Projects by Priority', view: 'Open Projects' },+ { type: 'list', view: 'Open Projects', name: 'Open' },+ { type: 'iframe', url: 'https://contoso.example/status', name: 'Status', colspan: 2, rowspan: 8 },+ ],+ }],+ pages: [{ key: 'overview', name: 'Kitchen Page', purpose: 'A page over projects.', dataSources: ['contoso_project'], source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' } }],+ appShell: {+ areas: [{+ label: 'Work',+ groups: [{+ label: 'Records',+ subAreas: [+ { entity: 'contoso_project', title: 'Projects' },+ { entity: 'contoso_task', title: 'Tasks' },+ { entity: 'contoso_tag', title: 'Tags' },+ { dashboard: 'Kitchen Overview', title: 'Overview' },+ { url: 'https://contoso.example/help', title: 'Help' },+ { page: 'overview', title: 'Kitchen Page' },+ ],+ }],+ }],+ },+ sampleData: {+ contoso_project: [{ contoso_name: 'Apollo', contoso_priority: 'High', contoso_stage: 'Active', contoso_billable: true, contoso_headcount: 4, statusReason: 'In Review' }],+ contoso_task: [{ contoso_title: 'Kickoff', contoso_hours: 2, $parent: { entity: 'contoso_project', match: { contoso_name: 'Apollo' } } }],+ },+ personas: [{+ persona: 'Kitchen Planner',+ jobs: [{ name: 'Plan projects', surfaces: ['Open Projects', 'Project'], privileges: [{ entity: 'contoso_project', access: ['read', 'write', 'create'], scope: 'businessUnit' }, { entity: 'contoso_task', access: ['read'], scope: 'user' }] }],+ }],+ roleGrants: [{ role: 'Basic User', privileges: [{ entity: 'contoso_tag', access: ['read'], scope: 'organization' }] }],+ };+}++// 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) {+ const appDir = path.join(root, 'app');+ const workspaceDir = path.join(appDir, '.maker-workspace');+ fs.mkdirSync(workspaceDir, { recursive: true });+ fs.writeFileSync(path.join(appDir, 'KitchenPage.tsx'), PAGE_SOURCE);+ // The production client, over the fake's transport: retries, change sets and the token scrubber are the ones a maker runs.+ const client = createAzHttpClient(org.origin, { getToken: () => TOKEN, request: org.request, sleep: async () => {} });+ const throwaway = (prefix) => fs.mkdtempSync(path.join(root, prefix));++ // build-model-app.js: the two SDK instances its makeSdk makes — one that names the solution, and the header-less one that owns the app+ // folder's workspace and recovers a form create whose answer was lost — and the deps its main() hands buildModelApp.+ async function build(spec, { apply = true, publish = true, sampleData = true, verify = true, appFolder = appDir, workspace = workspaceDir } = {}) {+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('sdk-')), instanceUrl: org.origin, httpClient: client, solutionUniqueName: spec.solution.uniqueName, languageCode: 1033 });+ const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(apply ? workspace : throwaway('preview-')), instanceUrl: org.origin, httpClient: client, languageCode: 1033, createRecovery: 'adoptExact' });+ await provisionSdk.initWorkspace();+ const genpage = makeGenpageSdk(org.origin, { httpClient: client });+ const warnings = [];+ const log = [];+ try {+ const result = await buildModelApp(spec, {+ apply, publish, sampleData, verify, phases: PHASES, profile: apply ? 'deploy' : 'plan', nonInteractive: false,+ appDir: appFolder, env: org.origin, workspaceDir: workspace, preResolvedLanguageCode: apply ? 1033 : undefined,+ }, {+ sdk, provisionSdk, genpage, sleep: async () => {}, warn: (m) => warnings.push(String(m)), log: (m) => log.push(String(m)), provisionedLanguages: async () => [1033],+ verify: async (s, o) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpage, workspaceDir: workspace }), o),+ });+ return { result, warnings, log };+ } finally {+ await genpage.dispose();+ }+ }++ // download-model-app.js main(), with the seams it gives: the result printer, the process exit, the auth probe, the HTTP client.+ async function downloadApp(appUnique, outDir) {+ let emitted;+ const stderr = [];+ // runDownload writes its WARNING lines to process.stderr itself (main's `stderr` seam carries the rest): both are what the maker reads.+ const write = process.stderr.write;+ process.stderr.write = (text) => { stderr.push(String(text)); return true; };+ try {+ await download.main({+ argv: ['--env', org.origin, '--app', appUnique, '--out', outDir],+ stderr: { write: (text) => { stderr.push(String(text)); return true; } },+ exit: (code) => { throw new Error(`download exited ${code}: ${stderr.join('')}`); },+ emitResult: (ok, payload) => { emitted = { ok, payload }; },+ preflightAuth: async () => ({ ok: true }),+ httpClient: client,+ });+ } finally {+ process.stderr.write = write;+ }+ const specPath = path.join(outDir, 'app-spec.json');+ return { emitted, stderr: stderr.join(''), spec: fs.existsSync(specPath) ? JSON.parse(fs.readFileSync(specPath, 'utf8')) : null, dir: outDir, text: fs.existsSync(specPath) ? fs.readFileSync(specPath, 'utf8') : null };+ }++ // verify-model-app.js: a throwaway SDK workspace, the page backend's own; the app folder is only read, for the build's baseline.+ async function verify(spec, { workspace = workspaceDir } = {}) {+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('verify-')), instanceUrl: org.origin, httpClient: client });+ await sdk.initWorkspace();+ const genpage = makeGenpageSdk(org.origin, { httpClient: client });+ try {+ return await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpage, workspaceDir: workspace }), { languageCode: 1033 });+ } finally {+ await genpage.dispose();+ }+ }++ // teardown-model-app.js: a throwaway SDK workspace; the build's workspace is where it fences the changed-only snapshot.+ async function teardown(spec, { apply = true, workspace = workspaceDir } = {}) {+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('teardown-')), instanceUrl: org.origin, httpClient: client });+ await sdk.initWorkspace();+ const log = [];+ const result = await teardownModelApp(spec, { apply, allowDestructive: apply, workspaceDir: workspace, env: org.origin }, { sdk, log: (m) => log.push(String(m)) });+ return { result, log };+ }++ // Runs `fn` and records what it sent: the writes per `METHOD resource`, the reads, every request, what the fake did not model, how long+ // it took, and what is left saved but unpublished. A throw is recorded, not raised, so a caller can still read what was sent.+ async function measure(fn) {+ const mark = org.mark();+ const unexpected = org.unexpected.length;+ const started = performance.now();+ const record = { mark };+ try {+ record.value = await fn();+ } catch (error) {+ record.error = error;+ }+ record.ms = Math.round(performance.now() - started);+ record.end = org.mark();+ record.writes = org.writeCounts(mark);+ record.reads = org.requests.slice(mark, record.end).filter((r) => r.method === 'GET').length;+ record.unexpected = org.unexpected.slice(unexpected);+ record.unpublished = org.unpublished();+ return record;+ }++ return { client, appDir, workspaceDir, build, download: downloadApp, verify, teardown, measure };+}++// Another maker's work, already in the environment before the kitchen sink is built: a solution of another publisher with a table (and+// on it a view that has the same name as one of the spec's views), an app with its navigation, a generative page, a web resource, a+// global choice and a security role. A build must not touch any of it, and a teardown must leave every row of it where it was — which+// a test proves by comparing the inventory before and after. It is created through the fake's own transport, as the maker's tools would.+const FOREIGN = {+ publisher: '22222222-0000-4000-8000-000000000001',+ solution: '22222222-0000-4000-8000-000000000002',+ app: '22222222-0000-4000-8000-000000000003',+ sitemap: '22222222-0000-4000-8000-000000000004',+ page: '22222222-0000-4000-8000-000000000005',+};+async function seedForeignWork(org) {+ const send = async (method, where, body, headers = {}) => {+ const res = await org.request({ url: `${org.API}${where}`, method, headers: { 'Content-Type': 'application/json', ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });+ if (res.statusCode >= 300) throw new Error(`seeding ${method} ${where} answered ${res.statusCode}: ${res.body}`);+ };+ const label = (text) => ({ LocalizedLabels: [{ Label: text, LanguageCode: 1033 }] });+ const inSolution = { 'MSCRM.SolutionUniqueName': 'FabrikamCore' };+ await send('POST', '/publishers', { publisherid: FOREIGN.publisher, uniquename: 'fabrikam', friendlyname: 'Fabrikam', customizationprefix: 'fabrikam', customizationoptionvalueprefix: 20000 });+ await send('POST', '/solutions', { solutionid: FOREIGN.solution, uniquename: 'FabrikamCore', friendlyname: 'Fabrikam Core', version: '1.0.0.0', '[email protected]': `/publishers(${FOREIGN.publisher})` });+ await send('POST', '/EntityDefinitions', { '@odata.type': 'Microsoft.Dynamics.CRM.EntityMetadata', SchemaName: 'fabrikam_widget', DisplayName: label('Widget'), DisplayCollectionName: label('Widgets'), OwnershipType: 'UserOwned', HasNotes: false, HasActivities: false, Attributes: [{ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata', SchemaName: 'fabrikam_name', IsPrimaryName: true, MaxLength: 100, DisplayName: label('Name'), RequiredLevel: { Value: 'None' } }] }, inSolution);+ await send('POST', '/savedqueries', { name: 'Open Projects', returnedtypecode: 'fabrikam_widget', querytype: 0, fetchxml: '<fetch version="1.0" mapping="logical"><entity name="fabrikam_widget"><attribute name="fabrikam_name" /></entity></fetch>', layoutxml: '<grid name="resultset" object="10400" jump="fabrikam_name" select="1" icon="1" preview="1"><row name="result" id="fabrikam_widgetid"><cell name="fabrikam_name" width="300" /></row></grid>' }, inSolution);+ await send('POST', '/GlobalOptionSetDefinitions', { '@odata.type': 'Microsoft.Dynamics.CRM.OptionSetMetadata', Name: 'fabrikam_size', DisplayName: label('Size'), IsGlobal: true, OptionSetType: 'Picklist', Options: [{ Value: 200000000, Label: label('Small') }] }, inSolution);+ await send('POST', '/webresourceset', { name: 'fabrikam_widget.js', displayname: 'Widget Scripts', webresourcetype: 3, content: Buffer.from('var Widget = {};').toString('base64') }, inSolution);+ await send('POST', '/roles', { name: 'Fabrikam Reader', '[email protected]': '/businessunits(11111111-0000-4000-8000-000000000002)' }, inSolution);+ await send('POST', '/appmodules', { appmoduleid: FOREIGN.app, name: 'Fabrikam Widgets', uniquename: 'fabrikam_widgets', clienttype: 4 });+ await send('POST', '/sitemaps', { sitemapid: FOREIGN.sitemap, sitemapnameunique: 'fabrikam_widgets', sitemapname: 'Fabrikam Widgets', sitemapxml: '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_0"><Group Id="group_0"><SubArea Id="sub_0" Entity="fabrikam_widget" /></Group></Area></SiteMap>' });+ await send('POST', '/AddAppComponents', { AppId: FOREIGN.app, Components: [{ '@odata.type': 'Microsoft.Dynamics.CRM.sitemap', sitemapid: FOREIGN.sitemap }] });+ await send('POST', '/PublishXml', { ParameterXml: `<importexportxml><entities><entity>fabrikam_widget</entity></entities><appmodules><appmodule>${FOREIGN.app}</appmodule></appmodules></importexportxml>` });+ // A generative page of the other app, published.+ org.pageServer.seedPage(FOREIGN.page, { name: 'Widget Board' });+ org.pageServer.publishProject(org.pageServer.state, FOREIGN.page);+}++// What the environment holds of each feature of the kitchen-sink spec, read from the fake's state (not from what a build reports): the+// deployed facts the matrix compares with the spec, and a recovery test compares with a clean build's.+function deployedFeatures(org) {+ const label = (l) => (l && l.UserLocalizedLabel ? l.UserLocalizedLabel.Label : null);+ const tables = {};+ for (const t of org.metadata.tables.values()) {+ if (!t.LogicalName.startsWith('contoso_')) continue;+ // The columns a maker sees: custom, not the table's id, not the companion of another column — and not a Money column's+ // base-currency twin, which is a physical custom column with no AttributeOf, told apart only by `IsBaseCurrency`+ // (fake-lifecycle-metadata.js companionsOf). An Image column is the one column that is `AttributeOf` something and still a column+ // (it is the projection of its `<name>id`, MEASURED live), and that `<name>id` is a custom Uniqueidentifier that is `AttributeOf`+ // nothing — no App Spec column is a Uniqueidentifier, so none is listed.+ const fileOrImage = (a) => ['FileType', 'ImageType'].includes(a.AttributeTypeName && a.AttributeTypeName.Value);+ const attributes = [...t.Attributes.values()].filter((a) => a.IsCustomAttribute && (!a.AttributeOf || fileOrImage(a)) && !a.IsPrimaryId && a.AttributeType !== 'Uniqueidentifier' && a.IsBaseCurrency !== true);+ // A column as `<AttributeTypeName> <RequiredLevel>` and then what its type carries: a text format and length, a whole number's+ // format and range, a decimal's precision, an auto-number format, a file's size, a Boolean's two labels, a choice's options (and+ // whether they are a global set's), a lookup's targets.+ const detail = (a) => [+ a.AttributeTypeName.Value, a.RequiredLevel.Value,+ ...(a.FormatName && a.FormatName.Value !== 'Text' ? [a.FormatName.Value] : []), ...(a.Format ? [a.Format] : []),+ ...(a.MaxLength !== undefined && a.AttributeType === 'String' ? [`max ${a.MaxLength}`] : []),+ ...(a.MinValue !== undefined || a.MaxValue !== undefined ? [`${a.MinValue}..${a.MaxValue}`] : []),+ ...(a.Precision !== undefined ? [`precision ${a.Precision}`] : []),+ ...(a.AutoNumberFormat ? [a.AutoNumberFormat] : []),+ ...(a.MaxSizeInKB !== undefined ? [`${a.MaxSizeInKB} KB`] : []),+ ...(a.OptionSet && a.OptionSet.TrueOption ? [`${label(a.OptionSet.TrueOption.Label)}/${label(a.OptionSet.FalseOption.Label)}`] : []),+ ...(a.OptionSet && a.OptionSet.Options.length ? [`${a.OptionSet.IsGlobal ? 'global ' : ''}${a.OptionSet.Options.map((o) => label(o.Label)).join('|')}`] : []),+ ...(a.Targets ? [a.Targets.join('|')] : []),+ ].join(' ');+ tables[t.LogicalName] = {+ plural: label(t.DisplayCollectionName),+ icon: t.IconVectorName || null,+ quickCreate: t.IsQuickCreateEnabled === true,+ intersect: t.IsIntersect || undefined,+ columns: Object.fromEntries(attributes.map((a) => [a.LogicalName, detail(a)]).sort()),+ keys: [...t.Keys.values()].map((k) => `${k.SchemaName}(${k.KeyAttributes.join(',')})`),+ statusReasons: (t.Attributes.get('statuscode').OptionSet.Options || []).map((o) => `${o.Value} ${label(o.Label)} state ${o.State}`),+ };+ for (const key of Object.keys(tables[t.LogicalName])) if (tables[t.LogicalName][key] === undefined) delete tables[t.LogicalName][key];+ }+ const rows = (set, predicate = () => true) => org.find(set, predicate);+ const own = (set, column) => rows(set, (r) => String(r[column] || '').startsWith('contoso_'));+ // The kitchen sink's own app, navigation, page, option sets and web resources — another maker's are in the environment too.+ const app = rows('appmodules', (a) => a.uniquename === 'contoso_kitchensink')[0] || {};+ const appRow = org.rowsOf('appmodules').get(app.appmoduleid);+ const appComponents = rows('appmodulecomponents', (c) => c._appmoduleidunique_value === app.appmoduleidunique);+ const sitemap = rows('sitemaps', (m) => m.sitemapnameunique === 'contoso_kitchensink')[0] || {};+ const setting = (name) => {+ const def = rows('settingdefinitions', (d) => d.uniquename === name)[0];+ const row = def && rows('appsettings', (s) => s._settingdefinitionid_value === def.settingdefinitionid)[0];+ return row ? row.value : null;+ };+ const roleNamed = (name) => rows('roles', (r) => r.name === name)[0];+ const grantsOf = (role) => rows('roleprivilegescollection', (g) => role && g.roleid === role.roleid)+ .map((g) => `${(rows('privileges', (p) => p.privilegeid === g.privilegeid)[0] || {}).name} ${g.privilegedepthmask}`).sort();+ const page = [...org.pageServer.state.projects.values()].find((p) => p.name === 'Kitchen Page');+ return {+ tables,+ relationships: [...org.metadata.relationships.values()].map((r) => (r.RelationshipType === 'ManyToManyRelationship' ? `${r.SchemaName} N:N ${r.Entity1LogicalName}-${r.Entity2LogicalName}` : `${r.SchemaName} 1:N ${r.ReferencedEntity}->${r.ReferencingEntity}.${r.ReferencingAttribute}`)).sort(),+ optionSets: Object.fromEntries([...org.metadata.optionSets.values()].filter((s) => s.Name.startsWith('contoso_')).map((s) => [s.Name, s.Options.map((o) => `${o.Value} ${label(o.Label)}`)])),+ views: own('savedqueries', 'returnedtypecode').filter((v) => !/^(Active|Inactive|Quick Find Active) |( Advanced Find View| Lookup View| Associated View)$/.test(v.name)).map((v) => `${v.returnedtypecode}: ${v.name}`).sort(),+ // A chart as it draws: the series' type from its presentation XML, and what its data XML measures by what —+ // <Chart …><Series><Series ChartType="Pie" … /></Series>…</Chart>+ // <datadefinition><fetchcollection><fetch … aggregate="true"><entity name="contoso_project">+ // <attribute alias="agg_0" name="contoso_projectid" aggregate="count" /><attribute alias="grp_0" name="contoso_priority" groupby="true" />+ // as `Pie: count(contoso_projectid) by contoso_priority` (the attributes' order and aliases do not matter).+ charts: rows('savedqueryvisualizations').map((c) => {+ const attributes = [...String(c.datadescription || '').matchAll(/<attribute\b([^>]*?)\/?>/g)].map((m) => Object.fromEntries([...m[1].matchAll(/(\w+)="([^"]*)"/g)].map((x) => [x[1], x[2]])));+ const types = [...String(c.presentationdescription || '').matchAll(/ChartType="([^"]+)"/g)].map((m) => m[1]);+ const measures = attributes.filter((a) => a.aggregate).map((a) => `${a.aggregate}(${a.name})`);+ const groups = attributes.filter((a) => a.groupby === 'true').map((a) => a.name);+ return `${c.primaryentitytypecode}: ${c.name} (${types.join('/')}: ${measures.join(', ')} by ${groups.join(', ')})`;+ }),+ forms: own('systemforms', 'objecttypecode').map((f) => `${f.objecttypecode}: ${f.name} (type ${f.type}${f.isdefault ? ', default' : ''})`).sort(),+ dashboards: rows('systemforms', (f) => f.type === 0).map((f) => f.name),+ commands: rows('appactions').map((a) => a.contextvalue).sort(),+ webResources: rows('webresourceset', (w) => w.name.startsWith('contoso_')).map((w) => w.name).sort(),+ app: {+ uniquename: app.uniquename,+ published: !!(appRow && appRow.published),+ // The tables the app holds, by name, and the kinds of its other components (26 view, 59 chart, 60 form or dashboard, 62 sitemap).+ tables: appComponents.filter((c) => c.componenttype === 1).map((c) => ([...org.metadata.tables.values()].find((t) => t.MetadataId.toLowerCase() === String(c.objectid).toLowerCase()) || {}).LogicalName).sort(),+ components: [...new Set(appComponents.map((c) => c.componenttype))].sort((a, b) => a - b),+ },+ navigation: [...String(sitemap.sitemapxml || '').matchAll(/<SubArea\b[^>]*?\bId="([^"]+)"/g)].length,+ settings: { NewLookAlwaysOn: setting('NewLookAlwaysOn'), HeaderAndNavigationRefresh: setting('HeaderAndNavigationRefresh') },+ page: page ? { name: page.name, published: org.pageServer.publishedPages.has(page.id) } : null,+ personaRole: grantsOf(roleNamed('Kitchen Planner')),+ basicUserGrants: grantsOf(roleNamed('Basic User')),+ records: {+ projects: rows('contoso_projects').map((r) => `${r.contoso_name} status ${r.statuscode}`),+ tasks: rows('contoso_tasks').map((r) => `${r.contoso_title} -> ${(rows('contoso_projects', (p) => p.contoso_projectid === r._contoso_projectid_value)[0] || {}).contoso_name}`),+ },+ unpublished: org.unpublished(),+ };+}++// The publishes a measured step sent (`measure` gives its marks), each as the tables and kinds it names: `app`, `page` and `webresource`+// stand for the id of one.+function publishesOf(org, step) {+ return org.requests.slice(step.mark, step.end).filter((r) => r.path === '/PublishXml').map((r) => {+ const xml = String(r.body.ParameterXml);+ const named = (tag) => [...xml.matchAll(new RegExp(`<${tag}>([^<]+)</${tag}>`, 'g'))].map((match) => match[1]);+ return [...named('entity'), ...named('appmodule').map(() => 'app'), ...named('uxagentproject').map(() => 'page'), ...named('webresource').map(() => 'webresource')].join(' ');+ });+}++// What changed between two `org.contents()` (fake-lifecycle-org.js): an artifact of `before` that is gone, or that holds something+// else (naming the first fields that differ: `saved.fetchxml`, `Attributes.fabrikam_name`, `Options`); and — unless `added: false` —+// one that `after` holds and `before` did not. One line each, empty when nothing changed. A command that only reads must leave the+// whole environment as it was; one that builds or tears down must leave every artifact it did not make as it was (`added: false`, the+// identity inventory then proving what it made and deleted).+function diffContents(before, after, { added = true } = {}) {+ const out = [];+ const differing = (a, b, at, depth) => {+ if (JSON.stringify(a) === JSON.stringify(b)) return [];+ if (depth >= 2 || !a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) || Array.isArray(b)) return [at || '(the value)'];+ return [...new Set([...Object.keys(a), ...Object.keys(b)])].flatMap((key) => differing(a[key], b[key], at ? `${at}.${key}` : key, depth + 1));+ };+ for (const [key, entry] of Object.entries(before)) {+ if (!Object.prototype.hasOwnProperty.call(after, key)) { out.push(`gone: ${entry.label}`); continue; }+ const fields = differing(entry.content, after[key].content, '', 0);+ if (fields.length) out.push(`changed: ${entry.label} (${fields.slice(0, 6).join(', ')}${fields.length > 6 ? `, +${fields.length - 6} more` : ''})`);+ }+ if (added) for (const [key, entry] of Object.entries(after)) if (!Object.prototype.hasOwnProperty.call(before, key)) out.push(`added: ${entry.label}`);+ return out;+}++module.exports = { kitchenSinkSpec, createLifecycleHarness, seedForeignWork, deployedFeatures, publishesOf, diffContents, FOREIGN, appUniqueName, PAGE_SOURCE, ICON_SVG };diff --git a/plugins/model-apps/scripts/tests/helpers/odata-filter.js b/plugins/model-apps/scripts/tests/helpers/odata-filter.jsnew file mode 100644index 000000000..4f364bfd6--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/odata-filter.js@@ -0,0 +1,315 @@+'use strict';+// The OData `$filter` grammar the plugin and the bundled SDK send to Dataverse, parsed and evaluated against one row — for the+// stateful fakes, so a query is answered by what it SAYS rather than by a regex that happens to fit today's wording of it.+//+// Accepted (anything else throws, naming the text, so a new query shape fails loudly in the test that first sends it):+// comparisons name eq 'Contoso' · statecode ne 1 · isdefault eq true · _parentid_value eq 11111111-2222-3333-4444-555555555555+// · description eq null · versionnumber gt 5 (eq ne gt ge lt le)+// functions contains(name,'x') · startswith(name,'x') · endswith(name,'x') · tolower(name) eq 'x'+// the CRM query function Microsoft.Dynamics.CRM.In(PropertyName='name',PropertyValues=['a','b'])+// logic and · or · not · parentheses+// lambdas appmoduleroles_association/any(x:x/roleid eq <guid>) · …/all(…), over a collection-valued navigation the caller+// resolves (`options.navigate(row, name)` -> the related rows)+// literals 'text' (a quote is doubled: 'O''Neil') · integers and decimals · true · false · null · bare GUIDs+//+// Text compares IGNORING CASE, as Dataverse does: its SQL collation is case-insensitive, so `uniquename eq 'contososd'` finds+// `ContosoSD`. A GUID compares ignoring case and braces. A column the row does not hold is `null` here: whether the column EXISTS is+// the caller's question, which a fake answers from its own schema before it evaluates a single row (describeFilter).+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/filter-rows+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;++function tokenize(text) {+ const tokens = [];+ let i = 0;+ while (i < text.length) {+ const ch = text[i];+ if (/\s/.test(ch)) { i += 1; continue; }+ if ('(),[]=:'.includes(ch)) { tokens.push({ kind: ch }); i += 1; continue; }+ if (ch === "'") {+ let value = '';+ i += 1;+ for (;;) {+ if (i >= text.length) throw new Error(`odata-filter: unterminated text in ${JSON.stringify(text)}`);+ if (text[i] === "'") {+ if (text[i + 1] === "'") { value += "'"; i += 2; continue; }+ i += 1;+ break;+ }+ value += text[i];+ i += 1;+ }+ tokens.push({ kind: 'literal', value });+ continue;+ }+ const guid = GUID.exec(text.slice(i));+ if (guid && !/[\w-]/.test(text[i + guid[0].length] || '')) {+ tokens.push({ kind: 'literal', value: guid[0].toLowerCase(), guid: true });+ i += guid[0].length;+ continue;+ }+ const number = /^-?\d+(\.\d+)?/.exec(text.slice(i));+ if (number && !/[A-Za-z_]/.test(text[i + number[0].length] || '')) {+ tokens.push({ kind: 'literal', value: Number(number[0]) });+ i += number[0].length;+ continue;+ }+ const word = /^[A-Za-z_@$][\w.@/$]*/.exec(text.slice(i));+ if (word) {+ const w = word[0];+ if (w === 'true' || w === 'false') tokens.push({ kind: 'literal', value: w === 'true' });+ else if (w === 'null') tokens.push({ kind: 'literal', value: null });+ else tokens.push({ kind: 'word', value: w });+ i += w.length;+ continue;+ }+ throw new Error(`odata-filter: cannot read ${JSON.stringify(text.slice(i, i + 20))} in ${JSON.stringify(text)}`);+ }+ return tokens;+}++const COMPARE = new Set(['eq', 'ne', 'gt', 'ge', 'lt', 'le']);++function parseFilter(text) {+ const tokens = tokenize(String(text));+ let at = 0;+ const peek = () => tokens[at];+ const next = () => tokens[at++];+ const expect = (kind) => {+ const t = next();+ if (!t || t.kind !== kind) throw new Error(`odata-filter: expected '${kind}' in ${JSON.stringify(text)}`);+ return t;+ };+ const isWord = (t, value) => t && t.kind === 'word' && t.value.toLowerCase() === value;++ function operand() {+ const t = next();+ if (!t) throw new Error(`odata-filter: unexpected end of ${JSON.stringify(text)}`);+ if (t.kind === 'literal') return { kind: 'literal', value: t.value, guid: !!t.guid };+ if (t.kind === 'word') {+ // A lambda over a collection-valued navigation: `<navigation>/any(<variable>:<expression>)`.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/filter-rows#lambda-expressions+ const lambda = /^(.+)\/(any|all)$/i.exec(t.value);+ if (lambda && peek() && peek().kind === '(') {+ expect('(');+ const variable = expect('word').value;+ expect(':');+ const body = orExpr();+ expect(')');+ return { kind: 'lambda', nav: lambda[1], op: lambda[2].toLowerCase(), variable, body };+ }+ if (peek() && peek().kind === '(') return call(t.value);+ return { kind: 'field', name: t.value };+ }+ if (t.kind === '(') {+ const inner = orExpr();+ expect(')');+ return inner;+ }+ throw new Error(`odata-filter: unexpected '${t.kind}' in ${JSON.stringify(text)}`);+ }++ function call(name) {+ expect('(');+ if (name === 'Microsoft.Dynamics.CRM.In') {+ // Microsoft.Dynamics.CRM.In(PropertyName='name',PropertyValues=['a','b'])+ const args = {};+ for (;;) {+ const key = expect('word').value;+ expect('=');+ if (peek() && peek().kind === '[') {+ next();+ const values = [];+ while (peek() && peek().kind !== ']') {+ values.push(expect('literal').value);+ if (peek() && peek().kind === ',') next();+ }+ expect(']');+ args[key] = values;+ } else {+ args[key] = expect('literal').value;+ }+ if (peek() && peek().kind === ',') { next(); continue; }+ break;+ }+ expect(')');+ return { kind: 'in', field: args.PropertyName, values: args.PropertyValues || [] };+ }+ const args = [];+ while (peek() && peek().kind !== ')') {+ args.push(orExpr());+ if (peek() && peek().kind === ',') next();+ }+ expect(')');+ const fn = name.toLowerCase();+ if (!['contains', 'startswith', 'endswith', 'tolower', 'toupper'].includes(fn)) throw new Error(`odata-filter: function ${name} is not modelled (${JSON.stringify(text)})`);+ return { kind: 'call', fn, args };+ }++ function comparison() {+ if (isWord(peek(), 'not')) {+ next();+ return { kind: 'not', expr: comparison() };+ }+ const left = operand();+ const t = peek();+ if (t && t.kind === 'word' && COMPARE.has(t.value.toLowerCase())) {+ next();+ return { kind: 'compare', op: t.value.toLowerCase(), left, right: operand() };+ }+ return left;+ }++ function andExpr() {+ let left = comparison();+ while (isWord(peek(), 'and')) {+ next();+ left = { kind: 'and', left, right: comparison() };+ }+ return left;+ }++ function orExpr() {+ let left = andExpr();+ while (isWord(peek(), 'or')) {+ next();+ left = { kind: 'or', left, right: andExpr() };+ }+ return left;+ }++ const ast = orExpr();+ if (at !== tokens.length) throw new Error(`odata-filter: unread text after position ${at} in ${JSON.stringify(text)}`);+ return ast;+}++const norm = (value) => {+ if (typeof value === 'string') {+ const bare = value.replace(/^\{|\}$/g, '');+ return GUID.test(bare) && bare.length === 36 ? bare.toLowerCase() : value.toLowerCase();+ }+ return value;+};++// `ctx.vars` holds the rows a lambda's variable stands for (`x` in `…/any(x:x/roleid eq …)`); `ctx.navigate(row, name)` answers a+// collection-valued navigation of a row.+function valueOf(node, row, ctx) {+ if (node.kind === 'literal') return node.value;+ if (node.kind === 'field') {+ const slash = node.name.split('/');+ if (slash.length === 2) {+ // `x/roleid` inside a lambda reads the related row the variable stands for.+ if (ctx.vars && Object.prototype.hasOwnProperty.call(ctx.vars, slash[0])) {+ const related = ctx.vars[slash[0]];+ return related[slash[1]] === undefined ? null : related[slash[1]];+ }+ // A navigation path (`parentrootroleid/roleid`) is read as the lookup's `_x_value`.+ const lookup = row[`_${slash[0]}_value`];+ return lookup === undefined ? null : lookup;+ }+ return row[node.name] === undefined ? null : row[node.name];+ }+ if (node.kind === 'call') {+ const args = node.args.map((a) => valueOf(a, row, ctx));+ if (node.fn === 'tolower') return args[0] == null ? null : String(args[0]).toLowerCase();+ if (node.fn === 'toupper') return args[0] == null ? null : String(args[0]).toUpperCase();+ const [hay, needle] = args.map((a) => (a == null ? '' : String(a).toLowerCase()));+ if (node.fn === 'contains') return hay.includes(needle);+ if (node.fn === 'startswith') return hay.startsWith(needle);+ if (node.fn === 'endswith') return hay.endsWith(needle);+ }+ return evaluate(node, row, ctx);+}++function compare(op, a, b) {+ const x = norm(a);+ const y = norm(b);+ if (op === 'eq') return x === y || (x == null && y == null);+ if (op === 'ne') return !(x === y || (x == null && y == null));+ if (x == null || y == null) return false;+ if (op === 'gt') return x > y;+ if (op === 'ge') return x >= y;+ if (op === 'lt') return x < y;+ if (op === 'le') return x <= y;+ throw new Error(`odata-filter: operator ${op}`);+}++function evaluate(node, row, ctx = {}) {+ switch (node.kind) {+ case 'and': return evaluate(node.left, row, ctx) && evaluate(node.right, row, ctx);+ case 'or': return evaluate(node.left, row, ctx) || evaluate(node.right, row, ctx);+ case 'not': return !evaluate(node.expr, row, ctx);+ case 'compare': return compare(node.op, valueOf(node.left, row, ctx), valueOf(node.right, row, ctx));+ case 'in': {+ const actual = norm(row[node.field]);+ return node.values.some((v) => norm(v) === actual);+ }+ case 'lambda': {+ if (typeof ctx.navigate !== 'function') throw new Error(`odata-filter: the navigation ${node.nav} cannot be followed here`);+ const related = ctx.navigate(row, node.nav);+ const holds = (r) => evaluate(node.body, row, { ...ctx, vars: { ...(ctx.vars || {}), [node.variable]: r } });+ return node.op === 'any' ? related.some(holds) : related.every(holds);+ }+ case 'call': return !!valueOf(node, row, ctx);+ case 'literal': return !!node.value;+ case 'field': return !!valueOf(node, row, ctx);+ default: throw new Error(`odata-filter: cannot evaluate ${node.kind}`);+ }+}++// The fields a filter reads, so a fake can refuse one it does not hold rather than answer "no rows" for a column it never modelled.+function fieldsOf(node, into = new Set()) {+ if (!node || typeof node !== 'object') return into;+ if (node.kind === 'field') into.add(node.name);+ if (node.kind === 'in') into.add(node.field);+ for (const key of ['left', 'right', 'expr', 'body']) if (node[key]) fieldsOf(node[key], into);+ for (const arg of node.args || []) fieldsOf(arg, into);+ return into;+}++// What a parsed filter reads, by where it reads it — what a fake validates against its schema BEFORE it looks at a single row, so a+// filter over an empty collection is checked exactly as one over a full one:+// fields the columns of the row itself (`name`, `_parentid_value`)+// paths a single-valued navigation followed to the key of the row it points at (`parentrootroleid/roleid`), as+// `{ navigation, field }`+// lambdas a collection-valued navigation and the columns its variable reads of the related rows+// (`appmoduleroles_association/any(x:x/roleid eq …)` -> `{ navigation: 'appmoduleroles_association', fields: ['roleid'] }`)+function describeFilter(ast) {+ const out = { fields: new Set(), paths: [], lambdas: [] };+ const visit = (node, scope) => {+ if (!node || typeof node !== 'object') return;+ if (node.kind === 'field') {+ const parts = node.name.split('/');+ if (parts.length === 1) out.fields.add(node.name);+ else if (parts.length === 2 && scope.has(parts[0])) scope.get(parts[0]).fields.add(parts[1]);+ else if (parts.length === 2) out.paths.push({ navigation: parts[0], field: parts[1] });+ else throw new Error(`odata-filter: the path ${node.name} is not modelled`);+ }+ if (node.kind === 'in') out.fields.add(node.field);+ if (node.kind === 'lambda') {+ const lambda = { navigation: node.nav, op: node.op, fields: new Set() };+ out.lambdas.push(lambda);+ visit(node.body, new Map([...scope, [node.variable, lambda]]));+ return;+ }+ for (const key of ['left', 'right', 'expr', 'body']) if (node[key]) visit(node[key], scope);+ for (const arg of node.args || []) visit(arg, scope);+ };+ visit(ast, new Map());+ return { fields: [...out.fields], paths: out.paths, lambdas: out.lambdas.map((l) => ({ ...l, fields: [...l.fields] })) };+}++// A filter's text is parsed once and kept: the fakes parse it before they enumerate (so an empty collection still refuses a filter it+// cannot answer), then evaluate the same tree against each row.+const compiled = new Map();+function compileFilter(text) {+ const key = String(text);+ if (!compiled.has(key)) compiled.set(key, parseFilter(key));+ return compiled.get(key);+}++function matchesFilter(text, row, ctx) {+ if (!text) return true;+ return evaluate(compileFilter(text), row, ctx || {});+}++module.exports = { parseFilter, compileFilter, describeFilter, matchesFilter, evaluateFilter: evaluate, filterFields: fieldsOf };diff --git a/plugins/model-apps/scripts/tests/helpers/queued-stdio-preload.js b/plugins/model-apps/scripts/tests/helpers/queued-stdio-preload.jsnew file mode 100644index 000000000..3172adb27--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/queued-stdio-preload.js@@ -0,0 +1,14 @@+'use strict';+// Loaded with `node --require` ahead of a script: gives the script the stdout and stderr a pipe gets on Linux and macOS — a `net.Socket` over the pipe, whose writes are QUEUED when the pipe cannot take them at+// once — on every platform. Node makes a pipe on descriptor 1 or 2 synchronous on Windows (lib/net.js: "Make stdout and stderr blocking on Windows"), so a script run there with its own stdout can never show what a+// reader on Linux or macOS gets when `process.exit` follows a large write (https://nodejs.org/api/process.html#a-note-on-process-io). Here `process.stdout` and `process.stderr` are sockets over descriptors 3 and 4+// instead, which Node leaves asynchronous everywhere; the test spawns the script with `stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe']` and reads what it printed from `output[3]` and `output[4]`.+//+// Everything the script writes through `process.stdout` and `process.stderr` goes there: `emitResult`, `console.*` (the global console reads the streams when it is first used), and the output guard of+// lib/output-redaction.js, which wraps whichever streams the process has when its first token is noted. Measured on Windows with Node 22: a 3.5 MB write followed by `process.exit` delivered 1.1 to 2.2 MB of it.+const net = require('node:net');++for (const [name, fd] of [['stdout', 3], ['stderr', 4]]) {+ const socket = new net.Socket({ fd, readable: false, writable: true });+ Object.defineProperty(process, name, { configurable: true, enumerable: true, get: () => socket });+}diff --git a/plugins/model-apps/scripts/tests/helpers/synthetic-token.js b/plugins/model-apps/scripts/tests/helpers/synthetic-token.jsnew file mode 100644index 000000000..fea754bdc--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/synthetic-token.js@@ -0,0 +1,41 @@+'use strict';+// A synthetic access token and the ways a service's diagnostic can spell it, for the tests that prove a token never reaches what a script writes.+//+// A token the way Azure issues one — three base64url parts joined by dots — and synthetic: each part is at least 24 characters, so each is taken out on its own.+const PARTS = ['syntheticHeaderPartNotARealCredential', 'syntheticPayloadPartNotARealCredential', 'syntheticSignaturePartNotARealCredential'];+const TOKEN = PARTS.join('.');+// What must not be readable anywhere: the token and each of its parts.+const SECRETS = [TOKEN, ...PARTS];+const NL = '\r\n';+const CODE = '0x80040220';+// A gateway that wraps a long header value folds it (RFC 9112 section 5.2, the obsolete line folding: a line break and a space) — here every eight characters.+const FOLDED = TOKEN.match(/.{1,8}/g).join(`${NL} `);+// The first character of each part spelled as a JSON escape (`\u0073` is `s`): written into a JSON body the SDK decodes it, written as text it stays what it is.+const ESCAPED_INITIALS = PARTS.map((part) => `\\u${part.charCodeAt(0).toString(16).padStart(4, '0')}${part.slice(1)}`).join('.');++// A token whose signature starts with `n` — the second character of the JSON escape `\n` — for a diagnostic that has a literal backslash right before the signature: a reader that takes `\n` for a line break+// reads the backslash and the `n` away together and finds the rest of the signature, which is not a part of the token. Header and payload are the base64url of small synthetic JSON documents.+const LEADING_N_PARTS = [+ Buffer.from('{"alg":"RS256","typ":"JWT","test":"synthetic"}').toString('base64url'),+ Buffer.from('{"aud":"synthetic","test":"not-a-real-credential"}').toString('base64url'),+ 'nSyntheticSignaturePartNotARealCredential',+];+const LEADING_N_TOKEN = LEADING_N_PARTS.join('.');+const LEADING_N_SECRETS = [LEADING_N_TOKEN, ...LEADING_N_PARTS];++// What the refused part of a change set can say. The SDK quotes the body of the part as it parses it — a JSON body is decoded, so a character written `\uXXXX` is the character itself in the message, and a body that is+// itself escaped JSON keeps its escapes — and takes any text between the part's own delimiters as that body, whatever lines it holds. `typed` is the platform's own code, which the SDK keeps in the body it parsed.+const REFUSALS = [+ { name: 'plain JSON', body: JSON.stringify({ error: { code: CODE, message: `Principal user rejected bearer ${TOKEN} for this write` } }), typed: CODE },+ { name: 'multi-byte JSON', body: JSON.stringify({ error: { code: CODE, message: `Accès refusé 日本語 🧪 ${TOKEN} — fin` } }), typed: CODE },+ { name: 'JSON that names one part of the token', body: JSON.stringify({ error: { code: CODE, message: `The payload ${PARTS[1]} is not valid` } }), typed: CODE },+ { name: 'JSON with the first character of each part spelled as a \\u escape', body: `{"error":{"code":"${CODE}","message":"Rejected bearer ${ESCAPED_INITIALS} for this write"}}`, typed: CODE },+ { name: 'JSON that spells the escape itself (the escape is escaped, so the decoded message still holds it)', body: JSON.stringify({ error: { code: CODE, message: `The supplied literal spelling was ${ESCAPED_INITIALS}` } }), typed: CODE },+ { name: 'JSON with the token folded onto several lines', body: JSON.stringify({ error: { code: CODE, message: `Rejected bearer ${FOLDED}` } }), typed: CODE },+ { name: 'JSON with the token as a key of the body', body: JSON.stringify({ error: { code: CODE, message: 'no detail' }, [TOKEN]: 'the header the gateway echoed' }), typed: CODE },+ { name: 'plain text with a line that looks like an HTTP/2 status line', body: `Gateway diagnostic${NL}HTTP/2 200 OK${NL}Rejected bearer ${TOKEN}` },+ { name: 'plain text that looks like a delimiter: two dashes and the token', body: `--${TOKEN}` },+ { name: 'plain text with the token folded onto several lines', body: `Rejected bearer ${FOLDED}` },+];++module.exports = { PARTS, TOKEN, SECRETS, NL, CODE, FOLDED, ESCAPED_INITIALS, REFUSALS, LEADING_N_PARTS, LEADING_N_TOKEN, LEADING_N_SECRETS };diff --git a/plugins/model-apps/scripts/tests/helpers/token-boundary-child.js b/plugins/model-apps/scripts/tests/helpers/token-boundary-child.jsnew file mode 100644index 000000000..7c27a924a--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/token-boundary-child.js@@ -0,0 +1,229 @@+'use strict';+// A REAL PROCESS that does what a script does with a failure the SDK raised, a warning it returned and an answer the service sent — prints them on stdout and stderr, writes them into the build's journal, its baseline and+// the files a download writes — so a test can read what actually reached the process's file descriptors and its folder, and not what a function was handed. Run by tests/output-token-real-bundle.test.js and+// tests/output-token-boundary.test.js:+// node token-boundary-child.js <scenario> [<json parameters>]+// with TOKEN_BOUNDARY_DIR (an existing folder: everything the scenario writes goes there) and TOKEN_BOUNDARY_FACTS (a file for what the scenario KNOWS — booleans and counts, never the token's text — written with the+// plain `fs`, outside anything the plugin guards). It requires no test runner: a test runner prints its own report on stdout when the process ends.+//+// Only the plugin's own code is used to make, send and print: the production SDK factory (lib/maker-sdk.js) over the real vendored bundle and the production az-token client, `emitResult`, the journal, the baseline writer+// and the safe file writer. Nothing here names the code that keeps a token out of them, so the same scenarios run against a tree that has none.+const fs = require('node:fs');+const path = require('node:path');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../../lib/maker-sdk.js');+const { createAzHttpClient } = require('../../lib/sdk-http-client.js');+const { emitResult, getAuthToken } = require('../../lib/dataverse-auth.js');+const { requireSuccessfulPush } = require('../../lib/entity-provision.js');+const { openJournal } = require('../../lib/build-journal.js');+const { writeFileAtomic } = require('../../lib/apply-snapshot-store.js');+const { writeFileSafe } = require('../../lib/safe-fs.js');+const ai = require('../../lib/artifact-intent.js');+const { refusedEdit } = require('./bpf-batch-service.js');+const { createHarness, seedForm, NOTES_CLASS_ID } = require('./form-store-harness.js');+const { INSTANCE } = require('./fake-genpage-server.js');+const { TOKEN, SECRETS, FOLDED, REFUSALS, CODE, LEADING_N_PARTS, LEADING_N_TOKEN, LEADING_N_SECRETS } = require('./synthetic-token.js');+const { leaksIn } = require('./token-leaks.js');++const DIR = process.env.TOKEN_BOUNDARY_DIR;+const facts = {};+const note = (name, value) => { facts[name] = value; };+const saveFacts = () => fs.writeFileSync(process.env.TOKEN_BOUNDARY_FACTS, JSON.stringify(facts));+// A new folder for an SDK's workspace, inside the folder the test reads back.+let folders = 0;+const makeDir = () => { folders += 1; const dir = path.join(DIR, `sdk-${folders}`); fs.mkdirSync(dir, { recursive: true }); return dir; };++// What a script does with a failure, in the ways the plugin's scripts do it: a progress line and a warning on stderr, the failure's message and the body the SDK kept on stdout, the build's journal and status file, the+// baseline, a file of the result, and at last the documented result printer — which exits, so what the scenario knows is saved first.+function printLikeAScript(error) {+ saveFacts();+ console.error(error);+ process.stderr.write(`WARNING: ${error.message}\n`);+ process.stdout.write(`${JSON.stringify({ progress: error.message, cause: error.cause })}\n`);+ const journal = openJournal(path.join(DIR, 'journal'));+ journal.record({ phase: 'bpf', status: 'failed', label: 'flow edit', detail: error.message });+ journal.close({ status: 'halt', error: error.message });+ writeFileAtomic(path.join(DIR, 'baseline.json'), JSON.stringify({ lastError: error.message, cause: error.cause }));+ writeFileSafe(path.join(DIR, 'result.json'), `${JSON.stringify({ error: error.message, cause: error.cause }, null, 2)}\n`);+ emitResult(false, error);+}++const scenarios = {+ // A change set the service refuses as a whole — HTTP 200 with the one part that failed — which the SDK quotes into the error it raises. `index` is the spelling in REFUSALS.+ async 'change-set'({ index }) {+ const { error } = await refusedEdit(REFUSALS[index].body, createMakerSdk, makeDir);+ note('refused', Boolean(error));+ note('errorHoldsToken', leaksIn(error, SECRETS).length > 0);+ printLikeAScript(error);+ },++ // The same change set, refused by a part that has a LITERAL backslash right before a part of the token that starts with `n` (the token is LEADING_N_TOKEN, which the client sends): in the decoded message the backslash and the+ // `n` read as the escape `\n`, which is not what they are. `spelling` is how the refusal says it: `signature` quotes the signature alone; `folded` quotes the whole token, folded onto several lines, with the backslash+ // before the signature; `escaped-fold` quotes it with a JSON-escaped fold in every part and the backslash before the signature.+ async 'leading-n'({ spelling }) {+ const [header, payload, signature] = LEADING_N_PARTS;+ const whole = `${header}.${payload}.\\${signature}`;+ const message = {+ signature: `Rejected signature \\${signature}`,+ folded: `Rejected bearer ${whole.match(/.{1,8}/g).join('\r\n ')}`,+ 'escaped-fold': `Rejected bearer ${whole.match(/.{1,8}/g).join('\\r\\n ')}`,+ }[spelling];+ if (message === undefined) throw new Error(`unknown spelling ${spelling}`);+ const { error } = await refusedEdit(JSON.stringify({ error: { code: CODE, message } }), createMakerSdk, makeDir, { token: LEADING_N_TOKEN });+ note('refused', Boolean(error));+ note('errorHoldsToken', leaksIn(error, LEADING_N_SECRETS).length > 0);+ printLikeAScript(error);+ },++ // The same, and nothing catches it: what Node itself prints when an error ends a script. `how` is how it escapes. `source` is where the error comes from: the SDK's refusal (`change-set`, spelled `index` of REFUSALS), or+ // an error a script builds from text it was handed after the process had obtained its token (`plain`). With `exitHandler` the script has a handler for the end of the process, as the ones that clean up their folders do.+ async fatal({ source = 'change-set', index = 0, how, exitHandler = false }) {+ if (exitHandler) process.on('exit', (code) => fs.writeFileSync(path.join(DIR, 'exit-handler.txt'), `ran with ${code}`));+ let error;+ if (source === 'plain') {+ note('obtained', getAuthToken(INSTANCE, { exec: () => `${TOKEN}\n` }) === TOKEN);+ error = new Error(`push form failed: Rejected bearer ${FOLDED}`);+ } else {+ error = (await refusedEdit(REFUSALS[index].body, createMakerSdk, makeDir)).error;+ }+ note('errorHoldsToken', leaksIn(error, SECRETS).length > 0);+ saveFacts();+ if (how === 'throw') setTimeout(() => { throw error; }, 0);+ else if (how === 'reject') Promise.reject(error);+ else if (how === 'async-main') (async function main() { await Promise.resolve(); throw error; })();+ else throw new Error(`unknown way ${how}`);+ },++ // The SDK writes a form, reads it back to confirm and is refused the read (HTTP 403, the token folded onto several lines): it returns the refusal as a WARNING and the push is reported as saved — the text the build prints and+ // journals, which no error object carries.+ async form() {+ const diagnostic = JSON.stringify({ error: { code: '0x80040220', message: `Rejected bearer ${FOLDED}` } });+ const state = { armed: false, ready: false, refused: 0 };+ const h = createHarness({+ createSdk: (options) => {+ const upstream = options.httpClient;+ const client = createAzHttpClient(options.instanceUrl, {+ getToken: () => TOKEN, sleep: async () => {}, random: () => 0,+ request: async ({ method, url, headers, body }) => {+ if (state.armed && state.ready && method === 'GET' && /\/systemforms\(/.test(url)) {+ state.refused += 1;+ return { statusCode: 403, headers: {}, body: diagnostic };+ }+ const verb = method.toLowerCase();+ const res = method === 'GET' || method === 'DELETE' ? await upstream[verb](url, { headers }) : await upstream[verb](url, typeof body === 'string' ? JSON.parse(body) : body, { headers });+ if (state.armed && method === 'PATCH' && /\/systemforms\(/.test(url)) state.ready = true;+ return { statusCode: res.status, headers: res.headers || {}, body: typeof res.body === 'string' ? res.body : JSON.stringify(res.body ?? null) };+ },+ });+ return createMakerSdk({ ...options, httpClient: client });+ },+ });+ const spec = {+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] }],+ forms: [{ entity: 'new_ticket', name: 'Main', tabs: [{ name: 'tab_main', label: 'Main', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }] }] }],+ };+ await seedForm(h, ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID }).tabs);+ const { sdk } = await h.freshSdk(makeDir());+ await sdk.fetchArtifact('form', h.formId);+ await sdk.updateElement('form', h.formId, '/name', 'Renamed');+ state.armed = true;+ const result = await sdk.pushArtifact('form', h.formId);+ h.cleanup();+ note('saved', result.saved);+ note('refusedReads', state.refused);+ // The warnings as the SDK returned them, and what the build does with them: each is a WARNING line on stderr, a step of the journal, and part of the result.+ const warnings = [];+ requireSuccessfulPush(result, 'form Main', (message) => { warnings.push(message); process.stderr.write(`WARNING: ${message}\n`); });+ note('warnings', warnings.length);+ note('warningHoldsToken', warnings.some((warning) => leaksIn(warning, SECRETS).length > 0));+ const journal = openJournal(path.join(DIR, 'journal'));+ for (const warning of warnings) journal.record({ phase: 'ui', status: 'warning', label: 'form Main', detail: warning });+ journal.close({ status: 'complete' });+ writeFileAtomic(path.join(DIR, 'baseline.json'), JSON.stringify({ warnings }));+ saveFacts();+ emitResult(true, { saved: result.saved, publish: result.publish, warnings });+ },++ // An error that is not the SDK's own — the transport failed with an error of an odd shape: a frozen one, one whose message is an accessor, one whose stack is a getter that writes — carried as the SDK's `cause`. `shape` names it.+ async 'error-shape'({ shape }) {+ let reads = 0;+ let original;+ if (shape === 'frozen') {+ original = Object.freeze(new Error(`Rejected bearer ${TOKEN}`));+ } else if (shape === 'accessor') {+ original = new Error('transport rejected');+ Object.defineProperty(original, 'message', { get() { reads += 1; return `Rejected bearer ${TOKEN}`; }, enumerable: true, configurable: true });+ } else if (shape === 'stack-getter') {+ original = new Error('transport rejected');+ Object.defineProperty(original, 'stack', { get() { reads += 1; process.stderr.write(`Stack accessor echoed ${TOKEN}\n`); return `Error: ${TOKEN}`; }, configurable: true });+ } else {+ original = new Error(`Rejected bearer ${TOKEN}`);+ }+ const client = createAzHttpClient(INSTANCE, { getToken: () => TOKEN, request: async () => { throw original; } });+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeDir()), instanceUrl: INSTANCE, httpClient: client });+ await sdk.initWorkspace();+ const error = await sdk.findTables().then(() => null, (e) => e);+ note('refused', Boolean(error));+ note('getterReadsDuringCall', reads);+ printLikeAScript(error);+ },++ // A token the process obtained the way a script does — from the Azure CLI — and then a success answer that repeats it: the data a script prints and a download writes. `answer` is the shape of the data.+ async answer() {+ const token = getAuthToken(INSTANCE, { exec: () => `${TOKEN}\n` });+ note('obtained', token === TOKEN);+ const data = { value: [{ name: 'Account', note: `Rejected bearer ${FOLDED}`, [TOKEN]: 'as a key', plain: `bearer ${TOKEN}` }] };+ writeFileSafe(path.join(DIR, 'answer.json'), `${JSON.stringify(data, null, 2)}\n`);+ saveFacts();+ emitResult(true, data);+ },++ // A token obtained from the Azure CLI and a result of several megabytes with the token in one row: printed in one write, complete, and still one JSON document when the process exits right after it.+ async big({ rows }) {+ note('obtained', getAuthToken(INSTANCE, { exec: () => `${TOKEN}\n` }) === TOKEN);+ const data = Array.from({ length: rows }, (_, i) => ({ id: i, name: `row ${i}`, note: i === Math.floor(rows / 2) ? `Rejected bearer ${FOLDED}` : 'The platform answered with a diagnostic that says nothing about credentials.' }));+ note('bytes', JSON.stringify(data).length);+ saveFacts();+ emitResult(true, data);+ },++ // The token obtained from the Azure CLI, printed in every way a script prints. `how` is the way.+ async print({ how }) {+ const token = getAuthToken(INSTANCE, { exec: () => `${TOKEN}\n` });+ note('obtained', token === TOKEN);+ saveFacts();+ const message = `Rejected bearer ${TOKEN}`;+ const ways = {+ 'stdout-write': () => process.stdout.write(`${message}\n`),+ 'stderr-write': () => process.stderr.write(`${message}\n`),+ 'console-log': () => console.log(message),+ 'console-info': () => console.info(message),+ 'console-debug': () => console.debug(message),+ 'console-warn': () => console.warn(message),+ 'console-error': () => console.error(message),+ 'console-error-object': () => console.error(new Error(message)),+ 'console-log-folded-object': () => console.log({ error: { message: `Rejected bearer ${FOLDED}` } }),+ 'json-line': () => process.stdout.write(`${JSON.stringify({ ok: false, error: message, nested: { list: [`bearer ${FOLDED}`] } })}\n`),+ 'write-callback': () => new Promise((resolve) => process.stderr.write(`${message}\n`, 'utf8', resolve)),+ 'emit-ok': () => emitResult(true, { message, folded: FOLDED }),+ 'emit-ok-ascii': () => emitResult(true, { message, accent: 'é' }, { ascii: true }),+ 'emit-error': () => emitResult(false, new Error(message)),+ 'emit-text': () => emitResult(false, message),+ 'emit-structured': () => emitResult(false, { ok: false, error: message, errors: [message, { detail: FOLDED }] }),+ };+ if (!ways[how]) throw new Error(`unknown way ${how}`);+ await ways[how]();+ // Ends as a script ends when it has nothing more to say.+ process.exit(0);+ },+};++const [, , name, parameters] = process.argv;+if (!scenarios[name]) {+ process.stderr.write(`unknown scenario ${name}\n`);+ process.exit(2);+}+scenarios[name](parameters ? JSON.parse(parameters) : {}).then(() => saveFacts(), (error) => {+ // A failure of the scenario itself (not the scripted one): said without the token's text, which the scenario never prints on purpose.+ fs.writeFileSync(process.env.TOKEN_BOUNDARY_FACTS, JSON.stringify({ ...facts, harnessFailure: String(error && error.stack ? error.stack : error).replace(TOKEN, '<token>') }));+ process.exit(3);+});diff --git a/plugins/model-apps/scripts/tests/helpers/token-leaks.js b/plugins/model-apps/scripts/tests/helpers/token-leaks.jsnew file mode 100644index 000000000..b754e3aaf--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/token-leaks.js@@ -0,0 +1,47 @@+'use strict';+// For tests: every text a value holds, and the spellings in which an access token can still be read out of one. A text a script writes is clean only when none of those spellings holds the token —+// not when a plain `includes(TOKEN)` finds nothing, which a token folded onto several lines, spelled with an escape, printed the way `util.inspect` prints a long string (in colours too) or with a stray backslash in it survives.+const { stripVTControlCharacters } = require('node:util');++// Every string a value holds, wherever it is: an Error's message and stack, its own properties (the non-enumerable and the symbol-keyed ones too), its `cause` chain, and the keys and values of whatever those hold.+// Accessors are not read: a test must not run code the subject would not. An Error's `stack` is, because a recent engine makes it one.+function stringsOf(value, seen = new Set(), out = []) {+ if (typeof value === 'string') {+ out.push(value);+ return out;+ }+ if (value === null || (typeof value !== 'object' && typeof value !== 'function') || seen.has(value)) return out;+ seen.add(value);+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return out;+ if (value instanceof Error) out.push(String(value.message), String(value.stack));+ for (const key of Reflect.ownKeys(value)) {+ if (typeof key === 'string') out.push(key);+ const descriptor = Object.getOwnPropertyDescriptor(value, key);+ if (descriptor && 'value' in descriptor) stringsOf(descriptor.value, seen, out);+ }+ return out;+}++// The JSON escapes a text can hold: `\u0073` for `s`, `\/` for `/`, and `\r`, `\n`, `\t`, `\f` for the white space they spell. Each is read whatever the number of backslashes before it: a text that was JSON inside JSON, or+// was written as JSON once more, holds `\\u0073` and `\\r\\n`, which a reader who decodes it once more reads as the same characters.+const unescaped = (text) => text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16))).replace(/\\+\//g, '/').replace(/\\+[rntf]/g, '');++// The ways a reader gets the token back out of `text`: as it is, with the line folds and any other white space taken out, with the escapes decoded as well, and with the quotes and plus signs of a long string printed+// over several lines (`'abc\r\n' +\n ' def'`) taken out too — each of them also with the terminal's colour codes taken out first (what a person reading a console sees), and each also with every backslash taken out+// (a token a diagnostic spelled with a literal backslash between its characters).+const viewsOf = (text) => {+ const views = [];+ for (const base of [text, stripVTControlCharacters(text)]) {+ const spelled = unescaped(base).replace(/\s+/g, '');+ for (const view of [base, base.replace(/\s+/g, ''), spelled, spelled.replace(/['"`+]/g, '')]) views.push(view, view.replace(/\\+/g, ''));+ }+ return views;+};++// The secrets (the token, and each part of it) that can be read out of any text `value` holds, in any of those spellings.+function leaksIn(value, secrets) {+ const views = stringsOf(value).flatMap(viewsOf);+ return secrets.filter((secret) => views.some((view) => view.includes(secret)));+}++module.exports = { stringsOf, viewsOf, unescaped, leaksIn };diff --git a/plugins/model-apps/scripts/tests/helpers/translation-export.js b/plugins/model-apps/scripts/tests/helpers/translation-export.jsnew file mode 100644index 000000000..e78f106a6--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/translation-export.js@@ -0,0 +1,165 @@+'use strict';+// A SYNTHESIZED translation export, for the tests of what `--verify` reads captions from. Every name, id and caption in it is invented: an+// export a real environment answers carries that environment's organization id, so none is ever stored here — what is stored is the SHAPE+// the platform was measured to answer, made again from made-up rows.+//+// POST …/api/data/v9.2/solutions/Microsoft.Dynamics.CRM.ExportTranslation { "SolutionName": "<uniquename>" }+// → 200 { "@odata.context": "…#Microsoft.Dynamics.CRM.ExportTranslationResponse", "ExportTranslationFile": "<base64 of a zip>" }+//+// The zip holds `CrmTranslations.xml` (an Excel 2003 XML spreadsheet) and `[Content_Types].xml`, each deflated, with flags 0x0002, version needed 20,+// version made by 45, and — what a reader that takes the data's place from the CENTRAL directory gets wrong — an extra field of 28 bytes on each LOCAL+// header and none on the central one. The workbook has three worksheets, `Information`, `Display Strings` and `Localized Labels`; a caption is a row+// of the last, `Entity name | Object ID | Object Column Name | <one column per language, headed by its LCID>`, keyed by the `id` the tab or section has+// in the form's FormXML, and an empty cell is `<Data ss:Type="String"></Data>`.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/exporttranslation+// https://learn.microsoft.com/en-us/power-apps/maker/data-platform/export-customized-entity-field-text-translation+const zlib = require('node:zlib');++const SPREADSHEET_NAMESPACE = 'urn:schemas-microsoft-com:office:spreadsheet';++const escapeXml = (text) => String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');++const cellOf = (text, { type = 'String', style = 's24' } = {}) => `<Cell ss:StyleID="${style}"><Data ss:Type="${type}">${escapeXml(text)}</Data></Cell>`;+const rowOf = (cells) => `<Row ss:AutoFitHeight="0">${cells.join('')}</Row>`;+// What the platform writes around a sheet's rows, as measured: column widths (`ss:Span` for a run of columns) before them and, after the table, the sheet's options in Excel's own namespace —+// elements with no attribute, some of them empty. None of it is read; the reader holds the sheet to this shape, so a sheet made here is one it reads.+const COLUMNS = '<Column ss:AutoFitWidth="0" ss:Width="105.75" /><Column ss:Width="224.25" /><Column ss:AutoFitWidth="0" ss:Width="105.75" /><Column ss:AutoFitWidth="0" ss:Width="114.75" ss:Span="2" />';+const WORKSHEET_OPTIONS = '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"><Unsynced /><ProtectObjects>False</ProtectObjects><ProtectScenarios>False</ProtectScenarios>'+ + '<AllowFormatCells /><AllowSizeCols /><AllowSizeRows /><AllowInsertCols /><AllowInsertRows /><AllowDeleteCols /><AllowDeleteRows /><AllowSort /><AllowFilter /><AllowUsePivotTables /></WorksheetOptions>';+const sheetOf = (name, rows) => `<Worksheet ss:Name="${name}" ss:Id="${name}" ss:Protected="1"><Table>${COLUMNS}${rows.join('')}</Table>${WORKSHEET_OPTIONS}</Worksheet>`;++/**+ * The text of a CrmTranslations.xml: the platform's three worksheets, with `captions` as the rows of `Localized Labels`.+ * @param {object} [options]+ * @param {number[]} [options.languages] the language columns of `Localized Labels`, in order+ * @param {{ entity: string, id: string, column?: string, texts?: Object<number, string> }[]} [options.captions] one row each; a language with no text is an empty cell+ * @param {string} [options.sheetsAfter] raw XML put after the last worksheet+ */+function workbookXml({ languages = [1033, 3082], captions = [], sheetsAfter = '' } = {}) {+ const header = rowOf([+ cellOf('Entity name', { style: 's21' }), cellOf('Object ID', { style: 's21' }), cellOf('Object Column Name', { style: 's21' }),+ ...languages.map((lcid) => cellOf(String(lcid), { type: 'Number', style: 's21' })),+ ]);+ const labels = captions.map(({ entity, id, column = 'displayname', texts = {} }) => rowOf([+ cellOf(entity, { style: 's22' }), cellOf(id, { style: 's22' }), cellOf(column, { style: 's22' }),+ ...languages.map((lcid) => cellOf(texts[lcid] === undefined ? '' : texts[lcid])),+ ]));+ const information = [+ rowOf([cellOf('Organization ID:', { style: 's21' }), cellOf('00000000-0000-0000-0000-000000000000', { style: 's22' })]),+ rowOf([cellOf('Exported on:', { style: 's21' }), cellOf('2030-01-01T00:00:00', { type: 'DateTime', style: 's23' })]),+ rowOf([cellOf('Base language ID:', { style: 's21' }), cellOf('1033', { type: 'Number', style: 's22' })]),+ ];+ const displayStrings = [rowOf([cellOf('Entity name', { style: 's21' }), cellOf('Display String Key', { style: 's21' }), ...languages.map((lcid) => cellOf(String(lcid), { type: 'Number', style: 's21' }))])];+ return `<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="${SPREADSHEET_NAMESPACE}" xmlns:o="urn:schemas-microsoft-com:office:office" `+ + `xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="${SPREADSHEET_NAMESPACE}" xmlns:html="http://www.w3.org/TR/REC-html40">`+ + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"></DocumentProperties>'+ + '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"><ActiveSheet>0</ActiveSheet><ProtectStructure>False</ProtectStructure></ExcelWorkbook>'+ + '<Styles><Style ss:ID="Default" ss:Name="Normal"><Alignment ss:Vertical="Bottom" /></Style></Styles>'+ + `${sheetOf('Information', information)}${sheetOf('Display Strings', displayStrings)}${sheetOf('Localized Labels', [header, ...labels])}${sheetsAfter}</Workbook>`;+}++// CRC-32 of the ZIP format (reflected, polynomial 0xEDB88320). `zlib.crc32` only exists from Node 22.2, and the suite runs on Node 20 as well.+const CRC_TABLE = (() => {+ const table = new Uint32Array(256);+ for (let n = 0; n < 256; n += 1) {+ let c = n;+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;+ table[n] = c >>> 0;+ }+ return table;+})();+function crc32(bytes) {+ let crc = 0xFFFFFFFF;+ for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xFF] ^ (crc >>> 8);+ return (crc ^ 0xFFFFFFFF) >>> 0;+}++const DATA_DESCRIPTOR_SIGNATURE = 0x08074b50;++/**+ * A ZIP archive of `entries` ({ name, data }), laid out the way the platform's export is: a local header (30 bytes, the name, `localExtra` bytes of+ * extra field) and the data of each entry, then the central directory (46 bytes and the name each, no extra field), then the end record.+ * @param {{ name: string, data: string | Buffer }[]} entries+ * @param {object} [options]+ * @param {0 | 8} [options.method] 8 deflates the data (as the platform does); 0 stores it+ * @param {number} [options.localExtra] the size of the extra field of each local header+ * @param {number} [options.flags] the general-purpose flags both headers carry+ * @param {'signed' | 'unsigned' | 'missing'} [options.descriptor] the way a streaming writer lays an entry out: flag bit 3 set, the checksum and the sizes zero in the local header, and — for+ * 'signed' (what every writer in use produces) and 'unsigned' (the shorter form the format also allows) — a data descriptor after the data holding them; 'missing' is the damaged archive that says+ * a descriptor follows and has none+ * @param {number} [options.versionMadeBy]+ * @param {string} [options.comment] the archive comment+ */+function zipOf(entries, { method = 8, localExtra = 28, flags = 0x0002, versionMadeBy = 45, comment = '', descriptor } = {}) {+ const locals = [];+ const centrals = [];+ let offset = 0;+ const entryFlags = descriptor === undefined ? flags : flags | 0x0008;+ for (const { name, data } of entries) {+ const raw = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8');+ const stored = method === 8 ? zlib.deflateRawSync(raw, { level: 9 }) : raw;+ const nameBytes = Buffer.from(name, 'utf8');+ const local = Buffer.alloc(30);+ local.writeUInt32LE(0x04034b50, 0);+ local.writeUInt16LE(20, 4);+ local.writeUInt16LE(entryFlags, 6);+ local.writeUInt16LE(method, 8);+ if (descriptor === undefined) {+ local.writeUInt32LE(crc32(raw), 14);+ local.writeUInt32LE(stored.length, 18);+ local.writeUInt32LE(raw.length, 22);+ }+ local.writeUInt16LE(nameBytes.length, 26);+ local.writeUInt16LE(localExtra, 28);+ const after = Buffer.alloc(descriptor === 'signed' ? 16 : descriptor === 'unsigned' ? 12 : 0);+ const values = descriptor === 'signed' ? 4 : 0;+ if (descriptor === 'signed') after.writeUInt32LE(DATA_DESCRIPTOR_SIGNATURE, 0);+ if (after.length > 0) {+ after.writeUInt32LE(crc32(raw), values);+ after.writeUInt32LE(stored.length, values + 4);+ after.writeUInt32LE(raw.length, values + 8);+ }+ const body = Buffer.concat([local, nameBytes, Buffer.alloc(localExtra), stored, after]);+ const central = Buffer.alloc(46);+ central.writeUInt32LE(0x02014b50, 0);+ central.writeUInt16LE(versionMadeBy, 4);+ central.writeUInt16LE(20, 6);+ central.writeUInt16LE(entryFlags, 8);+ central.writeUInt16LE(method, 10);+ central.writeUInt32LE(crc32(raw), 16);+ central.writeUInt32LE(stored.length, 20);+ central.writeUInt32LE(raw.length, 24);+ central.writeUInt16LE(nameBytes.length, 28);+ central.writeUInt32LE(offset, 42);+ centrals.push(Buffer.concat([central, nameBytes]));+ locals.push(body);+ offset += body.length;+ }+ const directory = Buffer.concat(centrals);+ const commentBytes = Buffer.from(comment, 'utf8');+ const end = Buffer.alloc(22);+ end.writeUInt32LE(0x06054b50, 0);+ end.writeUInt16LE(entries.length, 8);+ end.writeUInt16LE(entries.length, 10);+ end.writeUInt32LE(directory.length, 12);+ end.writeUInt32LE(offset, 16);+ end.writeUInt16LE(commentBytes.length, 20);+ return Buffer.concat([...locals, directory, end, commentBytes]);+}++const CONTENT_TYPES = '<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/octet-stream" /></Types>';++/** The zip the platform answers with: the workbook, then the content-types part. */+const exportZip = (workbook, options) => zipOf([{ name: 'CrmTranslations.xml', data: workbook }, { name: '[Content_Types].xml', data: CONTENT_TYPES }], options);++/** The HTTP answer (`{ status, headers, body }`, as the plugin's client gives it) of a successful ExportTranslation holding `archive`. */+const exportAnswer = (archive) => ({+ status: 200,+ headers: {},+ body: { '@odata.context': 'https://contoso.crm.dynamics.com/api/data/v9.2/$metadata#Microsoft.Dynamics.CRM.ExportTranslationResponse', ExportTranslationFile: archive.toString('base64') },+});++// The path the plugin POSTs to, and the one request this test double understands.+const EXPORT_PATH = /\/solutions\/Microsoft\.Dynamics\.CRM\.ExportTranslation(?:\?|$)/;++module.exports = { workbookXml, zipOf, exportZip, exportAnswer, crc32, escapeXml, EXPORT_PATH, CONTENT_TYPES, SPREADSHEET_NAMESPACE };diff --git a/plugins/model-apps/scripts/tests/helpers/type-head-pages.js b/plugins/model-apps/scripts/tests/helpers/type-head-pages.jsindex 33c3ac317..3b8c2a9a3 100644--- a/plugins/model-apps/scripts/tests/helpers/type-head-pages.js+++ b/plugins/model-apps/scripts/tests/helpers/type-head-pages.js@@ -289,6 +289,10 @@ const KEYWORD_BODIES = ['void <span>(MARK); // note</span>;', 'x;\nvoid <span>(Mconst CLASS_VALUES = ['class {}', 'class extends Base {}', 'class Named {}', 'class Named<T> extends Base<T> implements I {}', 'class C implements D {}', 'class extends mixin(A) {}', 'class extends (B) {}', 'class implements A, B() {}', 'class { m() {} }', 'class { a = 1; static b() { return 1; } }','class extends a.b.C<T> {}', 'class extends Base<{ a: 1 }> {}', 'class extends A, B {}', 'class \u00e9 extends B {}', 'class Named<T extends { a: 1 }> {}', 'class<T> {}', 'class implements {}', 'class interface {}', 'class extends Base implements I, J<K> {}', '@dec class {}',+ // A class expression in the head — the base, an element of `implements`, one after `new`, with decorators and members of its own — has its braces inside the head of the class: the braces of the class come after them, and the head of the class that holds them may hold the same.+ 'class extends class {} {}', 'class extends class A {} {}', 'class A extends class B {} {}', 'class extends class extends B {} {}', 'class extends class extends class {} {} {}', 'class extends class {} implements I {}', 'class implements class {} {}', 'class extends A implements class {} {}',+ 'class extends A implements class {}, class {} {}', 'class extends class {}.x {}', 'class extends class {}() {}', 'class extends class {}! {}', 'class extends new class {} {}', 'class extends new @d class {} {}', 'class extends class { m() { return class {}; } } {}', 'class extends class Named<T> extends Base<T> implements I {} {}',+ 'class extends class {}\n.x {}', 'class\nextends\nclass\n{}\n{}', 'class extends class /* c */ {} /* d */ {}', 'class extends class { a = { b: 1 }; } {}', 'class extends class implements I {} {}', 'class extends class<T> {} {}', 'class extends class {}, class {} {}',// The white space and the comments that stand inside a class and after it: every character that the scanner skips between two tokens.'class\u00a0extends\u2028Base\u3000{}', 'class /* c */ extends /* d */ Base /* e */ {}', 'class\nextends\nBase\n{}', 'class\ufeffNamed\u200b{}\u0085',];@@ -296,8 +300,16 @@ const CLASS_VALUES_WRAPPED = [...CLASS_VALUES, ...CLASS_VALUES.map((value) => `(const KEYWORD_METHOD_FRAMES = [['a method of a class', (n, b) => `class C { ${n}() { ${b} } }`], ['a method after a method', (n, b) => `class C { a() {} ${n}() { ${b} } }`], ['a method after a field', (n, b) => `class C { a = 1; ${n}() { ${b} } }`],['a method after a field and a line break', (n, b) => `class C { a = 1\n ${n}() { ${b} } }`], ['a method after a name and a line break', (n, b) => `class C { a\n ${n}() { ${b} } }`], ['a method after a name and a comment', (n, b) => `class C { a /* c */\n ${n}() { ${b} } }`],- // A field that a keyword names and no initializer or `;` ends, then a method on the next line: the word before the method's name is the name of a field, no keyword (`new` is read as it was: the operator).- ['a method after a field that the keyword names', (n, b) => (n === 'new' ? null : `class C { ${n}\n m() { ${b} } }`)],+ // A field that a keyword names and no initializer or `;` ends, then a method on the next line: the word before the method's name is the name of a field, no keyword. `new` is no operator there either: it is the operator only in the head of a class, after+ // `extends`, `implements` or a comma of the list (CLASS_HERITAGES has those), and what stands before a field is a member of the class: the start of its body, a separator, a modifier, a decorator.+ ['a method after a field that the keyword names', (n, b) => `class C { ${n}\n m() { ${b} } }`], ['a method after a static field that the keyword names', (n, b) => `class C { static ${n}\n m() { ${b} } }`], ['a method after a readonly field that the keyword names', (n, b) => `class C { readonly ${n}\n m() { ${b} } }`],+ ['a method after a declared field that the keyword names', (n, b) => `class C { declare ${n}\n m() { ${b} } }`], ['a method after a public field that the keyword names', (n, b) => `class C { public ${n}\n m() { ${b} } }`], ['a method after a decorated field that the keyword names', (n, b) => `class C { @d ${n}\n m() { ${b} } }`],+ ['a method after a field, a comment and a line break', (n, b) => `class C { ${n} // c\n m() { ${b} } }`], ['a method after a field and a comment that holds the line break', (n, b) => `class C { ${n} /* c\n */ m() { ${b} } }`], ['a method after a field and a CR LF', (n, b) => `class C { ${n}\r\n m() { ${b} } }`],+ ['a method after a field after a method', (n, b) => `class C { a() {}\n ${n}\n m() { ${b} } }`], ['a method after a field after a field', (n, b) => `class C { a = 1;\n ${n}\n m() { ${b} } }`], ['an async method after a field that the keyword names', (n, b) => `class C { ${n}\n async m() { ${b} } }`],+ ['a method after a field that the keyword names in a class that extends a name', (n, b) => `class C extends B { ${n}\n m() { ${b} } }`], ['a method after a field that the keyword names in a class that extends a call', (n, b) => `class C extends mixin(A) { ${n}\n m() { ${b} } }`],+ ['a method after a field that the keyword names in a class that extends new', (n, b) => `class C extends new X() { ${n}\n m() { ${b} } }`], ['a method after a field that the keyword names in a class that implements a call after a comma', (n, b) => `class C implements A, B() { ${n}\n m() { ${b} } }`],+ ['a method after a field that the keyword names in a class whose base is a class expression', (n, b) => `class C extends class {} { ${n}\n m() { ${b} } }`], ['a method after a field that the keyword names in a class expression', (n, b) => `const K = class { ${n}\n m() { ${b} } };`],+ ['a method after a field that the keyword names in the class of a property', (n, b) => `const o = { a: class { ${n}\n m() { ${b} } }, p: 1 };`], ['a method after a field that the keyword names in a class in a function', (n, b) => `function f() { return class { ${n}\n m() { ${b} } }; }`],['a static method', (n, b) => `class C { static ${n}() { ${b} } }`], ['an async method', (n, b) => `class C { async ${n}() { ${b} } }`], ['a getter', (n, b) => `class C { get ${n}() { ${b} } }`], ['a setter', (n, b) => `class C { set ${n}(v) { ${b} } }`],['a generator', (n, b) => `class C { *${n}() { ${b} } }`], ['an async generator', (n, b) => `class C { async *${n}() { ${b} } }`], ['a decorated method', (n, b) => `class C { @d ${n}() { ${b} } }`], ['a public method', (n, b) => `class C { public ${n}() { ${b} } }`],['a method of a class that extends a name', (n, b) => `class C extends B { ${n}() { ${b} } }`], ['a method of a class that extends a call', (n, b) => `class C extends mixin(A) { ${n}() { ${b} } }`], ['a method of a class that implements a name', (n, b) => `class C implements I { ${n}() { ${b} } }`],@@ -439,6 +451,9 @@ const CLASS_HERITAGES = ['abstract class C implements A, B()', 'export class C implements A, B()', '@dec class C implements B()', 'declare class C implements A, B()', 'class C implements "x", B()', String.raw`class C implements A, \u0042()`, String.raw`class C implements A, a.\u0062()`,// What stays as it was: a parenthesis, a `new` and an unread callee after a comma.'class C implements A, (B)', 'class C extends A, (B)', 'class C extends A, new B()', 'class C implements A, B<T>()', 'class C extends A, a?.b(c)', 'class C extends A, B.C().d()', 'class C<T> extends A<T>, B() implements I',+ // The operator `new` of an element, with a line break between it and what it takes or before it, after the keyword or the comma of the list: no field of a class, whatever the class that holds the head has before it (the wrap of a field's initializer).+ 'class C extends new\n X()', 'class C extends\n new X()', 'class C extends\n new\n X()', 'class C implements new\n X()', 'class C implements\n new X()', 'class C implements\n new\n X()', 'class C extends A,\n new X()', 'class C extends A,\n new\n X()', 'class C extends A, new\n X()',+ 'class C implements A,\n new\n X()', 'class C extends A implements\n new\n X()', 'class C extends new\n a.b.X()', 'class C implements A,\n new\n a.X()', 'class C implements A, B,\n new\n X()',// A letter beyond ASCII in a name of the list, which the comma is read back through, and the word that begins the list in other heads.'class C implements A, caf\u00e9()', 'class C extends caf\u00e9, B()', 'class C extends A, B(), caf\u00e9()', 'class C<T> implements (B)', 'abstract class C implements (B)', 'class C implements caf\u00e9, (B)', 'const K = class extends A, B()', 'class C extends implements, B()', 'class C extends A, implements, B()',// A class expression among the elements: its own head and braces stand between the keyword and the call, and are one element. The list that the braces after the call end is the outer class's, whatever words the inner class has.@@ -451,7 +466,9 @@ const CLASS_HERITAGES = [// Each of the elements that ends a list in a `)`, after `implements`, after a comma and after both keywords: the braces after it hold members (the sweep reads a part of them in every wrap)....LAST_ELEMENT_HERITAGES,];-const CLASS_CONTAINER_WRAPS = [(c) => c, (c) => `export ${c}`, (c) => `function f() { ${c} }`, (c) => `if (a) { b; } else { ${c} }`, (c) => `a(b)\n${c}`, (c) => `async () => { ${c} }`];+const CLASS_CONTAINER_WRAPS = [(c) => c, (c) => `export ${c}`, (c) => `function f() { ${c} }`, (c) => `if (a) { b; } else { ${c} }`, (c) => `a(b)\n${c}`, (c) => `async () => { ${c} }`,+ // The braces of a class around the head: what stands before a `new` there is the start of a member, and a field may be named so.+ (c) => `class H { a = ${c} }`];// The same for an interface, which names its bases after `extends` (and, to the parser, after `implements`, which only the checker refuses).const INTERFACE_HERITAGES = ['interface I extends J', 'interface I extends A, B()', 'interface I extends B()', 'interface I extends A<T>, B()', 'interface I extends A, ns.B()', 'interface I extends A, B(), C()', 'interface I extends B(),\n C()', 'interface I extends A, /* c */ B()', 'interface I extends A, B(x, y)',@@ -524,10 +541,15 @@ const NEST_FRAMES = [['stmt', 'stmt', 'const o = { a: class extends B {}, m() { __X__ } };'], ['stmt', 'stmt', 'const o = { a: class {}, implements() { __X__ } };'], ['stmt', 'stmt', 'const o = { a: class Named<T> extends Base<T> implements I {}, m() { __X__ } };'],['stmt', 'stmt', 'const o = { a: (class extends B {}), m() { __X__ } };'], ['stmt', 'stmt', 'class Q {}\nfunction implements() { __X__ }'], ['stmt', 'stmt', 'interface Q {}\nfunction implements() { __X__ }'], ['stmt', 'stmt', 'class Q extends mixin(A) {}\nfunction f() { __X__ }'],['stmt', 'stmt', 'class H { a = class {}\n implements() { __X__ } }'], ['stmt', 'stmt', 'class H { static a = class extends B {}\n extends() { __X__ } }'],+ // A class whose own base is a class expression has the braces of the base inside its head, so that the braces of the class come after a `}`: as the value before a method, and as a declaration before a function. A field named `new` that a line break ends,+ // before the method on the next line (`new` is the operator only in a heritage).+ ['stmt', 'stmt', 'const o = { a: class extends class {} {}, m() { __X__ } };'], ['stmt', 'stmt', 'class Q extends class {} {}\nfunction implements() { __X__ }'], ['stmt', 'stmt', 'const o = { a: class A extends class B implements I {} implements J, K() {}, implements() { __X__ } };'],+ ['stmt', 'stmt', 'class H { a = class extends class {} {}\n m() { __X__ } }'], ['stmt', 'stmt', 'class C { new\n m() { __X__ } }'], ['stmt', 'stmt', 'class C { static new\n m() { __X__ } }'], ['stmt', 'stmt', 'class C extends class {} { new\n m() { __X__ } }'], ['stmt', 'stmt', 'class C extends mixin(A) { readonly new\n m() { __X__ } }'],+ ['stmt', 'stmt', 'const o = { a: class { new\n m() { __X__ } }, b: 1 };'], ['stmt', 'stmt', 'class C { a() {}\n @d new\n implements() { __X__ } }'],// Statements inside, an expression.['stmt', 'expr', '(function () { __X__ })'], ['stmt', 'expr', '(() => { __X__ })'], ['stmt', 'expr', '(async () => { __X__ })'], ['stmt', 'expr', '({ m() { __X__ } })'], ['stmt', 'expr', '({ get x() { __X__ } })'], ['stmt', 'expr', '(class { m() { __X__ } })'],['stmt', 'expr', '({ a: 1, m() { __X__ } })'], ['stmt', 'expr', '({ a: caf\u00e9, m() { __X__ } })'], ['stmt', 'expr', '({ implements() { __X__ } })'], ['stmt', 'expr', '({ a: class extends B {}, m() { __X__ } })'],- ['stmt', 'expr', '(class extends mixin(A) { m() { __X__ } })'], ['stmt', 'expr', '(function* () { __X__ })'], ['stmt', 'expr', '(class { static { __X__ } })'],+ ['stmt', 'expr', '(class extends mixin(A) { m() { __X__ } })'], ['stmt', 'expr', '(function* () { __X__ })'], ['stmt', 'expr', '(class { static { __X__ } })'], ['stmt', 'expr', '({ a: class extends class {} {}, m() { __X__ } })'], ['stmt', 'expr', '(class { new\n m() { __X__ } })'],// An expression inside, a statement.['expr', 'stmt', 'f(__X__);'], ['expr', 'stmt', '[__X__];'], ['expr', 'stmt', '(__X__);'], ['expr', 'stmt', 'const e = __X__;'], ['expr', 'stmt', 'a ? __X__ : b;'], ['expr', 'stmt', 'const o = { k: __X__ };'], ['expr', 'stmt', 'const h = () => __X__;'],['expr', 'stmt', 'const t = `${__X__}`;'], ['expr', 'stmt', 'const e = <div a={__X__} />;'], ['expr', 'stmt', 'const e = <div>{__X__}</div>;'], ['expr', 'stmt', 'function g() { return __X__; }'], ['expr', 'stmt', 'x = __X__;'], ['expr', 'stmt', 'for (__X__;;) {}'],@@ -553,6 +575,8 @@ const NEST_FRAMES = [];// What stands before the payload member, by the kind of the braces: a member that a separator or a line break ends.const NEST_MEMBER_BEFORE = { body: ['', '', '', 'static ', 'async ', 'get a() { return 1; }\n', 'a = await\n', 'a = 1;\n', 'x;\n', '@dec ', 'a: 1,\n', 'a() {},\n', '*', 'readonly ', '@dec<T> *', '@dec<T> in\n', '@dec<T> instanceof\n', '@1. *', 'a = 1\n', 'a\n',+ // A field named `new` that a line break ends, before a method named like an operator.+ 'new\n', 'static new\n',// A decimal point that ends a number, after white space that is not ASCII.'@\u00a01. *', '@\u2028 1.\n', 'a =\u00a01.\n', 'a =\u3000 1.\n'], signature: ['', '', 'a: void\n', 'a: string;\n', 'a(): void\n', 'readonly ', 'a?: T,\n'] };const NEST_PRECEDING_WORDS = ['', '', 'void', 'typeof', 'delete', 'await', 'a in', 'a instanceof', 'x ? 1 :', 'a &&', 'a ||'];diff --git a/plugins/model-apps/scripts/tests/helpers/valid-pages.js b/plugins/model-apps/scripts/tests/helpers/valid-pages.jsindex 768b96e08..f5a55853c 100644--- a/plugins/model-apps/scripts/tests/helpers/valid-pages.js+++ b/plugins/model-apps/scripts/tests/helpers/valid-pages.js@@ -416,6 +416,10 @@ const EVERYDAY = ['async function k15() { const e = await\nvoid <span>(value); // note</span>; return e; }', 'class K16 { async m() { const e = await\ndelete <span>(value); // note</span>; } }', 'const k17 = { async m() { return await\ntypeof <span>(value); // note</span>; } };','class K18 extends mixin(B) { async m() { const e = await\nvoid <>(value); // note</>; } }', 'if (a) { const e = await\nvoid <span>(value); // note</span>; }', 'class K19 { @decorate method() { return\nvoid <span>(value); // note</span>; } }','function k20() { try { g(); } catch (e) { return\ndelete <span>(value); // note</span>; } finally { h(); } }', 'class K21 { constructor(a) { this.x = a in\nvoid <span>(value); // note</span>; } }',+ // A class whose base is a class expression, as the value before a method and as a declaration before a function, and a field named `new` that a line break ends before a method: the braces after the method's `)` are its body, whatever the head before it holds.+ 'const n1 = { a: class extends class {} {}, m() { void <span>(value); // note</span>; } };', 'class N2 extends class {} {}\nfunction n3() { void <span>(value); // note</span>; }', 'class N4 { new\n m() { void <span>(value); // note</span>; } }',+ 'class N5 { static new\n m() { return <span>(value) // note</span>; } }', 'const n6 = { a: class extends class {} implements I {}, b: 1, m() { const e = delete <>(value); // note</>; } };', 'class N7 extends class {} { new\n m() { void <span>(value); // note</span>; } }',+ 'const n8 = { a: class A extends class B extends class {} {} {}, implements() { void <span>(value); // note</span>; } };', 'class N9 { x = 1\n new\n m() { typeof <span>(value); // note</span>; } }', 'const n10 = class { new\n render() { void <span>(value); // note</span>; } };',];// The pages. Each is { group, name, code }; the test drops those TypeScript does not parse.diff --git a/plugins/model-apps/scripts/tests/helpers/write-order-preload.js b/plugins/model-apps/scripts/tests/helpers/write-order-preload.jsnew file mode 100644index 000000000..6d6c3efcf--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/write-order-preload.js@@ -0,0 +1,35 @@+'use strict';+// Loaded with `node --require` — after helpers/queued-stdio-preload.js when a test uses both — by the tests that hold a printer to the ORDER of its+// last writes. It records each time this process makes its stdout or stderr blocking (`setBlocking(true)` on the stream's handle: what+// lib/output-redaction.js makeWritesBlocking calls) and each write to either, and when the process exits it writes the record to the file that+// WRITE_ORDER_FILE names, for example `{"code":1,"events":["blocking stdout","blocking stderr","write stderr"]}`.+//+// Why an order: it does not depend on the platform, the runtime or how far a reader reads ahead, so a printer that writes before it makes its stream+// blocking fails such a test on every run. A test of the text that arrives can pass by luck: a reader that pauses its stream still lets the runtime+// read ahead below it, and on Windows a printer that did not make its writes blocking delivered a megabyte whole to a held reader under Node 20 (and+// 65,536 characters of it under Node 22). Nothing else about the streams changes: their own `write` and `setBlocking` are called with what they+// were given, and what they answer is answered.+const fs = require('node:fs');++const file = process.env.WRITE_ORDER_FILE;+if (file) {+ const events = [];+ for (const name of ['stdout', 'stderr']) {+ const stream = process[name];+ const handle = stream && stream._handle;+ if (handle && typeof handle.setBlocking === 'function') {+ const setBlocking = handle.setBlocking;+ handle.setBlocking = function setBlockingRecorded(flag, ...rest) {+ if (flag === true) events.push(`blocking ${name}`);+ return setBlocking.call(this, flag, ...rest);+ };+ }+ const write = stream.write;+ stream.write = function writeRecorded(...args) {+ events.push(`write ${name}`);+ return write.apply(this, args);+ };+ }+ // Added before anything the script adds, so it runs first: a write made by a later 'exit' listener is not the printer's, and is not recorded.+ process.on('exit', (code) => fs.writeFileSync(file, JSON.stringify({ code, events })));+}diff --git a/plugins/model-apps/scripts/tests/import-job-proof.test.js b/plugins/model-apps/scripts/tests/import-job-proof.test.jsnew file mode 100644index 000000000..053aa319c--- /dev/null+++ b/plugins/model-apps/scripts/tests/import-job-proof.test.js@@ -0,0 +1,300 @@+'use strict';+// lib/import-job-proof.js — what the job of an import the platform REFUSED to start proves about whether that import applied anything.+//+// The platform answers an import that meets another import or a publish with HTTP 429 and 0x80071151, "Cannot start another [Import] because there is a previous [Import] running …". Measured on a+// Public-cloud environment, the refused send's `importjobs(<id>)` is then one of two things: it never exists (the refusal came at the first lock check), or it exists and is final by the time the answer+// arrives (two imports started together: the refusal came at the second check) — a finished row whose log says the import failed with that error, with the solution manifest and every component+// left unprocessed. Only the first row and the 404 prove that a second send cannot meet a first that applied something; the rest (a job still running, an import that failed AFTER it began, a log+// that is not what it should be) prove nothing and the import is not sent again. These tests hold the rule to the 347 states the measurement captured (helpers/import-job-logs.js makes a twin of+// each kind of state — made up, not copied) and to every clause of it, one at a time, so that a clause that is dropped or loosened fails here.+const test = require('node:test');+const assert = require('node:assert');+const {+ refusedBeforeAnyComponent, proveRefusedImport, MAX_JOB_LOG_CHARS, CONCURRENCY_ERRORCODE, PROOF_ABSENT, PROOF_LOG,+} = require('../lib/import-job-proof.js');+const { importLog, LOGS, jobRow, rootOf, CAPTURED_STATES, LOCK_ERRORCODE, REFUSAL_STATUS } = require('./helpers/import-job-logs.js');++const refused = (options) => LOGS.refused(options);+// `rootOf` gives the root a `processed="true"` of its own unless told another; a root with no mark at all is made by taking it out.+const withoutMark = (root) => { const copy = { ...root }; delete copy.processed; return copy; };+const verdictOf = (data, row) => refusedBeforeAnyComponent(jobRow(data, row));+const assertProven = (data, what, row) => assert.deepStrictEqual(verdictOf(data, row), { proven: true }, what);+const assertNot = (data, why, what, row) => {+ const verdict = verdictOf(data, row);+ assert.strictEqual(verdict.proven, false, `${what}: not proven`);+ assert.strictEqual(verdict.why, why, `${what}: ${verdict.reason}`);+ assert.strictEqual(typeof verdict.reason, 'string');+ return verdict;+};++test('the error code the rule looks for is 0x80071151 as the signed 32-bit integer the platform writes in a log, and a log is read up to 8 MiB', () => {+ assert.strictEqual(CONCURRENCY_ERRORCODE, '-2147020463');+ assert.strictEqual(CONCURRENCY_ERRORCODE, String(0x80071151 | 0));+ assert.strictEqual(LOCK_ERRORCODE, CONCURRENCY_ERRORCODE, 'the twins the tests are made of use the same code');+ assert.strictEqual(MAX_JOB_LOG_CHARS, 8 * 1024 * 1024);+});++// --- the 347 states ------------------------------------------------------------------------------------------------------------------------++test('the 347 job-row states the measurement captured: the rule accepts exactly the 8 final rows of refused imports and none of the other 339', () => {+ const tally = {};+ let states = 0;+ let proven = 0;+ for (const state of CAPTURED_STATES) {+ const row = jobRow(state.data(), { completed: state.completed });+ const verdict = refusedBeforeAnyComponent(row);+ assert.strictEqual(verdict.proven, state.group === 'refused-final', `${state.name}: ${JSON.stringify(verdict)}`);+ // The same verdict through the answer of the read (HTTP 200), which is what the script has in hand.+ assert.deepStrictEqual(proveRefusedImport({ status: 200, body: row }), verdict.proven ? { proven: true, proof: PROOF_LOG } : verdict, state.name);+ states += state.count;+ if (verdict.proven) proven += state.count;+ tally[state.group] = tally[state.group] || { states: 0, proven: 0 };+ tally[state.group].states += state.count;+ if (verdict.proven) tally[state.group].proven += state.count;+ }+ assert.deepStrictEqual({ states, proven, notProven: states - proven }, { states: 347, proven: 8, notProven: 339 });+ assert.deepStrictEqual(tally, {+ 'running-or-early-success': { states: 308, proven: 0 },+ 'success-final': { states: 17, proven: 0 },+ 'refused-early': { states: 9, proven: 0 },+ 'failed-after-start': { states: 5, proven: 0 },+ 'refused-final': { states: 8, proven: 8 },+ });+});++test('every state that is not the final row of a refused import says WHY in the first clause of the rule it fails — a running import is "not finished", an import that applied the package "does not say it failed", one that failed after it began "another error"', () => {+ const why = (data, row) => verdictOf(data, row).why;+ assert.strictEqual(why(LOGS.running(), { completed: false }), 'unfinished');+ assert.strictEqual(why(LOGS.running(), { completed: true }), 'not-a-failure', 'a skeleton whose row is complete says nothing of failing');+ assert.strictEqual(why(LOGS.succeeded()), 'not-a-failure');+ assert.strictEqual(why(LOGS.unfinishedRoot()), 'not-a-failure', 'a row complete before its root has its verdict (completedon set, no succeeded, no errorcode)');+ assert.strictEqual(why(LOGS.unfinishedRoot({ manifest: 'true', components: 'true', finished: true })), 'not-a-failure');+ assert.strictEqual(why(LOGS.failedAfterStart()), 'other-error', 'an import that failed after it began failed with another error');+});++// --- every clause of the rule, one at a time --------------------------------------------------------------------------------------------++test('the rule accepts the final row of a refused import — and what it does not read does not matter: progress, solutionid, import context, the value of completedon, the root\'s own mark, the package\'s own checks, the size of the package', () => {+ assertProven(refused(), 'the row as measured');+ assertProven(refused({ tables: 1 }), 'a package of one table');+ assertProven(refused({ tables: 60 }), 'a package of sixty tables');+ assertProven(refused(), 'a first import of a solution that does not exist (a solutionid that names nothing)', { progress: 40, solutionid: '11111111-2222-3333-4444-555555555555', importcontext: 'ImportInstall' });+ assertProven(refused(), 'a running import passes through the same progress', { progress: 17.142857142857142, operationcontext: 'None' });+ assertProven(refused(), 'the value of completedon is not read: only that there is one', { completedon: '2001-02-03T04:05:06Z' });+ assertProven(importLog({ root: withoutMark(rootOf({ errorcode: LOCK_ERRORCODE, succeeded: 'failure', status: REFUSAL_STATUS })), manifest: 'false', components: 'false', handlers: 'true' }), 'the root\'s own `processed` is not read: it may be missing');+ assertProven(importLog({ root: rootOf({ errorcode: LOCK_ERRORCODE, succeeded: 'failure', status: REFUSAL_STATUS, processed: 'false' }), manifest: 'false', components: 'false', handlers: 'true' }), 'the root\'s own `processed` is not read: it may be false');+ assertProven(refused({ handlers: 'false' }), 'the package\'s own checks may be processed or not');+ assertProven(refused({ handlers: null }), 'and need not be there');+ assertProven(importLog({ root: rootOf({ errorcode: LOCK_ERRORCODE, succeeded: 'failure', status: undefined }), manifest: 'false', components: 'false', handlers: 'true' }), 'the root\'s words (status) are not read');+ assertProven(`\uFEFF<?xml version="1.0" encoding="utf-8"?>\n${refused()}\n`, 'a byte order mark and an XML declaration are no part of the document');+});++test('completedon: a job that is not finished proves nothing — null, missing, empty, white space, or not text — whatever its log says', () => {+ for (const [what, completedon] of [['null', null], ['empty', ''], ['white space', ' \t'], ['a number', 1], ['an object', {}], ['a boolean', true]]) {+ assertNot(refused(), 'unfinished', what, { completedon });+ }+ const noKey = jobRow(refused());+ delete noKey.completedon;+ assert.strictEqual(refusedBeforeAnyComponent(noKey).why, 'unfinished', 'a row with no completedon at all');+ assert.match(refusedBeforeAnyComponent(noKey).reason, /not finished \(completedon is empty\)/);+});++test('data: a row with no log, or one that is not text, proves nothing', () => {+ for (const [what, data] of [['null', null], ['missing', undefined], ['empty', ''], ['a number', 42], ['an object', { importexportxml: {} }], ['a list', [refused()]]]) {+ assertNot(data, 'no-log', what);+ }+ for (const [what, row] of [['null', null], ['undefined', undefined], ['a string', refused()], ['a number', 7], ['a list', [jobRow(refused())]], ['a function', () => jobRow(refused())]]) {+ const verdict = refusedBeforeAnyComponent(row);+ assert.deepStrictEqual([verdict.proven, verdict.why], [false, 'no-log'], `a row that is ${what}`);+ }+});++test('the root: it must be importexportxml, say succeeded="failure" exactly, and carry the error code -2147020463 exactly — each of them, by itself, is required', () => {+ const data = refused();+ assertNot(data.replace(/importexportxml/g, 'importexport'), 'not-an-import-log', 'another root element');+ assertNot(data.replace(/importexportxml/g, 'x:importexportxml'), 'not-an-import-log', 'a root with a namespace prefix is another name');+ assertNot(data.replace(/importexportxml/g, 'ImportExportXml'), 'not-an-import-log', 'XML is case-sensitive');+ for (const [what, replacement] of [+ ['success', 'succeeded="success"'], ['an empty value', 'succeeded=""'], ['another case', 'succeeded="Failure"'], ['white space around it', 'succeeded=" failure "'], ['a word that contains it', 'succeeded="failure!"'],+ ['the attribute missing', ''], ['the attribute under another name', 'Succeeded="failure"'],+ ]) {+ assertNot(data.replace('succeeded="failure"', replacement), 'not-a-failure', `succeeded: ${what}`);+ }+ const failedOtherwise = (replacement) => data.replace(`errorcode="${CONCURRENCY_ERRORCODE}"`, replacement);+ const hex = assertNot(failedOtherwise('errorcode="-2147188685"'), 'other-error', 'an import that failed after it began');+ assert.match(hex.reason, /failed with error 0x80048033, not with 0x80071151/, 'the code is shown the way the platform spells codes');+ assert.match(assertNot(failedOtherwise('errorcode="0"'), 'other-error', 'zero').reason, /failed with error 0x0, not with 0x80071151/);+ for (const [what, replacement] of [+ ['the lock code spelled in hex', 'errorcode="0x80071151"'], ['with a fraction', 'errorcode="-2147020463.0"'], ['with white space', 'errorcode=" -2147020463"'], ['as an unsigned number', 'errorcode="2147946833"'],+ ['with a plus sign', 'errorcode="+2147020463"'], ['with another digit', 'errorcode="-2147020462"'], ['with a text', 'errorcode="none"'], ['empty', 'errorcode=""'], ['missing', ''],+ ]) {+ const verdict = assertNot(failedOtherwise(replacement), 'other-error', `errorcode: ${what}`);+ assert.ok(!/NaN|undefined|none/.test(verdict.reason), `${what}: ${verdict.reason}`);+ }+ // A text from the platform is never in the reason: only a number that is one.+ assert.doesNotMatch(assertNot(failedOtherwise('errorcode="a secret: kv-secret-value"'), 'other-error', 'a text').reason, /secret|kv-/);+});++test('the solution manifest: there must be one, and EVERY one must be processed="false" exactly', () => {+ const data = refused();+ const manifest = 'LocalizedName="Contoso solution" processed="false"';+ assert.ok(data.includes(manifest));+ assertNot(data.replace(manifest, 'LocalizedName="Contoso solution" processed="true"'), 'manifest-processed', 'processed');+ for (const [what, replacement] of [['no mark', 'LocalizedName="Contoso solution"'], ['another case', 'LocalizedName="Contoso solution" processed="False"'], ['a number', 'LocalizedName="Contoso solution" processed="0"'], ['empty', 'LocalizedName="Contoso solution" processed=""']]) {+ assertNot(data.replace(manifest, replacement), 'manifest-unmarked', `solutionManifest: ${what}`);+ }+ assertNot(data.replace(/<solutionManifests>.*<\/solutionManifests>/, ''), 'no-manifest', 'no solutionManifests');+ assertNot(data.replace(/<solutionManifests>.*<\/solutionManifests>/, '<solutionManifests />'), 'no-manifest', 'an empty list');+ // A second manifest that was processed, beside the one that was not.+ assertNot(data.replace('</solutionManifests>', '<solutionManifest languagecode="1033" processed="true" /></solutionManifests>'), 'manifest-processed', 'one of two');+ assertNot(data.replace('</solutionManifests>', '<solutionManifest languagecode="1033" /></solutionManifests>'), 'manifest-unmarked', 'one of two, with no mark');+ assertProven(data.replace('</solutionManifests>', '<solutionManifest languagecode="1033" processed="false" /></solutionManifests>'), 'two manifests, both unprocessed');+ // The manifest as a node of another name is not one.+ assertNot(data.replace(/solutionManifest\b/g, 'SolutionManifest'), 'no-manifest', 'XML is case-sensitive');+});++test('the components: NO element but the root and the package\'s own checks may be processed — any element, whatever its name, with any value of `processed` but "false"', () => {+ // Every kind of component the log has, and one it has never been seen to have, processed.+ for (const name of ['entity', 'savedQuery', 'formXml', 'entityRibbon', 'rootComponent', 'dependency', 'workflowAndStepActivation', 'entityCustomResources', 'hierarchyrule', 'CustomControlDefaultConfig', 'savedQueryVisualization', 'entityrelationship', 'webResource', 'aNameNobodyHasSeen']) {+ assertNot(refused({ extra: `<${name} id="x" processed="true"></${name}>` }), 'component-processed', `${name} processed`);+ assertNot(refused({ extra: `<${name} processed="true" />` }), 'component-processed', `${name} processed, self-closing`);+ assertProven(refused({ extra: `<${name} id="x" processed="false"></${name}>` }), `${name} unprocessed`);+ assertProven(refused({ extra: `<${name} id="x"></${name}>` }), `${name} with no mark`);+ }+ assertNot(refused({ components: 'true' }), 'component-processed', 'all of them');+ for (const [what, value] of [['another case', 'True'], ['a number', '1'], ['empty', ''], ['a word', 'yes'], ['with white space', ' true'], ['a word that contains it', 'false-ish']]) {+ assertNot(refused({ extra: `<entity id="x" processed="${value}" />` }), 'component-unmarked', `a mark that is ${what}`);+ }+ // The only exemptions are by name: a node that looks like a check, and is not one, is a component. The package's own checks may be processed under any parent; a nested importexportxml is no root.+ assertNot(refused({ extra: '<importexportxml processed="true" />' }), 'component-processed', 'an importexportxml that is not the root');+ assertNot(refused({ extra: '<upgradeHandlers><UpgradeHandler processed="true" /></upgradeHandlers>' }), 'component-processed', 'another case of upgradeHandler');+ assertNot(refused({ extra: '<skuHandlers><skuHandler processed="true" /></skuHandlers>' }), 'component-processed', 'a check that is not one of the two');+ assertProven(refused({ extra: '<upgradeHandler processed="true"><result result="success" errorcode="0" errortext="" /></upgradeHandler><validateHandler processed="true" />' }), 'one more of each check');+});++// --- a document that is read as XML, not searched ---------------------------------------------------------------------------------------++test('the log is read as ONE well-formed XML document and nothing else: what is only text that looks like the rule\'s attributes — in a comment, a CDATA section, a value, character data — is never the attribute', () => {+ // A comment, a processing instruction and character data that spell the proof, over a root that has no verdict.+ const bare = importLog({ root: rootOf({ errorcode: undefined, succeeded: undefined, status: undefined }), manifest: 'false', components: 'false', handlers: 'true' });+ assertNot(bare, 'not-a-failure', 'no verdict');+ assertNot(bare.replace('<solutionManifests>', '<!-- succeeded="failure" errorcode="-2147020463" --><solutionManifests>'), 'not-a-failure', 'the verdict in a comment');+ assertNot(bare.replace('<solutionManifests>', '<?x succeeded="failure" errorcode="-2147020463"?><solutionManifests>'), 'not-a-failure', 'the verdict in a processing instruction');+ assertNot(bare.replace('<solutionManifests>', '<![CDATA[ succeeded="failure" errorcode="-2147020463" ]]><solutionManifests>'), 'not-a-failure', 'the verdict in a CDATA section');+ assertNot(bare.replace('<solutionManifests>', 'succeeded="failure" errorcode="-2147020463"<solutionManifests>'), 'not-a-failure', 'the verdict in character data');+ // Another attribute whose VALUE spells the proof: it is that attribute's value, not a second attribute.+ assertNot(refused().replace('succeeded="failure"', 'succeeded="success" Note=\'succeeded="failure" errorcode="-2147020463"\''), 'not-a-failure', 'the verdict in the value of a note');+ // A processed component that a search by pattern misses and a reader does not: a ">" is allowed in a value, and a tag does not end there.+ assertNot(refused({ extra: '<entity id="a>b" processed="true"></entity>' }), 'component-processed', 'processed after a ">" in a value');+ assertNot(refused({ extra: '<entity Description="an <b>escaped</b> note" processed="true" />' }), 'component-processed', 'processed after an escaped markup in a value');+ assertNot(refused().replace('processed="false">', 'Note="a>b" processed="true">'), 'manifest-processed', 'a processed manifest after a ">" in a value');+ assertNot(refused({ extra: '<entity\nprocessed="true"\n/>' }), 'component-processed', 'processed on a line of its own');+ assertNot(refused({ extra: '<entity id=\'x\' processed=\'true\'/>' }), 'component-processed', 'processed in single quotes');+ assertNot(refused({ extra: '<entity id = "x" processed = "true" />' }), 'component-processed', 'processed with white space around the equals sign');+ assertNot(refused({ extra: '<entity processed="true" />' }), 'component-processed', 'processed="true" written with a character reference');+ assertNot(refused().replace('succeeded="failure"', 'succeeded="success"'), 'not-a-failure', 'succeeded written with a character reference');+ // What is only text is not an element: a processed component inside a CDATA section or a comment is data.+ assertProven(refused({ extra: '<![CDATA[<entity processed="true" />]]><!-- <entity processed="true" /> -->' }), 'markup in a CDATA section and a comment is text');+ // The attributes may come in any order, in either quote style.+ assertProven(refused().replace('errorcode="-2147020463" succeeded="failure"', 'succeeded=\'failure\' errorcode = \'-2147020463\''), 'any order, either quote');+});++test('a log that is not exactly one well-formed XML document proves nothing — and says so — whatever it contains: unclosed or mismatched tags, a second root, text outside the root, a duplicate attribute, an entity that is not predefined, a DOCTYPE', () => {+ const data = refused();+ const cases = [+ ['an unclosed root', data.replace(/<\/importexportxml>$/, '')],+ ['a mismatched end tag', data.replace('</entities>', '</entity>')],+ ['a second root', `${data}<importexportxml />`],+ ['text after the root', `${data} succeeded="failure"`],+ ['text before the root', `x${data}`],+ ['a duplicate succeeded', data.replace('succeeded="failure"', 'succeeded="failure" succeeded="failure"')],+ ['a duplicate errorcode that disagrees', data.replace(`errorcode="${CONCURRENCY_ERRORCODE}"`, `errorcode="${CONCURRENCY_ERRORCODE}" errorcode="-1"`)],+ ['a duplicate processed on a manifest', data.replace('processed="false">', 'processed="false" processed="false">')],+ ['an unquoted value', data.replace('succeeded="failure"', 'succeeded=failure')],+ ['a "<" in a value', data.replace('succeeded="failure"', 'succeeded="fail<ure"')],+ ['an entity that is not predefined', data.replace('Contoso solution', ' ')],+ ['a DOCTYPE with an entity', `<!DOCTYPE importexportxml [<!ENTITY processed "true">]>${data}`],+ ['a DOCTYPE with no entity', `<!DOCTYPE importexportxml>${data}`],+ ['not XML at all', 'The import failed.'],+ ['JSON', JSON.stringify({ succeeded: 'failure', errorcode: -2147020463 })],+ ['a tag that is never closed', '<importexportxml succeeded="failure"'],+ ['white space only', ' \n\t '],+ ['a control character', data.replace('Contoso solution', 'Contoso\u0001solution')],+ ['a declaration of another version', `<?xml version="1.1"?>${data}`],+ ];+ for (const [what, text] of cases) {+ const verdict = assertNot(text, 'log-unreadable', what);+ assert.match(verdict.reason, /not an XML document this script can read/, what);+ }+});++test('the size of a log is bounded: a log longer than 8 MiB is not read, one of exactly 8 MiB is', () => {+ const log = refused();+ const exactly = `${log}${' '.repeat(MAX_JOB_LOG_CHARS - log.length)}`;+ assert.strictEqual(exactly.length, MAX_JOB_LOG_CHARS);+ assertProven(exactly, 'exactly the limit');+ const verdict = assertNot(`${exactly} `, 'log-too-large', 'one more character');+ assert.match(verdict.reason, /longer than 8 MiB/);+ assertNot(' '.repeat(MAX_JOB_LOG_CHARS + 1), 'log-too-large', 'white space past the limit is no reason to read it');+});++test('the rule never throws and never proves on what it cannot make sense of — not a row, not text, a cyclic or a hostile value', () => {+ const hostile = [+ undefined, null, 0, 1, '', 'x', true, [], {}, Symbol('s'), () => {}, new Date(), /x/, new Map(), Object.create(null),+ { completedon: 'x', data: Symbol('d') }, { completedon: 'x', get data() { throw new Error('a getter that throws'); } }, { get completedon() { throw new Error('boom'); }, data: refused() },+ ];+ const cyclic = { completedon: 'x' };+ cyclic.data = cyclic;+ hostile.push(cyclic);+ for (const value of hostile) {+ let verdict;+ assert.doesNotThrow(() => { verdict = refusedBeforeAnyComponent(value); }, String(typeof value));+ assert.strictEqual(verdict.proven, false, String(typeof value));+ assert.strictEqual(typeof verdict.why, 'string');+ }+});++// --- the answer of the read ---------------------------------------------------------------------------------------------------------------++test('proveRefusedImport: a 404 is proof whatever its body says; a 200 is proof only through its row; any other answer — or none — proves nothing, and says which', () => {+ for (const body of [undefined, null, '', 'Not Found', { error: { code: '0x80040217', message: 'importjob With Id = x Does Not Exist' } }, { error: { code: 'something else' } }, []]) {+ assert.deepStrictEqual(proveRefusedImport({ status: 404, body }), { proven: true, proof: PROOF_ABSENT }, JSON.stringify(body));+ }+ assert.deepStrictEqual(proveRefusedImport({ status: 200, body: jobRow(refused()) }), { proven: true, proof: PROOF_LOG });+ const notProof = proveRefusedImport({ status: 200, body: jobRow(LOGS.failedAfterStart()) });+ assert.deepStrictEqual([notProof.proven, notProof.why], [false, 'other-error']);+ assert.deepStrictEqual(proveRefusedImport({ status: 200 }), { proven: false, why: 'no-log', reason: 'its import job has no log to read' });+ for (const status of [201, 204, 301, 400, 401, 403, 405, 408, 409, 412, 429, 500, 502, 503, 504]) {+ const verdict = proveRefusedImport({ status, body: jobRow(refused()) });+ assert.deepStrictEqual(verdict, { proven: false, why: 'unreadable', reason: `the read of its import job answered HTTP ${status}, which is neither the job nor a 404` }, String(status));+ }+ for (const answer of [null, undefined, 0, 'x', {}, { status: 'ok' }, { status: NaN }, { status: 200.5 }, { body: jobRow(refused()) }]) {+ const verdict = proveRefusedImport(answer);+ assert.deepStrictEqual([verdict.proven, verdict.why], [false, 'no-answer'], JSON.stringify(answer));+ }+});++test('the words that say why a job is no proof are fixed text and numbers — nothing the platform wrote is in them', () => {+ const secret = 'kv-secret-value-0123456789';+ const text = (data, row) => verdictOf(data, row).reason;+ assert.strictEqual(text(LOGS.running(), { completed: false }), 'its import job is not finished (completedon is empty)');+ assert.strictEqual(text(null), 'its import job has no log to read');+ assert.strictEqual(text('<importexportxml'), 'the log of its import job is not an XML document this script can read');+ assert.strictEqual(text('<other />'), 'the log of its import job is not an importexportxml document');+ assert.strictEqual(text(LOGS.succeeded()), 'the log of its import job does not say that the import failed');+ assert.strictEqual(text(LOGS.failedAfterStart()), 'the log of its import job says the import failed with error 0x80048033, not with 0x80071151');+ assert.strictEqual(text(refused().replace(`errorcode="${CONCURRENCY_ERRORCODE}"`, '')), 'the log of its import job does not give the error code the import failed with');+ assert.strictEqual(text(refused().replace(`errorcode="${CONCURRENCY_ERRORCODE}"`, 'errorcode="7.5"')), 'the log of its import job gives an error code this script does not recognise');+ assert.strictEqual(text(refused().replace(/<solutionManifests>.*<\/solutionManifests>/, '')), 'the log of its import job has no solution manifest');+ assert.strictEqual(text(refused({ manifest: 'true' })), 'the log of its import job shows that the import began to apply the package (its solution manifest is processed)');+ assert.strictEqual(text(refused({ manifest: undefined })), 'the log of its import job does not say that its solution manifest was left unprocessed');+ assert.strictEqual(text(refused({ components: 'true' })), 'the log of its import job shows that the import began to apply components of the package');+ assert.strictEqual(text(refused({ extra: '<entity processed="maybe" />' })), 'the log of its import job marks a component in a way this script does not recognise');+ // What the platform wrote — the status of the root, an error text, a name — is never carried into a reason.+ for (const [what, data] of [+ ['the status', LOGS.failedAfterStart().replace('The import failed.', secret)],+ ['an error code', refused().replace(`errorcode="${CONCURRENCY_ERRORCODE}"`, `errorcode="${secret}"`)],+ ['a mark', refused({ extra: `<entity processed="${secret}" />` })],+ ['a name', refused({ extra: `<${'x'}${secret.replace(/[^a-z]/g, '')} processed="true" />` })],+ ]) assert.ok(!verdictOf(data).reason.includes(secret) && !verdictOf(data).reason.includes('kvsecretvalue'), what);+});diff --git a/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.jsnew file mode 100644index 000000000..fcd0a045c--- /dev/null+++ b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js@@ -0,0 +1,508 @@+'use strict';+// The CROSS-FEATURE REGRESSION MATRIX: one kitchen-sink App Spec — every feature the fake environment can model faithfully — driven+// through the whole lifecycle a maker runs, over the REAL vendored SDK, the plugin's own az-token HTTP client and a stateful fake+// Dataverse (helpers/fake-lifecycle-org.js):+//+// build buildModelApp, as the CLI wires it (--apply --publish --sample-data --verify)+// NOOP rebuild the same spec again, unchanged: what it still writes and publishes is pinned, request by request+// download download-model-app.js main(), as the CLI runs it: the spec it writes must equal the authored one, except for the+// differences the round trip is documented to have (the difference table at THE ROUND TRIP, below)+// verify verifySpec over the CLI's reader, in a throwaway workspace: every check passes, and the checks it makes are pinned+// teardown teardownModelApp --apply --allow-destructive: the environment ends exactly as it started, but for what teardown is+// documented to keep+//+// Another maker's work is in the environment from the start, and every stage is held to leaving it — and every row and definition the+// environment had — as it found it, compared by CONTENT (saved and published layers, whole definitions, page files: org.contents),+// not only by identity; the two read-only stages (download, verify) to changing nothing at all.+//+// Each phase also has a REQUEST BUDGET: its writes are pinned exactly (`METHOD resource` -> count) and its reads are held under a+// ceiling, so a regression that adds a write — or turns one read into one per row — fails here even when every artifact still ends up+// right. Every pinned number lives in ONE table per phase below; when a change moves one on purpose, update that line and say why in+// the commit. The tables say which behaviour each entry depends on, so a reader can tell an intended change from a regression.+//+// What the fake models, and what it does NOT (those features are left out of this spec on purpose — an assertion about them here would+// be an assertion about the fake, not about the plugin):+// - business rules: the bound member the SDK writes them through is a preview most environments do not expose, and its success path+// is not modelled. The fake answers as an environment without it (404), which the build turns into a skip and a warning — pinned+// by business-rules tests, not here.+// - business process flows: activating one makes the platform create the flow's backing table, whose shape is not modelled.+// - AI features: admin-gated settings and row summaries whose platform behaviour is not modelled.+// - localized labels in a second language, connector/Custom API page bindings, and pages whose source holds navigation tokens.+// Everything else the App Spec offers is in the spec: new tables with every column type, a Customer column, a global choice, status+// reasons, an alternate key, 1:N, self-referencing 1:N and N:N relationships, views (sorted, filtered, my-records), a chart, Main /+// Quick Create / Quick View forms with a sub-grid, a quick view, form events and security roles, a dashboard of chart, list and iframe+// tiles, web resources (script and table icon), commands (a button and a flyout), a generative page, navigation with table, dashboard,+// URL and page entries, app settings (new look, header refresh), app.tables membership, sample data with a parent and a status reason,+// a persona with its role, and a grant on an existing role.+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 { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { kitchenSinkSpec, createLifecycleHarness, seedForeignWork, deployedFeatures, publishesOf, diffContents, appUniqueName, PAGE_SOURCE } = require('./helpers/lifecycle-harness.js');+const { validateAppSpec } = require('../lib/app-spec.js');++// ------------------------------------------------------------------------------------------------------------------------------------+// The lifecycle, run ONCE for the file (every test below reads its stage of it), in the order a maker runs it. A stage that throws is+// recorded, and every later stage still runs against what is there, so one regression fails its own test and not the whole matrix.+let lifecycleP;+const lifecycle = () => lifecycleP || (lifecycleP = runLifecycle());++async function runLifecycle() {+ const spec = kitchenSinkSpec();+ const org = createLifecycleOrg();+ const harness = createLifecycleHarness(org, makeTempDir('lifecycle-matrix-'));+ // Another maker's work is there first: everything the lifecycle does must leave it as it was.+ await seedForeignWork(org);+ // What it holds then, by identity (inventory) and by content (contents, after every stage too): the proofs that a stage made and+ // deleted only its own, and left everything else — another maker's work, the system's rows and definitions — exactly as it was.+ const out = { spec, org, seed: org.inventory(), seedContents: org.contents(), contents: {}, stages: {}, timings: {} };+ const stage = async (name, fn) => {+ out.stages[name] = await harness.measure(fn);+ out.timings[name] = out.stages[name].ms;+ out.contents[name] = org.contents();+ };+ await stage('build', () => harness.build(spec));+ out.afterBuild = org.inventory();+ // The one row a teardown leaves behind on purpose: the publisher the build made for the prefix (see the teardown test).+ out.builtPublisher = out.afterBuild.rows.publishers.filter((p) => !out.seed.rows.publishers.includes(p));+ out.built = deployedFeatures(org);+ // The ids the round trip writes back, read from what the environment holds once the app is built (teardown removes them).+ const one = (set, predicate) => { const rows = org.find(set, predicate); return rows.length === 1 ? rows[0] : null; };+ out.ids = {+ dashboard: (one('systemforms', (f) => f.type === 0 && f.name === 'Kitchen Overview') || {}).formid,+ openProjects: (one('savedqueries', (v) => v.returnedtypecode === 'contoso_project' && v.name === 'Open Projects') || {}).savedqueryid,+ chart: (one('savedqueryvisualizations', (c) => c.name === 'Projects by Priority') || {}).savedqueryvisualizationid,+ page: ([...org.pageServer.state.projects.values()].find((p) => p.name === 'Kitchen Page') || {}).id,+ };+ await stage('rebuild', () => harness.build(spec));+ out.afterRebuild = org.inventory();+ await stage('download', () => harness.download(appUniqueName(spec), path.join(harness.appDir, '..', 'download')));+ await stage('verify', () => harness.verify(spec));+ await stage('teardown', () => harness.teardown(spec));+ out.afterTeardown = org.inventory();+ return out;+}+++// A stage that threw fails its own test with the cause.+function stageOf(run, name) {+ const s = run.stages[name];+ assert.ok(s, `the ${name} stage ran`);+ if (s.error) throw s.error;+ assert.deepEqual(s.unexpected, [], `every request the ${name} stage sent is one the fake models`);+ return s;+}++// ====================================================================================================================================+// THE PINNED NUMBERS — one table per phase. Writes are counted per operation (a `$batch` change set counts each request it carries),+// named `METHOD resource` with keys and query left out. A table entry that moves on purpose is a one-line change here.++// The first build. Each entry is a write the build makes for the spec above; the comment names the step that makes it.+const BUILD_WRITES = {+ 'POST publishers': 1, // solution: the publisher for the prefix, which no environment has yet+ 'POST solutions': 1, // solution: ContosoKitchen+ 'POST GlobalOptionSetDefinitions': 1, // data model: the global choice+ 'POST EntityDefinitions': 3, // data model: each table, with its primary name column only+ 'POST EntityDefinitions/Attributes': 17, // data model: the ordinary columns in one change set per table (12 + 2), and the global choice's, the File and the Image column in a request each+ 'POST InsertStatusValue': 1, // data model: the status reason, at its pinned value+ 'POST EntityDefinitions/Keys': 1, // data model: the alternate key+ 'POST CreateCustomerRelationships': 1, // data model: the Customer column and its two relationships+ 'POST RelationshipDefinitions': 3, // data model: 1:N, self 1:N and N:N+ 'PUT EntityDefinitions': 2, // data model: quick create on the Quick Create form's table; web resources: the table icon+ 'POST contoso_projects/Microsoft.Dynamics.CRM.CreateMultiple': 1, // sample data: the parent row first+ 'POST contoso_tasks/Microsoft.Dynamics.CRM.CreateMultiple': 1, // sample data: then the child that binds it+ 'POST webresourceset': 4, // the script, the table icon, the generated app icon, the page manifest+ 'POST savedqueries': 3, // views+ 'PATCH savedqueries': 4, // the default-view enrichment of the two tables with columns to show (Active and Inactive each)+ 'POST savedqueryvisualizations': 1, // chart+ 'POST systemforms': 5, // four forms and the dashboard+ 'PATCH systemforms': 6, // the Project form's sub-grid, each table's Main form made the default (2), the Task form's order and its quick view, the Project form's security roles+ 'POST appactions': 4, // commands: the button, the flyout, the group the adapter puts under it, and its child+ 'POST appmodules': 1,+ 'POST sitemaps': 1,+ 'PATCH sitemaps': 1, // the pages phase writes the page's navigation entry into the sitemap once the page exists+ 'POST AddAppComponents': 3, // the app's create, the app.tables member pinned after it, the sitemap finalize+ 'POST appmodules/appmoduleroles_association/$ref': 2, // System Administrator (the SDK's create) and the persona's role+ 'POST appsettings': 1, // the header refresh setting the SDK writes with a new app+ 'PATCH appsettings': 1, // ...set to the spec's false+ 'POST SaveSettingValue': 1, // the new look setting+ 'POST uxagentprojects': 1, // the generative page...+ 'PATCH uxagentprojects': 1,+ 'POST uxagentprojectfiles': 4, // ...its four rows+ 'PATCH uxagentprojectfiles/filecontent': 4, // ...and their content+ 'POST agentconversationmessages': 2, // ...and the conversation the maker sees+ 'POST roles': 1, // the persona's role+ 'POST roles/Microsoft.Dynamics.CRM.ReplacePrivilegesRole': 1, // its privileges, converged+ 'POST roles/Microsoft.Dynamics.CRM.AddPrivilegesRole': 1, // the grant on Basic User, added+ 'POST AddSolutionComponent': 16, // each component the build creates or reuses that the solution does not already hold+ 'POST PublishXml': 11, // see BUILD_PUBLISHES+};+// What each publish of the first build names, in order (an app or a page id is `app` / `page`, a web resource `webresource`).+const BUILD_PUBLISHES = [+ 'webresource', 'webresource', // the script and the table icon, each published before anything points at it+ 'contoso_project', // the table whose icon was just set+ 'webresource', // the generated app icon+ 'contoso_project contoso_tag contoso_task', // the tables before the app's first publish, so their saved labels go live+ 'app', // the app's create+ 'app', // the app again after the app.tables member is pinned+ 'page', // the generative page+ 'webresource', // the page manifest+ 'app', // the app after the sitemap finalize put the page in its navigation+ 'contoso_project contoso_task app', // the publish phase: the tables of the spec's forms, views and charts, with the app+];++// The rebuild of the UNCHANGED spec. It is not free: each line is a write the current build still sends when nothing changed, and+// what it depends on. A line that disappears is progress (lower it here); a line that appears is a regression.+const REBUILD_WRITES = {+ 'POST InsertStatusValue': 1, // re-sent at its pinned value; the platform's "already exists" is the skip (entity-provision.js)+ 'POST EntityDefinitions/Keys': 1, // the SDK has no key lister: re-sent, "already exists" is the skip (entity-provision.js)+ 'PUT EntityDefinitions': 2, // the quick-create flag and the table icon are re-asserted on every build (entity-provision.js, sdk-build.js 3c)+ 'PATCH savedqueries': 4, // the SDK's default-view enrichment saves both generated views of each table on every build (rebuild-writes-real-bundle.test.js)+ 'PATCH systemforms': 3, // isdefault is set again on each table's chosen Main form (promoteDefaultForm reads nothing first), and the form's security roles are rewritten byte for byte+ 'PATCH sitemaps': 1, // the sitemap of an existing app is rewritten by the pages finalize, byte for byte+ 'POST AddAppComponents': 1, // ...and the push re-adds the app's components+ 'POST SaveSettingValue': 1, // the new look setting is saved again+ 'POST roles/Microsoft.Dynamics.CRM.ReplacePrivilegesRole': 1, // a persona role converges with replace semantics on every build+ 'POST appmodules/appmoduleroles_association/$ref': 1, // re-associated; the platform refuses the duplicate and the build reads that as "already linked"+ 'POST roles/Microsoft.Dynamics.CRM.AddPrivilegesRole': 1, // a role grant is additive and re-sent+ 'POST PublishXml': 4, // see REBUILD_PUBLISHES+};+const REBUILD_PUBLISHES = [+ 'contoso_project', // the table icon set again+ 'contoso_project contoso_tag contoso_task', // the tables before the app's publish+ 'app', // the app after the sitemap finalize+ 'contoso_project contoso_task app', // the publish phase+];++// The teardown: every component the build made is deleted, in dependency order.+const TEARDOWN_WRITES = {+ 'DELETE appmodules': 1, // the app and its sitemap, in one change set+ 'DELETE sitemaps': 1,+ 'DELETE uxagentprojects': 1, // the page this app's navigation proved it owns...+ 'DELETE agentconversationmessages': 2, // ...and its conversation, which a project delete does not cascade+ 'DELETE systemforms': 5, // the dashboard and the four forms+ 'DELETE appactions': 4,+ 'PATCH systemforms': 2, // the stock Main forms made the default again before the build's Main forms go+ 'DELETE roles': 1, // the persona's role (the grant on Basic User is one-way: references/app-spec-schema-advanced.md)+ 'DELETE savedqueryvisualizations': 1,+ 'DELETE savedqueries': 3,+ 'PATCH savedqueries': 4, // the enriched default views reset to lookup-free columns, so the relationships can go...+ 'POST PublishXml': 1, // ...published once+ 'DELETE RelationshipDefinitions': 2, // the self-referencing 1:N goes with its table+ 'DELETE EntityDefinitions': 3,+ 'DELETE webresourceset': 4,+ 'DELETE GlobalOptionSetDefinitions': 1,+ 'DELETE solutions': 1,+};++// Reads per phase: a ceiling about a tenth above what each phase reads today, so a read that starts being made once per row fails+// here. HTTP requests (reads, writes and change sets) likewise.+const BUDGET = {+ build: { reads: 335, requests: 430 }, // today 302 / 392+ rebuild: { reads: 295, requests: 320 }, // today 268 / 289+ download: { reads: 130, requests: 130 }, // today 117 / 117 (the File and the Image column's sizes are one read each, of the one table that has them)+ verify: { reads: 85, requests: 85 }, // today 74 / 74+ teardown: { reads: 95, requests: 135 }, // today 86 / 122+};++// What verify checks, by kind: a kind that stops being checked (or is checked fewer times) fails here even though verify still passes.+const VERIFY_CHECKS = {+ entity: 3, column: 18, relationship: 3,+ view: 3, 'view-columns': 3, 'view-filters': 3, 'view-sort': 1, chart: 1,+ form: 4, 'form-identities': 4, 'form-default': 2, 'form-order': 1, 'form-order-served': 1, 'form-timeline': 1,+ dashboard: 1, command: 1,+ subarea: 4, 'subarea-dashboard-launcher': 1, 'app-table-component': 4, page: 1, 'page-subarea': 1,+ role: 1, 'app-role': 1, 'role-privileges': 1, 'role-grant': 1, 'role-grant-privileges': 1,+};++++// What the environment holds once the build is done — every feature of the spec, read from the environment's own state.+const BUILT = {+ tables: {+ contoso_project: {+ plural: 'Projects', icon: 'contoso_projecticon.svg', quickCreate: false,+ columns: {+ contoso_billable: 'BooleanType None Yes/No',+ contoso_budget: 'MoneyType None 0..1000000000 precision 2', // the SDK's defaults for a Money column+ contoso_bytes: 'BigIntType None',+ contoso_contract: 'FileType None 1024 KB',+ contoso_due: 'DateTimeType None DateOnly',+ contoso_email: 'StringType None Email max 200',+ contoso_headcount: 'IntegerType None None 0..500',+ contoso_labels: 'MultiSelectPicklistType None Red|Green|Blue',+ contoso_logo: 'ImageType None 10240 KB', // the SDK's default size+ contoso_name: 'StringType None max 100', // the primary name column: the length the build asks for when the spec gives none+ contoso_notes: 'MemoType None TextArea',+ contoso_parentprojectid: 'LookupType None contoso_project', // the self-referencing relationship's lookup+ contoso_priority: 'PicklistType None Low|Medium|High',+ contoso_rate: 'DecimalType None -100000000000..100000000000 precision 2',+ contoso_ref: 'StringType None max 100 P-{SEQNUM:5}',+ contoso_score: 'DoubleType None -100000000000..100000000000 precision 2',+ contoso_stage: 'PicklistType None global Planned|Active|Done',+ },+ keys: ['contoso_emailkey(contoso_email)'],+ statusReasons: ['1 Active state 0', '2 Inactive state 1', '100000000 In Review state 0'],+ },+ contoso_task: {+ plural: 'Task Items', icon: null, quickCreate: true, // the Quick Create form turns quick create on+ columns: {+ contoso_customer: 'CustomerType None account|contact',+ contoso_done: 'BooleanType None Yes/No',+ contoso_hours: 'IntegerType None None -2147483648..2147483647',+ contoso_projectid: 'LookupType None contoso_project',+ contoso_title: 'StringType None max 100',+ },+ keys: [],+ statusReasons: ['1 Active state 0', '2 Inactive state 1'],+ },+ contoso_tag: { plural: 'Tag Catalog', icon: null, quickCreate: false, columns: { contoso_label: 'StringType None max 100' }, keys: [], statusReasons: ['1 Active state 0', '2 Inactive state 1'] },+ // The N:N's intersect table, which the platform makes with the relationship.+ contoso_tag_contoso_task: { plural: 'contoso_tag_contoso_task', icon: null, quickCreate: false, intersect: true, columns: {}, keys: [], statusReasons: ['1 Active state 0', '2 Inactive state 1'] },+ },+ relationships: [+ 'contoso_contoso_task_account 1:N account->contoso_task.contoso_customer',+ 'contoso_contoso_task_contact 1:N contact->contoso_task.contoso_customer',+ 'contoso_project_contoso_project 1:N contoso_project->contoso_project.contoso_parentprojectid',+ 'contoso_project_contoso_task 1:N contoso_project->contoso_task.contoso_projectid',+ 'contoso_tag_contoso_task N:N contoso_task-contoso_tag',+ ],+ optionSets: { contoso_stage: ['100000000 Planned', '100000001 Active', '100000002 Done'] },+ views: ['contoso_project: Open Projects', 'contoso_task: My Open Tasks', 'contoso_task: Open Tasks'],+ // The chart as it draws: its type, and what it counts by what (the chart's datadescription and presentationdescription).+ charts: ['contoso_project: Projects by Priority (Pie: count(contoso_projectid) by contoso_priority)'],+ // Each table's chosen Main form is its default (the platform keeps one), next to the stock form the platform made.+ forms: [+ 'contoso_project: Information (type 2)', 'contoso_project: Project (type 2, default)', 'contoso_project: Project Card (type 6)',+ 'contoso_tag: Information (type 2, default)',+ 'contoso_task: Information (type 2)', 'contoso_task: Task (type 2, default)', 'contoso_task: Task Quick Create (type 7)',+ ],+ dashboards: ['Kitchen Overview'],+ commands: ['contoso_project', 'contoso_project', 'contoso_project', 'contoso_project'],+ webResources: ['contoso_kitchensink_icon', 'contoso_kitchensink_pagemanifest', 'contoso_project.js', 'contoso_projecticon.svg'],+ app: { uniquename: 'contoso_kitchensink', published: true, tables: ['contact', 'contoso_project', 'contoso_tag', 'contoso_task'], components: [1, 26, 59, 60, 62] },+ navigation: 6,+ // The new look on; the header refresh written OFF, in the SDK's tri-state encoding (references/app-spec-schema.md, headerNavigationRefresh).+ settings: { NewLookAlwaysOn: 'true', HeaderAndNavigationRefresh: '1' },+ page: { name: 'Kitchen Page', published: true },+ // The persona's jobs, unioned: businessUnit is Local (2), user Basic (1), and the app's read (Global, 8) for appAccess.+ personaRole: ['prvCreatecontoso_project 2', 'prvReadappmodule 8', 'prvReadcontoso_project 2', 'prvReadcontoso_task 1', 'prvWritecontoso_project 2'],+ basicUserGrants: ['prvReadcontoso_tag 8'],+ records: { projects: ['Apollo status 100000000'], tasks: ['Kickoff -> Apollo'] },+ unpublished: [],+};++// The publishes of a stage (helpers/lifecycle-harness.js publishesOf).+const publishesOfStage = (run, name) => publishesOf(run.org, run.stages[name]);++function withinBudget(s, name) {+ const requests = s.end - s.mark;+ assert.ok(s.reads <= BUDGET[name].reads, `${name} reads ${s.reads}, its budget is ${BUDGET[name].reads}`);+ assert.ok(requests <= BUDGET[name].requests, `${name} sends ${requests} requests, its budget is ${BUDGET[name].requests}`);+}++test('lifecycle matrix: the build makes every feature of the kitchen-sink spec, publishes all of it, and its own verify passes', async (t) => {+ const run = await lifecycle();+ const s = stageOf(run, 'build');+ t.diagnostic(`build ${run.timings.build} ms, ${s.end - s.mark} requests (${s.reads} reads)`);+ const { result, warnings } = s.value;+ assert.equal(result.ok, true, JSON.stringify(result.errors || result.error));+ assert.deepEqual(result.verify && { ok: result.verify.ok, missing: result.verify.missing }, { ok: true, missing: [] }, 'the build\'s --verify finds every artifact');+ assert.deepEqual(warnings, [], 'the build of this spec warns about nothing');+ assert.deepEqual(run.built, BUILT, 'the environment holds every feature as the spec declares it');+ assert.deepEqual(diffContents(run.seedContents, run.contents.build, { added: false }), [], 'every artifact the environment held before the build — another maker\'s, the system\'s — holds exactly what it held');+ assert.deepEqual(s.writes, BUILD_WRITES);+ assert.deepEqual(publishesOfStage(run, 'build'), BUILD_PUBLISHES);+ assert.deepEqual(s.unpublished, [], 'nothing is left saved but not published');+ withinBudget(s, 'build');+});++test('lifecycle matrix: rebuilding the unchanged spec creates and deletes nothing, and sends only the writes the budget lists', async (t) => {+ const run = await lifecycle();+ const s = stageOf(run, 'rebuild');+ t.diagnostic(`rebuild ${run.timings.rebuild} ms, ${s.end - s.mark} requests (${s.reads} reads)`);+ const { result, warnings } = s.value;+ assert.equal(result.ok, true, JSON.stringify(result.errors || result.error));+ assert.deepEqual(result.verify && { ok: result.verify.ok, missing: result.verify.missing }, { ok: true, missing: [] });+ assert.deepEqual(run.afterRebuild, run.afterBuild, 'the environment holds exactly what it held after the build: no component, column, row, link or page is added or removed');+ assert.deepEqual(diffContents(run.seedContents, run.contents.rebuild, { added: false }), [], 'every artifact the environment held before the build still holds exactly what it held');+ assert.deepEqual(s.writes, REBUILD_WRITES);+ assert.deepEqual(publishesOfStage(run, 'rebuild'), REBUILD_PUBLISHES);+ assert.deepEqual(s.unpublished, []);+ // Documented: a view that exists keeps its filters and sort, and the build says so (references/app-spec-schema.md, views[]).+ assert.deepEqual(warnings.slice().sort(), [+ "view 'My Open Tasks' already exists — its columns and description were updated, but authored filters/sort are NOT reapplied to an existing view. Rename the view to author a separate one, or adjust its filters in Maker.",+ "view 'Open Projects' already exists — its columns and description were updated, but authored filters/sort are NOT reapplied to an existing view. Rename the view to author a separate one, or adjust its filters in Maker.",+ ]);+ withinBudget(s, 'rebuild');+});++// ====================================================================================================================================+// THE ROUND TRIP. The spec a download writes is the authored spec, but for these differences — each one the step below makes. Where+// the round trip is documented to differ, the comment says where; the rest are what it does today and are reported as gaps.+// documented forms[], views[], charts[] and commands[] are not reconstructed; the download names them (notRoundTripped)+// (docs/app-builder-capabilities.md, "Round-trip scope")+// documented a table, relationship and global choice read back is marked `existing: true`, so a teardown of the downloaded spec never+// deletes it; the app's immutable `uniqueName` and each page's `pageId` are written; a page's source is stored under+// pages/<pageId>/ and its prompt is written (references/app-spec-schema.md, app.uniqueName and pages[])+// documented a dashboard comes back pinned by `dashboardId`, its tiles bound to the deployed view and chart ids+// documented an AutoNumber column comes back as Text (download-model-app.js: "no AutoNumber column or format is ever emitted")+// documented a lookup label that is the referenced table's display name is left out (it is the default)+// documented a File or Image column comes back typed, with the size it was made with unless that is the size a build gives a column+// that sets none (docs/app-builder-capabilities.md, "Round-trip scope")+// documented a table's first Image column comes back with `isPrimaryImage: true`: the platform makes it the table's primary image+// whatever the create sent (MEASURED on a live environment; helpers/fake-lifecycle-metadata.js models it)+// documented a table's plural comes back when it is not the display name plus "s", the one a rebuild would derive+// (references/app-spec-schema.md, "Round-trip")+// documented personas[] are not carried (references/app-spec-schema.md: "a download carries none")+// warned a Customer column is left out: its two relationships have no relationships[] form (the download warns)+// gap solution.displayName, a global choice's displayName, a table's vectorIcon, statusReasons and alternateKeys, a column's+// type options (format, length, range, precision, labels, date format), a dashboard tile's size, script and+// table-icon web resources, roleGrants[] and sampleData are not carried+function expectedDownload(authored, ids) {+ const byName = (a, b) => (a.schemaName < b.schemaName ? -1 : a.schemaName > b.schemaName ? 1 : 0);+ const column = (c, primaryImage) => ({+ schemaName: c.schemaName,+ displayName: c.displayName,+ type: c.type === 'AutoNumber' ? 'Text' : c.type, // documented+ ...(c.options ? { options: c.options } : {}),+ ...(c.globalChoice ? { globalChoice: c.globalChoice } : {}),+ ...((c.type === 'File' || c.type === 'Image') && c.maxSizeKb !== undefined ? { maxSizeKb: c.maxSizeKb } : {}), // documented+ ...(c === primaryImage ? { isPrimaryImage: true } : {}), // documented+ });+ const entity = (e) => ({+ schemaName: e.schemaName,+ displayName: e.displayName,+ ...(e.pluralName !== `${e.displayName}s` ? { pluralName: e.pluralName } : {}), // documented+ primaryAttribute: { schemaName: e.primaryAttribute.schemaName, displayName: e.primaryAttribute.displayName },+ columns: e.columns+ .filter((c) => c.type !== 'Customer') // warned+ .map((c) => column(c, e.columns.find((x) => x.type === 'Image'))).sort(byName),+ existing: true,+ description: e.description,+ });+ const tableName = new Map(authored.entities.map((e) => [e.schemaName, e.displayName]));+ const relationship = (r) => (r.type === 'ManyToMany'+ ? { type: r.type, entity1: r.entity1, entity2: r.entity2, existing: true }+ : { type: r.type, referenced: r.referenced, referencing: r.referencing, lookup: { schemaName: r.lookup.schemaName, ...(r.lookup.displayName !== tableName.get(r.referenced) ? { displayName: r.lookup.displayName } : {}) }, existing: true });+ const dashboard = authored.dashboards[0];+ const page = authored.pages[0];+ return {+ schemaVersion: authored.schemaVersion,+ minimumPluginVersion: authored.minimumPluginVersion,+ solution: { uniqueName: authored.solution.uniqueName, publisherPrefix: authored.solution.publisherPrefix, description: authored.solution.description },+ app: { ...authored.app, uniqueName: 'contoso_kitchensink' },+ entities: authored.entities.map(entity),+ relationships: authored.relationships.map(relationship),+ globalChoices: authored.globalChoices.map((g) => ({ name: g.name, options: g.options, existing: true })),+ webResources: [],+ views: [],+ charts: [],+ forms: [],+ commands: [],+ dashboards: [{+ name: dashboard.name,+ dashboardId: ids.dashboard,+ description: dashboard.description,+ tiles: [+ { type: 'chart', name: 'Projects by Priority', entity: 'contoso_project', viewId: ids.openProjects, visualizationId: ids.chart },+ { type: 'list', name: 'Open', entity: 'contoso_project', viewId: ids.openProjects },+ { type: 'iframe', name: 'Status', url: 'https://contoso.example/status' },+ ],+ }],+ pages: [{ key: page.key, name: page.name, pageId: ids.page, purpose: page.purpose, dataSources: page.dataSources, prompt: `Generative page ${page.name}`, source: { kind: 'tsx', codeFile: `pages/${ids.page}/page.tsx` } }],+ // The page's navigation entry comes back with the icon the build gave it.+ appShell: { areas: authored.appShell.areas.map((a) => ({ ...a, groups: a.groups.map((g) => ({ ...g, subAreas: g.subAreas.map((sa) => (sa.page ? { ...sa, vectorIcon: '/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg' } : sa)) })) })) },+ };+}+// Relationships come back in an order the reads decide; the comparison is of the set.+const relationshipKey = (r) => `${r.type} ${r.referenced || r.entity1} ${r.referencing || r.entity2} ${r.lookup ? r.lookup.schemaName : ''}`;+const sortRelationships = (spec) => ({ ...spec, relationships: [...(spec.relationships || [])].sort((a, b) => (relationshipKey(a) < relationshipKey(b) ? -1 : 1)) });++test('lifecycle matrix: the download writes the authored spec back, but for the differences the round trip is pinned to', async (t) => {+ const run = await lifecycle();+ const s = stageOf(run, 'download');+ t.diagnostic(`download ${run.timings.download} ms, ${s.end - s.mark} requests`);+ const { emitted, stderr, spec, dir } = s.value;+ assert.equal(emitted && emitted.ok, true, JSON.stringify(emitted));+ assert.deepEqual(s.writes, {}, 'a download writes nothing to the environment');+ assert.deepEqual(diffContents(run.contents.rebuild, run.contents.download), [], 'and changes nothing in it');+ const { descriptionInventory, ...downloaded } = spec;+ assert.deepEqual(sortRelationships(downloaded), sortRelationships(expectedDownload(run.spec, run.ids)));+ // The page's source comes back byte for byte.+ assert.equal(fs.readFileSync(path.join(dir, 'pages', run.ids.page, 'page.tsx'), 'utf8'), PAGE_SOURCE);+ // What it does not carry, it names: the forms, views and charts of each table.+ assert.deepEqual(emitted.payload.notRoundTripped.classes, [{ kind: 'forms', count: 5, label: 'form' }, { kind: 'views', count: 9, label: 'view' }, { kind: 'charts', count: 1, label: 'chart' }]);+ assert.deepEqual(Object.fromEntries(Object.entries(descriptionInventory).map(([k, list]) => [k, list.map((x) => (x.entity ? `${x.entity}: ${x.name}` : x.name))])), {+ views: ['contoso_project: Active Projects', 'contoso_project: Inactive Projects', 'contoso_project: Open Projects', 'contoso_tag: Active Tag Catalog', 'contoso_tag: Inactive Tag Catalog', 'contoso_task: Active Task Items', 'contoso_task: Inactive Task Items', 'contoso_task: My Open Tasks', 'contoso_task: Open Tasks'],+ charts: ['contoso_project: Projects by Priority'],+ forms: ['contoso_project: Information', 'contoso_project: Project', 'contoso_tag: Information', 'contoso_task: Information', 'contoso_task: Task'],+ globalChoices: ['contoso_stage'],+ });+ // ...and it warns about the two losses a rebuild elsewhere would otherwise not show.+ const warningLines = stderr.split('\n').filter((l) => /^WARNING:/.test(l));+ assert.equal(warningLines.length, 2, stderr);+ assert.match(warningLines[0], /lookup 'contoso_customer' is polymorphic \(targets account, contact\)/);+ assert.match(warningLines[1], /restricted to specific security roles \(contoso_project\.Project\)/);+ // The written spec is one the build takes.+ const validation = validateAppSpec(spec, { profile: 'plan', reconstructed: true });+ assert.deepEqual(validation.errors, []);+ withinBudget(s, 'download');+});++test('lifecycle matrix: verify passes, and makes every check it made before', async (t) => {+ const run = await lifecycle();+ const s = stageOf(run, 'verify');+ t.diagnostic(`verify ${run.timings.verify} ms, ${s.end - s.mark} requests`);+ const result = s.value;+ assert.deepEqual({ ok: result.ok, missing: result.missing, unverified: result.unverified || [] }, { ok: true, missing: [], unverified: [] });+ const kinds = {};+ for (const c of result.checks) kinds[c.kind] = (kinds[c.kind] || 0) + 1;+ assert.deepEqual(kinds, VERIFY_CHECKS);+ assert.deepEqual(s.writes, {}, 'verify writes nothing');+ assert.deepEqual(diffContents(run.contents.download, run.contents.verify), [], 'and changes nothing');+ withinBudget(s, 'verify');+});++test('lifecycle matrix: teardown deletes everything the build made and nothing else', async (t) => {+ const run = await lifecycle();+ const s = stageOf(run, 'teardown');+ t.diagnostic(`teardown ${run.timings.teardown} ms, ${s.end - s.mark} requests; whole lifecycle ${Object.values(run.timings).reduce((a, b) => a + b, 0)} ms`);+ const { result } = s.value;+ assert.equal(result.ok, true, JSON.stringify(result.errors));+ assert.deepEqual({ errors: result.errors, skipped: result.skipped }, { errors: [], skipped: [] });+ assert.deepEqual(s.writes, TEARDOWN_WRITES);+ // The environment is back to where it started, but for the publisher the build made for the prefix: teardown deletes the solution and+ // never a publisher, which other solutions may share. Only THAT row is set aside — by its identity, captured after the build — so a+ // publisher the environment had before that went missing would still fail here.+ assert.equal(run.builtPublisher.length, 1);+ assert.match(run.builtPublisher[0], / contosopublisher$/);+ const publishers = run.afterTeardown.rows.publishers;+ assert.deepEqual(publishers.filter((p) => !run.seed.rows.publishers.includes(p)), run.builtPublisher, 'the one row left that the environment did not have is the build\'s publisher');+ assert.deepEqual({ ...run.afterTeardown, rows: { ...run.afterTeardown.rows, publishers: publishers.filter((p) => !run.builtPublisher.includes(p)) } }, run.seed, 'every table, column, relationship, option set, row, solution component, link and page the build made is gone, and nothing the environment had before is missing');+ // ...and every artifact the environment had before holds exactly what it held: saved and published layers, metadata, page files.+ assert.deepEqual(diffContents(run.seedContents, run.contents.teardown, { added: false }), [], 'nothing the environment had before was touched');+ withinBudget(s, 'teardown');+});++// ====================================================================================================================================+// DEFECTS the matrix found, kept as tests that state the right behaviour. A defect found later is added the same way: skipped while it+// is open, and when it is fixed the `skip` goes, and so does its step from expectedDownload above.++// Fixed: a File or Image column reports AttributeType "Virtual", which the download's type map never matched, so both were left out of+// every download without a word. The download now types them by their AttributeTypeName (FileType / ImageType) and keeps the size.+test('lifecycle matrix: a download keeps the File and Image columns it reads', async () => {+ const run = await lifecycle();+ const project = stageOf(run, 'download').value.spec.entities.find((e) => e.schemaName === 'contoso_project');+ assert.deepEqual(project.columns.filter((c) => ['File', 'Image'].includes(c.type)).map((c) => c.schemaName), ['contoso_contract', 'contoso_logo']);+});++// Fixed: a plain plural was left out of every download as "derivable", but "Tag Catalog" is not "Tags", so a rebuild into another+// environment named the table differently. The download now leaves out only the plural the build's own derivation would write.+test('lifecycle matrix: a download keeps a plural that is not the display name plus "s"', async () => {+ const run = await lifecycle();+ const tag = stageOf(run, 'download').value.spec.entities.find((e) => e.schemaName === 'contoso_tag');+ assert.equal(tag.pluralName, 'Tag Catalog');+});diff --git a/plugins/model-apps/scripts/tests/lifecycle-recovery-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-recovery-real-bundle.test.jsnew file mode 100644index 000000000..d36cf0f48--- /dev/null+++ b/plugins/model-apps/scripts/tests/lifecycle-recovery-real-bundle.test.js@@ -0,0 +1,255 @@+'use strict';+// RECOVERY PINS around the lifecycle matrix (lifecycle-matrix-real-bundle.test.js): what a maker relies on when the environment and+// the spec part ways — over the same kitchen-sink spec, the REAL vendored SDK and the stateful fake Dataverse+// (helpers/fake-lifecycle-org.js, helpers/lifecycle-harness.js):+//+// verify catches drift what a maker deleted in Maker is named by verify, and a rebuild puts it back+// a failed build resumes a build that stops part way, run again, ends as a clean build ends: nothing missing, nothing twice+// a failed teardown resumes a teardown that stops part way, run again, deletes the rest and leaves everything else as it was+// teardown never loses data a teardown of a DOWNLOADED spec keeps every table, column, relationship, global choice and row+// teardown is re-runnable a teardown of what is already gone changes nothing and reports no error+//+// Two environments serve the tests, each walked in the order a maker meets these steps; as in the matrix, a step that throws is+// recorded and fails its own test (a later test on the same environment then fails after it):+// CLEAN built -> a maker deletes six artifacts in Maker -> verify -> rebuild | download -> teardown of the downloaded spec ->+// teardown of the authored spec -> a teardown of what is gone+// FAULTED a build refused part way -> the build run again | a teardown refused part way -> the teardown run again+// A failure is provoked only by refusing a request for this test's own app, in front of the fake: the refused request never reaches+// the fake, so the environment holds what it would after a real refusal. Whatever a step does, everything the environment held before+// the build is held to what it held — by identity and by content (assertBackToSeed, diffContents).+const test = require('node:test');+const assert = require('node:assert/strict');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { kitchenSinkSpec, createLifecycleHarness, seedForeignWork, deployedFeatures, diffContents, appUniqueName } = require('./helpers/lifecycle-harness.js');++const spec = kitchenSinkSpec();++// A fake environment with another maker's work in it, and a seam in front of its transport that refuses what `refuse` names.+async function environment() {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const faults = [];+ // A refusal is a Dataverse OData error the client does not retry — { "error": { "code", "message" } } with a 400 — so the step fails+ // as it would on a real refusal. It holds until it is lifted, whatever the step retries. The error shape:+ // https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#parse-errors-from-the-response+ const request = async (req) => {+ const where = decodeURIComponent(new URL(req.url).pathname);+ const fault = faults.find((f) => f.method === req.method && f.path.test(where));+ if (!fault) return org.request(req);+ fault.hits += 1;+ return { statusCode: 400, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error: { code: '0x80040216', message: fault.message } }) };+ };+ const refuse = (method, pathPattern, message) => {+ const fault = { method, path: pathPattern, message, hits: 0 };+ faults.push(fault);+ return { lift: () => { faults.splice(faults.indexOf(fault), 1); return fault.hits; } };+ };+ const harness = createLifecycleHarness({ ...org, request }, makeTempDir('lifecycle-recovery-'));+ return { org, harness, refuse, seed: org.inventory(), seedContents: org.contents() };+}+// The publisher a build made for the prefix: the publisher rows that were not there before it (captured right after the build).+const publishersMade = (env) => env.org.inventory().rows.publishers.filter((p) => !env.seed.rows.publishers.includes(p));++// What a maker does in Maker, sent to the fake as the Web API call Maker makes.+async function inMaker(org, method, where) {+ const res = await org.request({ url: `${org.API}${where}`, method, headers: {} });+ assert.ok(res.statusCode < 300, `${method} ${where} answered ${res.statusCode}: ${res.body}`);+}++const buttonsOf = (org) => org.find('appactions', () => true).map((a) => a.buttonlabeltext).sort();++// CLEAN: the kitchen sink built, and what it deployed (the reference a recovered environment must end equal to); then a maker deletes+// a view, a Quick Create form, a button, the persona's role, the N:N relationship and the generative page; verify; the rebuild.+let cleanP;+const clean = () => cleanP || (cleanP = (async () => {+ const env = await environment();+ const { org, harness } = env;+ const build = await harness.build(spec);+ assert.equal(build.result.ok, true, JSON.stringify(build.result.errors));+ env.builtPublisher = publishersMade(env);+ env.reference = deployedFeatures(org);+ env.buttons = buttonsOf(org);+ const one = (set, predicate) => { const rows = org.find(set, predicate); assert.equal(rows.length, 1, `one ${set} row matches`); return rows[0]; };+ await inMaker(org, 'DELETE', `/savedqueries(${one('savedqueries', (v) => v.name === 'My Open Tasks').savedqueryid})`);+ await inMaker(org, 'DELETE', `/systemforms(${one('systemforms', (f) => f.name === 'Task Quick Create').formid})`);+ await inMaker(org, 'DELETE', `/appactions(${one('appactions', (a) => a.buttonlabeltext === 'Escalate').appactionid})`);+ await inMaker(org, 'DELETE', `/roles(${one('roles', (r) => r.name === 'Kitchen Planner').roleid})`);+ await inMaker(org, 'DELETE', `/RelationshipDefinitions(${org.metadata.relationships.get('contoso_tag_contoso_task').MetadataId})`);+ // The page goes with its conversation, as the plugin's own teardown deletes it: a project delete does not cascade to the messages, and+ // whether Maker's page delete takes them too is not modelled — left behind, they would be two rows no teardown names.+ const page = [...org.pageServer.state.projects.values()].find((p) => p.name === 'Kitchen Page');+ for (const message of org.pageServer.messagesOf(page.id)) await inMaker(org, 'DELETE', `/agentconversationmessages(${message.id})`);+ await inMaker(org, 'DELETE', `/uxagentprojects(${page.id})`);+ env.drifted = await harness.measure(() => harness.verify(spec));+ env.rebuild = await harness.measure(() => harness.build(spec));+ env.afterRebuild = deployedFeatures(org);+ env.afterRebuildContents = org.contents();+ return env;+})());++// FAULTED: the build is refused its first form create — the solution, the data model, sample data, web resources, views and the chart+// are in by then — and run again once the refusal is lifted.+let faultedP;+const faulted = () => faultedP || (faultedP = (async () => {+ const env = await environment();+ const { harness, refuse } = env;+ const refusal = refuse('POST', /\/systemforms$/, 'An unexpected error occurred.');+ env.failedBuild = await harness.measure(() => harness.build(spec));+ env.failedBuild.hits = refusal.lift();+ env.resumedBuild = await harness.measure(() => harness.build(spec));+ env.builtPublisher = publishersMade(env);+ env.afterResume = deployedFeatures(env.org);+ env.afterResumeContents = env.org.contents();+ return env;+})());++// A measured step ran: it did not throw, and every request it sent is one the fake models.+const ran = (step, label) => {+ assert.ok(step, `${label} ran`);+ if (step.error) throw step.error;+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);+ return step;+};++// The environment is as the seed left it, but for the publisher the build made for the prefix (teardown never deletes a publisher) —+// set aside by its identity, so a publisher the environment had before that went missing still fails. By identity, nothing the build+// made is left and nothing the environment had is missing; by content, everything the environment had holds exactly what it held.+function assertBackToSeed(env) {+ const { org, seed } = env;+ const now = org.inventory();+ assert.equal(env.builtPublisher.length, 1);+ assert.deepEqual(now.rows.publishers.filter((p) => !seed.rows.publishers.includes(p)), env.builtPublisher, 'the one row left that the environment did not have is the build\'s publisher');+ assert.deepEqual({ ...now, rows: { ...now.rows, publishers: now.rows.publishers.filter((p) => !env.builtPublisher.includes(p)) } }, seed, 'every other row is as it was before the build: no more, no fewer');+ assert.deepEqual(diffContents(env.seedContents, org.contents(), { added: false }), [], 'and every one of them holds exactly what it held');+}++// ====================================================================================================================================+// THE PINNED VALUES — one per step. A value that moves on purpose is a one-line change here.++// What verify reports for the six deletions, in its order. The deleted "Escalate" button is NOT among them: verify checks one command+// bar per table (verify-spec.js, "Commands (existence)"), and the table still has the flyout.+const DRIFT_MISSING = [+ 'view contoso_task.My Open Tasks',+ 'form Task Quick Create',+ 'relationship contoso_tag_contoso_task',+ 'page Kitchen Page',+ 'role Kitchen Planner (persona security role not found (or its business unit could not be resolved))',+];++// The refused build stops at the phase that failed and says which, and why (the CLI prints it and exits non-zero)...+const FAILED_BUILD_ERROR = 'forms failed: HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.0/systemforms?$select=formid: An unexpected error occurred.';+// ...having written every phase before it, whole.+const FAILED_BUILD_WRITES = {+ 'POST publishers': 1, 'POST solutions': 1, // solution+ 'POST GlobalOptionSetDefinitions': 1, 'POST EntityDefinitions': 3, 'POST EntityDefinitions/Attributes': 17, 'POST InsertStatusValue': 1, // data model+ 'POST EntityDefinitions/Keys': 1, 'POST CreateCustomerRelationships': 1, 'POST RelationshipDefinitions': 3, 'PUT EntityDefinitions': 2,+ 'POST contoso_projects/Microsoft.Dynamics.CRM.CreateMultiple': 1, 'POST contoso_tasks/Microsoft.Dynamics.CRM.CreateMultiple': 1, // sample data+ 'POST webresourceset': 2, // web resources: the script and the table icon+ 'POST savedqueries': 3, 'PATCH savedqueries': 4, // views, and the default-view enrichment+ 'POST savedqueryvisualizations': 1, // the chart+ 'POST AddSolutionComponent': 6,+ 'POST PublishXml': 4,+};++// The refused teardown: one table's delete fails, the teardown goes on as far as it can, keeps the solution for the re-run, and says so.+const FAILED_TEARDOWN_LINES = [+ "[18/27] ✗ table contoso_tag — HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='contoso_tag'): The Entity component cannot be deleted because it is referenced by 1 other component.",+ '✗ teardown finished with errors — 25 deleted, 0 not found, 1 failed, 1 kept (27 steps)',+];+// The teardown run again: the table it could not delete and the solution it kept. A table or global choice is deleted by name, so the+// two tables and the global choice that are already gone are sent again and answered 404, which the teardown reads as "already gone".+const RESUMED_TEARDOWN_WRITES = { 'DELETE EntityDefinitions': 3, 'DELETE GlobalOptionSetDefinitions': 1, 'DELETE solutions': 1 };++// What a teardown of the downloaded spec deletes: the app and what is the app's own. Its tables, relationships and global choice are+// marked existing and kept; its forms, views, charts and commands are not in a downloaded spec, so they are kept too.+const DOWNLOADED_TEARDOWN_WRITES = {+ 'DELETE appmodules': 1, // the app and its sitemap+ 'DELETE sitemaps': 1,+ 'DELETE uxagentprojects': 1, // the page, and its conversation+ 'DELETE agentconversationmessages': 2,+ 'DELETE systemforms': 1, // the dashboard, which the download pins by its id+ 'DELETE webresourceset': 2, // the generated app icon and the page manifest+ // The solution: the download names the app's own unmanaged solution "for a later clean teardown" (docs/app-builder-capabilities.md,+ // "Edit flow"). Deleting an unmanaged solution deletes the container only; every component it held stays in the environment.+ 'DELETE solutions': 1,+};++// A teardown of what is gone. This overstates what it did: a default-view reset, a relationship, a table or a global choice that was+// already gone is reported as deleted (each step is idempotent and ends ✓). Once that is fixed this reads "0 deleted, 27 not found".+const AGAIN_SUMMARY = '✓ teardown complete — 9 deleted, 18 not found, 0 failed (27 steps)';++// ====================================================================================================================================++test('lifecycle recovery: verify names every artifact a maker deleted in Maker, and a rebuild puts it back', async () => {+ const env = await clean();+ const drifted = ran(env.drifted, 'verify of the drifted app');+ assert.equal(drifted.value.ok, false);+ assert.deepEqual(drifted.value.missing.map((m) => `${m.kind} ${m.name}${m.detail ? ` (${m.detail})` : ''}`), DRIFT_MISSING);+ const rebuild = ran(env.rebuild, 'the rebuild of the drifted app');+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));+ assert.deepEqual(rebuild.value.result.verify && { ok: rebuild.value.result.verify.ok, missing: rebuild.value.result.verify.missing }, { ok: true, missing: [] });+ // Documented: the command phase creates a table's command bar only when the table has none ("Button edits are not applied on+ // rebuild", references/app-spec-schema-advanced.md), so the deleted button stays deleted, and the build says it reused the bar.+ assert.deepEqual(buttonsOf(env.org), env.buttons.filter((label) => label !== 'Escalate'));+ assert.ok(rebuild.value.log.some((line) => line.includes("command bar for contoso_project (exists — reuse; button edits aren't applied on rebuild, recreate to change)")));+ assert.deepEqual({ ...env.afterRebuild, commands: env.reference.commands }, env.reference, 'every other deleted artifact is back, once, as the clean build made it');+ assert.deepEqual(diffContents(env.seedContents, env.afterRebuildContents, { added: false }), [], 'and nothing the environment had before the build was touched');+});++test('lifecycle recovery: a build that fails part way, run again, ends as a clean build ends', async () => {+ const env = await faulted();+ const failed = env.failedBuild;+ assert.ok(failed.hits > 0, 'the refusal was hit');+ assert.deepEqual(failed.unexpected, []);+ assert.equal(failed.error && failed.error.message, FAILED_BUILD_ERROR);+ assert.deepEqual(failed.writes, FAILED_BUILD_WRITES);+ const resumed = ran(env.resumedBuild, 'the build run again');+ assert.equal(resumed.value.result.ok, true, JSON.stringify(resumed.value.result.errors));+ assert.deepEqual(env.afterResume, (await clean()).reference, 'nothing is missing, nothing is made twice, nothing is left unpublished');+ assert.deepEqual(diffContents(env.seedContents, env.afterResumeContents, { added: false }), [], 'and nothing the environment had before was touched');+});++test('lifecycle recovery: a teardown that fails part way, run again, deletes the rest and nothing else', async () => {+ const env = await faulted();+ const { harness, refuse } = env;+ const refusal = refuse('DELETE', /EntityDefinitions\(LogicalName='contoso_tag'\)$/, 'The Entity component cannot be deleted because it is referenced by 1 other component.');+ const failed = ran(await harness.measure(() => harness.teardown(spec)), 'the refused teardown');+ assert.ok(refusal.lift() > 0, 'the refusal was hit');+ assert.equal(failed.value.result.ok, false);+ assert.deepEqual(failed.value.log.filter((line) => /✗/.test(line)).map((line) => line.trim()), FAILED_TEARDOWN_LINES);+ const resumed = ran(await harness.measure(() => harness.teardown(spec)), 'the teardown run again');+ assert.equal(resumed.value.result.ok, true, JSON.stringify(resumed.value.result.errors));+ assert.deepEqual(resumed.writes, RESUMED_TEARDOWN_WRITES);+ assertBackToSeed(env);+});++test('lifecycle recovery: a teardown of the downloaded spec keeps every table, column, relationship, global choice and row', async () => {+ const env = await clean();+ const { org, harness } = env;+ const dir = path.join(makeTempDir('lifecycle-recovery-download-'), 'app');+ const download = ran(await harness.measure(() => harness.download(appUniqueName(spec), dir)), 'the download');+ const before = deployedFeatures(org);+ const beforeContents = org.contents();+ const teardown = ran(await harness.measure(() => harness.teardown(download.value.spec, { workspace: path.join(dir, '.maker-workspace') })), 'the teardown of the downloaded spec');+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));+ assert.deepEqual(teardown.writes, DOWNLOADED_TEARDOWN_WRITES);+ const after = deployedFeatures(org);+ for (const kept of ['tables', 'relationships', 'optionSets', 'records', 'views', 'charts', 'forms', 'commands']) assert.deepEqual(after[kept], before[kept], `the ${kept} are kept`);+ // ...and what it kept, it kept whole: no artifact that is still there holds anything else (a column, an option, a row's value, a view's+ // XML), whatever the teardown deleted around it.+ assert.deepEqual(diffContents(beforeContents, org.contents(), { added: false }).filter((line) => !line.startsWith('gone: ')), []);+ // The authored spec's teardown then deletes the rest...+ const rest = ran(await harness.measure(() => harness.teardown(spec)), 'the teardown of the authored spec');+ assert.equal(rest.value.result.ok, true, JSON.stringify(rest.value.result.errors));+ assertBackToSeed(env);+ // ...and a teardown of what is gone changes nothing: what is resolved by a query is skipped when the query finds nothing, and a table+ // or global choice is deleted by name, the platform's 404 read as "already gone".+ const again = ran(await harness.measure(() => harness.teardown(spec)), 'the teardown of what is gone');+ assert.equal(again.value.result.ok, true, JSON.stringify(again.value.result.errors));+ assert.deepEqual(again.writes, { 'DELETE EntityDefinitions': 3, 'DELETE GlobalOptionSetDefinitions': 1 });+ assert.deepEqual(org.since(again.mark).filter((r) => r.method !== 'GET').map((r) => r.status), [404, 404, 404, 404]);+ assertBackToSeed(env);+ assert.deepEqual(again.value.log.filter((line) => /teardown complete|finished with errors/.test(line)).map((line) => line.trim()), [AGAIN_SUMMARY]);+});diff --git a/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.jsnew file mode 100644index 000000000..acb6047ac--- /dev/null+++ b/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js@@ -0,0 +1,180 @@+'use strict';+// FOCUSED PINS around the lifecycle matrix (lifecycle-matrix-real-bundle.test.js): the paths a maker takes besides build -> rebuild ->+// download -> verify -> teardown, each over the same kitchen-sink spec, the REAL vendored SDK and the stateful fake Dataverse+// (helpers/fake-lifecycle-org.js, helpers/lifecycle-harness.js). Each pins a property whose silent loss would hurt a maker:+//+// a preview never writes a dry run of the build — on an empty environment and on a built one — and a teardown without+// --apply send no write at all, and the teardown preview lists what --apply would delete+// the download is stable two downloads of an unchanged app write the same spec, byte for byte+// --publish means what it says a rebuild without it sends none of the bulk publishes it gates, and leaves the rest unpublished+// the edit flow is safe the downloaded spec rebuilds in the same environment without creating or deleting anything, and both+// it and the authored spec verify+// (lifecycle-recovery-real-bundle.test.js pins the rest: drift, a failed build or teardown run again, a teardown of a downloaded spec.)+//+// One environment is built once and the tests use it in order — the ones that only read first, then the rebuilds.+const test = require('node:test');+const assert = require('node:assert/strict');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { kitchenSinkSpec, createLifecycleHarness, seedForeignWork, publishesOf, diffContents, appUniqueName } = require('./helpers/lifecycle-harness.js');++const spec = kitchenSinkSpec();+const APP = appUniqueName(spec);++// The environment the scenarios share: built once, with another maker's work in it.+let builtP;+const built = () => builtP || (builtP = (async () => {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const seedContents = org.contents();+ const root = makeTempDir('lifecycle-scenarios-');+ const harness = createLifecycleHarness(org, root);+ const build = await harness.measure(() => harness.build(spec));+ if (build.error) throw build.error;+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));+ return { org, root, harness, seedContents };+})());++// Every request a measured step sent was one the fake models, and the step did not throw.+const clean = (step, label) => {+ if (step.error) throw step.error;+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);+ return step;+};++// ====================================================================================================================================+// THE PINNED VALUES — one per scenario. A value that moves on purpose is a one-line change here.++// What teardown --apply would delete for the kitchen sink, in the order it would: the plan a maker approves (a page id is <id>).+const TEARDOWN_PLAN = [+ 'app module "Kitchen Sink"',+ 'generative pages proven for this app: <id> "Kitchen Page" (would delete)',+ 'dashboard "Kitchen Overview"',+ 'command bar for contoso_project',+ 'form "Project" (contoso_project)',+ 'form "Task Quick Create" (contoso_task)',+ 'form "Task" (contoso_task)',+ 'form "Project Card" (contoso_project)',+ 'security role "Kitchen Planner"',+ 'chart "Projects by Priority" (contoso_project)',+ 'view "Open Projects" (contoso_project)',+ 'view "Open Tasks" (contoso_task)',+ 'view "My Open Tasks" (contoso_task)',+ 'reset default views for contoso_project (drop parent lookups)',+ 'reset default views for contoso_task (drop parent lookups)',+ 'relationship contoso_project_contoso_task',+ 'relationship contoso_tag_contoso_task',+ 'table contoso_tag',+ 'table contoso_task',+ 'table contoso_project',+ 'relationship contoso_project_contoso_project', // a self-referencing relationship goes with its table; this step finds it gone+ 'web resource contoso_project.js',+ 'web resource contoso_projecticon.svg',+ 'web resource contoso_kitchensink_icon (generated app icon)',+ 'web resource contoso_kitchensink_pagemanifest (page manifest)',+ 'global choice contoso_stage',+ 'solution ContosoKitchen',+];++// A rebuild of the unchanged spec WITHOUT --publish. The bulk publishes are what --publish gates (skills/app-builder/SKILL.md: the+// tables published together once before the app, and the publish phase); without it each step publishes what it re-pushed, table by+// table — measured, not derived: 11 publishes where the --publish rebuild of the matrix sends 4, each a PublishXml that takes seconds+// on a real environment. The two tables' views and forms are pushed concurrently, so the publishes are counted, not ordered.+const UNPUBLISHED_REBUILD_PUBLISHES = {+ contoso_project: 5, // the table icon set again; the view "Open Projects" pushed again unchanged (no write, but a publish); the+ // default-view enrichment; the forms "Project" and "Project Card", likewise unchanged+ contoso_task: 5, // the views "Open Tasks" and "My Open Tasks"; the default-view enrichment; the forms "Task Quick Create" and "Task"+ app: 1, // the app after the sitemap finalize, the last publish+};+// ...and what it leaves saved but not published, for the maker's own publish: the two Main forms whose default flag and security roles+// were written again, and the new look setting saved after the app's publish.+const UNPUBLISHED_AFTER = ['appsettings <id>', 'systemforms Project', 'systemforms Task'];++// The rebuild of the downloaded spec. Its tables are existing and it carries no form, view, chart or command, so nothing of the data+// model or the record UI is written; what is written is the app's own, as on any rebuild of an existing app.+const DOWNLOADED_REBUILD_WRITES = {+ 'PATCH webresourceset': 1, // the page manifest: the downloaded page's source is pages/<pageId>/page.tsx, where the authored one was KitchenPage.tsx+ 'PATCH sitemaps': 1, // the sitemap of an existing app is rewritten by the pages finalize, byte for byte (as in the matrix's rebuild)+ 'POST AddAppComponents': 1, // ...and the push re-adds the app's components+ 'POST SaveSettingValue': 1, // the new look setting is saved again+ 'POST PublishXml': 5, // the tables before the app's publish, the page, the manifest, the app after the finalize, and the publish phase+};++// ====================================================================================================================================++test('lifecycle scenarios: a dry run of the build writes nothing, against an empty environment and against the built one', async () => {+ // An empty environment: everything would be created, nothing may be.+ const emptyOrg = createLifecycleOrg();+ const empty = createLifecycleHarness(emptyOrg, makeTempDir('lifecycle-scenarios-empty-'));+ const before = emptyOrg.contents();+ const fresh = clean(await empty.measure(() => empty.build(spec, { apply: false })), 'the dry run on an empty environment');+ assert.equal(fresh.value.result.ok, true, JSON.stringify(fresh.value.result.errors));+ assert.equal(fresh.value.result.dryRun, true);+ assert.deepEqual(fresh.writes, {}, 'a preview sends no write');+ assert.deepEqual(diffContents(before, emptyOrg.contents()), [], 'and the environment is as it was, artifact by artifact');+ // The built environment: everything would be reused, and nothing may be written either.+ const { org, harness } = await built();+ const held = org.contents();+ const again = clean(await harness.measure(() => harness.build(spec, { apply: false })), 'the dry run on the built environment');+ assert.equal(again.value.result.ok, true, JSON.stringify(again.value.result.errors));+ assert.deepEqual(again.writes, {});+ assert.deepEqual(diffContents(held, org.contents()), []);+ // The live plan tells the two apart: on the empty environment nothing is reused, on the built one the tables and the app are.+ const stateOf = (r, label) => (r.value.result.planItems.find((p) => p.label === label) || {}).state;+ assert.equal(stateOf(fresh, 'app module "Kitchen Sink" + sitemap'), 'create');+ assert.equal(stateOf(again, 'app module "Kitchen Sink" + sitemap'), 'reuse');+});++test('lifecycle scenarios: a teardown without --apply writes nothing and lists every artifact the build made', async () => {+ const { org, harness } = await built();+ const held = org.contents();+ const plan = clean(await harness.measure(() => harness.teardown(spec, { apply: false })), 'the teardown preview');+ assert.equal(plan.value.result.dryRun, true);+ assert.deepEqual(plan.writes, {}, 'a teardown preview sends no write');+ assert.deepEqual(diffContents(held, org.contents()), [], 'and changes nothing');+ assert.deepEqual(plan.value.result.plan.map((line) => line.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '<id>')), TEARDOWN_PLAN);+});++test('lifecycle scenarios: two downloads of an unchanged app write the same spec', async () => {+ const { org, harness, root } = await built();+ const held = org.contents();+ const first = clean(await harness.measure(() => harness.download(APP, path.join(root, 'download-a'))), 'the first download');+ const second = clean(await harness.measure(() => harness.download(APP, path.join(root, 'download-b'))), 'the second download');+ assert.equal(first.value.emitted.ok, true, JSON.stringify(first.value.emitted));+ assert.equal(second.value.text, first.value.text, 'the spec is the same, byte for byte');+ // And downloading again into the folder that holds the first spec rewrites it unchanged (the page keys it gave are kept).+ const third = clean(await harness.measure(() => harness.download(APP, path.join(root, 'download-a'))), 'the download over the first');+ assert.equal(third.value.text, first.value.text);+ assert.deepEqual(diffContents(held, org.contents()), [], 'three downloads change nothing in the environment');+});++test('lifecycle scenarios: a rebuild without --publish skips the bulk publishes, and leaves the rest unpublished', async () => {+ const { org, harness, seedContents } = await built();+ const held = org.inventory();+ const rebuild = clean(await harness.measure(() => harness.build(spec, { publish: false })), 'the rebuild without --publish');+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));+ assert.deepEqual(org.inventory(), held);+ assert.deepEqual(diffContents(seedContents, org.contents(), { added: false }), [], 'nothing the environment had before the build was touched, or published');+ const publishes = publishesOf(org, rebuild);+ assert.deepEqual(publishes.reduce((counts, name) => ({ ...counts, [name]: (counts[name] || 0) + 1 }), {}), UNPUBLISHED_REBUILD_PUBLISHES);+ assert.equal(publishes[publishes.length - 1], 'app');+ assert.deepEqual(rebuild.unpublished.map((row) => row.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '<id>')).sort(), UNPUBLISHED_AFTER);+});++test('lifecycle scenarios: the downloaded spec rebuilds in the same environment without creating or deleting anything, and verifies', async () => {+ const { org, harness, root, seedContents } = await built();+ const dir = path.join(root, 'download-a');+ const downloaded = (await harness.download(APP, dir)).spec;+ const held = org.inventory();+ const rebuild = clean(await harness.measure(() => harness.build(downloaded, { appFolder: dir, workspace: path.join(dir, '.maker-workspace') })), 'the rebuild of the downloaded spec');+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));+ assert.deepEqual(org.inventory(), held, 'nothing is created or deleted: the app keeps every form, view, chart, command and page the download did not carry');+ assert.deepEqual(diffContents(seedContents, org.contents(), { added: false }), [], 'nothing the environment had before the build was touched');+ assert.deepEqual(rebuild.writes, DOWNLOADED_REBUILD_WRITES);+ const verified = clean(await harness.measure(() => harness.verify(downloaded, { workspace: path.join(dir, '.maker-workspace') })), 'verify of the downloaded spec');+ assert.deepEqual({ ok: verified.value.ok, missing: verified.value.missing }, { ok: true, missing: [] });+ // The authored spec still verifies too: the rebuild of the downloaded one took nothing away.+ const original = clean(await harness.measure(() => harness.verify(spec)), 'verify of the authored spec');+ assert.deepEqual({ ok: original.value.ok, missing: original.value.missing }, { ok: true, missing: [] });+});diff --git a/plugins/model-apps/scripts/tests/maker-sdk.test.js b/plugins/model-apps/scripts/tests/maker-sdk.test.jsindex ae68a303b..65198219b 100644--- a/plugins/model-apps/scripts/tests/maker-sdk.test.js+++ b/plugins/model-apps/scripts/tests/maker-sdk.test.js@@ -70,6 +70,33 @@ test('a powerAppsServiceClient the caller names wins, as an explicit compiler doassert.strictEqual(create({ powerAppsServiceClient: own, connectivity: true }).powerAppsServiceClient, own);});+// --- the workspace storage: every file the SDK writes is written without the access tokens the process obtained (lib/output-redaction.js) ----------------------++test('the workspaceStorage a caller names is handed to the SDK guarded — it is the storage in everything but the text it is asked to write — and a caller that names none is given none', async () => {+ const { withVendoredCompiler } = require('../lib/maker-sdk.js');+ const create = withVendoredCompiler((options) => options);+ const written = [];+ const storage = {+ root: '/workspace',+ getRoot() { return this.root; },+ pathFor(key) { return `${this.root}/${key.join('/')}`; },+ async writeTextAtomic(key, text) { written.push([key, text]); },+ async readText() { return null; },+ async deleteFile() {},+ async deleteByPrefix() {},+ };+ const made = create({ instanceUrl: ORG, workspaceStorage: storage });+ assert.notStrictEqual(made.workspaceStorage, storage, 'a wrapper');+ assert.strictEqual(Object.getPrototypeOf(made.workspaceStorage), storage, 'with the storage for its prototype: its folder, its paths and every other member are its own');+ assert.strictEqual(made.workspaceStorage.getRoot(), '/workspace');+ assert.strictEqual(made.workspaceStorage.pathFor(['forms', 'one.json']), '/workspace/forms/one.json');+ assert.strictEqual(await made.workspaceStorage.readText(['forms', 'one.json']), null);+ await made.workspaceStorage.writeTextAtomic(['forms', 'one.json'], '{"a":1}');+ assert.deepStrictEqual(written, [[['forms', 'one.json'], '{"a":1}']], 'a text that holds no token is written as it is');+ assert.deepStrictEqual(Object.keys(create({ instanceUrl: ORG })).sort(), ['instanceUrl', 'typescript'], 'none named, none given');+ assert.strictEqual(create({ instanceUrl: ORG, workspaceStorage: null }).workspaceStorage, null, 'and one that is no storage is what it was');+});+test('the client module is loaded only when connectivity is asked for — an instance that reads no connections pays nothing', () => {const { spawnSync } = require('node:child_process');const probe = [diff --git a/plugins/model-apps/scripts/tests/output-redaction.test.js b/plugins/model-apps/scripts/tests/output-redaction.test.jsnew file mode 100644index 000000000..09086454f--- /dev/null+++ b/plugins/model-apps/scripts/tests/output-redaction.test.js@@ -0,0 +1,706 @@+'use strict';+// lib/output-redaction.js — the access tokens a process obtained, kept out of everything it writes.+//+// The matcher reads a text as it SPELLS a token (a character itself or a JSON escape of it, with folds between the characters), so these tests hold it against the spellings a service's diagnostic can take, against a plain+// reference that shares none of its code, and against the cost of a large text. The registry, the guard on a stream and the guard on the SDK's workspace storage are held here too; what reaches a process's descriptors and files+// is read from a real process in tests/output-token-boundary.test.js, which is where a guard that is a replaced `process.stdout.write` can be measured.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const util = require('node:util');+const { spawnSync } = require('node:child_process');+const { redactTokens, needlesOf, guardStream, guardWorkspaceStorage, TOKEN_MARKER } = require('../lib/output-redaction.js');+const { scrub } = require('../lib/sdk-http-client.js');+const bundle = require('../vendor/cds-maker-sdk.cjs');+const { PARTS, TOKEN, SECRETS } = require('./helpers/synthetic-token.js');+const { leaksIn } = require('./helpers/token-leaks.js');+const { makeTempDir } = require('./helpers/temp-dirs.js');++const OTHER = ['otherHeaderPartNotARealCredentialAAA', 'otherPayloadPartNotARealCredentialBBB', 'otherSignaturePartNotARealCredentialC'].join('.');+const MARK = '<token>';+const unicode = (char, upper = false) => { const hex = char.charCodeAt(0).toString(16).padStart(4, '0'); return `\\u${upper ? hex.toUpperCase() : hex}`; };++// ── The matcher: a token as a text spells it ───────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('a token is taken out wherever the text has it, whole or by a part of 24 characters or more — exactly what the one scrubber does for a text that spells it plainly', () => {+ assert.equal(redactTokens(`Rejected bearer ${TOKEN} for this write`, [TOKEN]), `Rejected bearer ${MARK} for this write`);+ for (const part of PARTS) assert.equal(redactTokens(`the part ${part} is not valid`, [TOKEN]), `the part ${MARK} is not valid`, part);+ assert.equal(redactTokens(`${TOKEN} and ${TOKEN}`, [TOKEN]), `${MARK} and ${MARK}`);+ assert.equal(redactTokens(`a ${PARTS[0]}.${PARTS[2]} b`, [TOKEN]), `a ${MARK}.${MARK} b`);+ // A part shorter than 24 characters would be taken out of ordinary words, so it is left alone, as the scrubber leaves it.+ const short = 'aaa.bbb.ccc-and-a-longer-opaque-token-value';+ assert.equal(redactTokens('aaa and bbb and ccc', [short]), 'aaa and bbb and ccc');+ assert.equal(redactTokens(`bearer ${short}`, [short]), `bearer ${MARK}`);+ const texts = [`x ${TOKEN} y ${OTHER}`, `${PARTS[1]}${OTHER}`, `[${PARTS[0]}] (${OTHER.split('.')[2]})`, 'no secret here', ''];+ for (const text of texts) assert.equal(redactTokens(text, [TOKEN, OTHER]), [TOKEN, OTHER].reduce((out, token) => scrub(out, token), text), JSON.stringify(text));+});++test('a text that holds no token is the very string it was — whatever else it holds: line breaks, escapes, white space, quotes, a near miss', () => {+ // A near miss of the token spoils each of its parts (a part of 24 characters or more is taken out on its own, so one left whole would be).+ const nearMiss = PARTS.map((part) => `${part.slice(0, 12)}X${part.slice(13)}`).join('.');+ const texts = ['', 'plain', `line one\r\nline two \\u0073 \\/ \\n \\\\r ${nearMiss}`, ' \t\r\n ', PARTS[0].slice(0, 23), `${PARTS[0].slice(0, 23)}x${PARTS[0].slice(23)}`, [...PARTS[0]].reverse().join(''), "'a' +\n 'b' \"c\" `d`"];+ for (const text of texts) assert.equal(redactTokens(text, [TOKEN]), text, JSON.stringify(text));+ assert.equal(redactTokens('anything', []), 'anything', 'no token, nothing to take out');+ assert.equal(redactTokens(`bearer ${TOKEN}`, ['']), `bearer ${TOKEN}`, 'an empty token is no token');+ assert.equal(redactTokens(`bearer ${TOKEN}`, [undefined, null]), `bearer ${TOKEN}`);+ assert.equal(redactTokens(`bearer ${TOKEN}`, undefined), `bearer ${TOKEN}`);+ assert.equal(redactTokens(42, [TOKEN]), 42, 'what is not a text is returned as it is');+});++const FOLDS = ['\r\n ', '\n ', '\r\n\t', '\n', '\r\n', ' \r\n ', ' ', '\n\n', '\u00a0', '\u2028', '\\r\\n ', '\\n', '\\r\\n\\t', '\\\\r\\\\n ', '\\u000d\\u000a ', '\\u0020'];++test('a token folded onto several lines — the obsolete line folding of RFC 9112 §5.2, a column wrapped at any width, a fold a JSON body spells with escapes — is taken out from its first character to its last', () => {+ for (const fold of FOLDS) {+ for (const width of [1, 8, 76]) {+ const folded = TOKEN.match(new RegExp(`.{1,${width}}`, 'g')).join(fold);+ assert.equal(redactTokens(`Rejected bearer ${folded} for this write`, [TOKEN]), `Rejected bearer ${MARK} for this write`, `${JSON.stringify(fold)} every ${width}`);+ }+ }+ // Each part of the token can be folded on its own, and a text can hold both the folded spelling and the plain one.+ const foldedPart = PARTS[1].match(/.{1,5}/g).join('\r\n ');+ assert.equal(redactTokens(`one ${foldedPart} two ${PARTS[0]} three`, [TOKEN]), `one ${MARK} two ${MARK} three`);+ // The line break before and after the token is not part of it.+ assert.equal(redactTokens(`before\r\n${TOKEN.match(/.{1,9}/g).join('\r\n ')}\r\nafter`, [TOKEN]), `before\r\n${MARK}\r\nafter`);+});++test('a JSON escape in the text — \\u in either case, \\/, the white space \\r \\n \\t \\f, any number of backslashes before it — is read as the character it spells', () => {+ const initials = PARTS.map((part) => `${unicode(part[0])}${part.slice(1)}`).join('.');+ assert.equal(redactTokens(`The supplied literal spelling was ${initials}`, [TOKEN]), `The supplied literal spelling was ${MARK}`);+ for (const upper of [false, true]) {+ const everyThird = [...TOKEN].map((char, i) => (i % 3 === 0 ? unicode(char, upper) : char)).join('');+ assert.equal(redactTokens(`bearer ${everyThird}.`, [TOKEN]), `bearer ${MARK}.`, `upper ${upper}`);+ }+ assert.equal(redactTokens([...TOKEN].map((char) => unicode(char)).join(''), [TOKEN]), MARK);+ // A token that holds a slash (an opaque one can) may be written `\/`.+ const slashed = 'opaque/token/with/slashes/in/it/and-enough-characters';+ assert.equal(redactTokens(`bearer ${slashed.replace(/\//g, '\\/')}`, [slashed]), `bearer ${MARK}`);+ // JSON inside JSON doubles every backslash, and so on: a run of backslashes before an escape letter is one escape.+ for (const backslashes of ['\\', '\\\\', '\\\\\\\\', '\\\\\\']) {+ const nested = [...TOKEN].map((char, i) => (i % 4 === 0 ? `${backslashes}u${char.charCodeAt(0).toString(16).padStart(4, '0')}` : char) + (i % 9 === 0 ? `${backslashes}r${backslashes}n ` : '')).join('');+ assert.equal(redactTokens(`bearer ${nested} end`, [TOKEN]), `bearer ${MARK} end`, `${backslashes.length} backslash(es)`);+ }+ // Folds and escapes in one spelling.+ const both = [...TOKEN].map((char, i) => (i % 5 === 0 ? unicode(char) : char) + (i % 7 === 0 ? '\r\n ' : '')).join('');+ assert.equal(redactTokens(`bearer ${both} end`, [TOKEN]), `bearer ${MARK} end`);+ // A backslash that is not an escape of those is a stray between two characters, which is a fold like any other; a character that is not the token's own is not.+ assert.equal(redactTokens('C:\\path\\u12 and \\x', [TOKEN]), 'C:\\path\\u12 and \\x');+ assert.equal(redactTokens(`${PARTS[0].slice(0, 10)}\\x${PARTS[0].slice(10)}`, [TOKEN]), `${PARTS[0].slice(0, 10)}\\x${PARTS[0].slice(10)}`, 'an `x` inside a token breaks it: it is not the token');+});++test('a long string printed the way util.inspect prints it — the pieces joined by a quote, a plus sign and a line break — is the token too', () => {+ const folded = TOKEN.match(/.{1,8}/g).join('\r\n ');+ for (const [subject, cut] of [[{ error: { message: `Rejected bearer ${folded}` } }, true], [new Error(`top ${folded}`), false], [[`bearer ${folded}`], true], [`bearer ${folded}`, true]]) {+ const printed = util.inspect(subject, { depth: 6 });+ // An Error's own message is part of its stack, which is printed as it is; a string held by anything else is cut after each line break.+ assert.equal(/' \+\n/.test(printed), cut, `inspect ${cut ? 'cut' : 'did not cut'} the string: ${printed}`);+ assert.deepEqual(leaksIn(redactTokens(printed, [TOKEN]), SECRETS), [], printed);+ assert.ok(redactTokens(printed, [TOKEN]).includes(MARK));+ }+ // The same with the other quotes, and only exactly so: a quote that is followed by something else is a quote.+ for (const quote of ["'", '"', '`']) assert.equal(redactTokens(`a ${PARTS[0].slice(0, 20)}${quote} +\n ${quote}${PARTS[0].slice(20)} b`, [TOKEN]), `a ${MARK} b`, quote);+ assert.equal(redactTokens(`${PARTS[0].slice(0, 20)}' + 'x${PARTS[0].slice(20)}`, [TOKEN]), `${PARTS[0].slice(0, 20)}' + 'x${PARTS[0].slice(20)}`, 'a plus sign with no line break after it joins nothing');+ assert.equal(redactTokens(`${PARTS[0].slice(0, 20)}'\n'${PARTS[0].slice(20)}`, [TOKEN]), `${PARTS[0].slice(0, 20)}'\n'${PARTS[0].slice(20)}`, 'and neither does a line break with no plus sign');+ // A token that itself holds a quote reads it as a character.+ const quoted = "it's-an-opaque-token-with-a-quote-in-it";+ assert.equal(redactTokens(`bearer ${quoted} end`, [quoted]), `bearer ${MARK} end`);+ assert.equal(redactTokens(`bearer it's-an-opaque-token-with-a-quote-in-it' +\n 'x end`, [quoted]), `bearer ${MARK}' +\n 'x end`);+});++test('a long string printed the way util.inspect prints it IN COLOURS — each piece in its own colour codes, the codes between the quote, the plus sign and the line break — is the token too; the codes around it stay', () => {+ const folded = TOKEN.match(/.{1,8}/g).join('\r\n ');+ // A string value is cut after each line break; a key is not.+ const subjects = [+ [{ error: { message: `Rejected bearer ${folded}` } }, true],+ [[`bearer ${folded}`], true],+ [{ list: [{ note: `bearer ${folded}`, other: 'x' }], count: 2 }, true],+ [{ [`bearer ${folded}`]: 1 }, false],+ ];+ for (const [subject, cut] of subjects) {+ const printed = util.inspect(subject, { depth: 6, colors: true });+ assert.match(printed, /\u001b\[\d+m'/, 'in colours');+ assert.equal(/\u001b\[\d+m'[^'\n]*\\r\\n'\u001b\[39m \+\n\s*\u001b\[\d+m'/.test(printed), cut, `inspect ${cut ? 'cut the string and put each piece in colour codes' : 'did not cut it'}: ${JSON.stringify(printed)}`);+ const cleaned = redactTokens(printed, [TOKEN]);+ assert.deepEqual(leaksIn(cleaned, SECRETS), [], JSON.stringify(printed));+ assert.ok(cleaned.includes(MARK), 'the token stood where the marker is');+ assert.equal(util.stripVTControlCharacters(cleaned), redactTokens(util.stripVTControlCharacters(printed), [TOKEN]), 'the same text whether the colours are read away before or after');+ }+ // The string that held the token is still one coloured string: its opening code and its closing one are where they were.+ const one = util.inspect({ error: { message: `Rejected bearer ${folded}` }, other: 'x' }, { depth: 6, colors: true });+ assert.match(redactTokens(one, [TOKEN]), /message: \u001b\[32m'Rejected bearer <token>'\u001b\[39m\n \},\n other: \u001b\[32m'x'\u001b\[39m/);+});++test('a terminal colour code between two characters of a token is a fold — a well-formed one, and up to a bound; the codes before and after the token stay', () => {+ const inner = (i) => i % 5 === 2 && i !== 0 && i !== TOKEN.length - 1;+ const coloured = [...TOKEN].map((char, i) => (inner(i) ? `\u001b[${30 + (i % 8)};1m${char}\u001b[39m` : char)).join('');+ assert.equal(redactTokens(`\u001b[31mbearer ${coloured}\u001b[39m end`, [TOKEN]), `\u001b[31mbearer ${MARK}\u001b[39m end`);+ assert.equal(redactTokens(`bearer ${[...TOKEN].join('\u001b')} end`, [TOKEN]), `bearer ${MARK} end`, 'an ESC alone is a fold too');+ assert.equal(redactTokens(`bearer ${[...TOKEN].map((char) => `\u001b[0m${char}`).join('')} end`, [TOKEN]), `bearer \u001b[0m${MARK} end`, 'a code in front of every character');+ // Colour codes and the other folds, in one spelling.+ const last = TOKEN.length - 1;+ const mixed = [...TOKEN].map((char, i) => (i % 3 === 0 ? `\u001b[2m${char}\u001b[22m` : char) + (i < last && i % 7 === 0 ? '\r\n ' : '') + (i < last && i % 11 === 0 ? "'\u001b[39m +\n \u001b[32m'" : '')).join('');+ assert.equal(redactTokens(`bearer ${mixed} end`, [TOKEN]), `bearer \u001b[2m${MARK} end`, 'the code in front of the first character stays; the one right after it is inside the token');+ assert.equal(redactTokens(`bearer ${mixed} end`, [TOKEN]), reference(`bearer ${mixed} end`, [TOKEN]));+ // Only a code that is well-formed and short is read: anything else is characters, and a token that has them in it is not the token.+ const opaque = 'opaque-token-without-any-dot-in-it';+ const half = opaque.length >> 1;+ assert.equal(redactTokens(`bearer ${opaque.slice(0, half)}\u001b[1;2;3m${opaque.slice(half)} end`, [opaque]), `bearer ${MARK} end`, 'a short code');+ const tooLong = `\u001b[${'1;'.repeat(40)}m`;+ assert.equal(redactTokens(`bearer ${opaque.slice(0, half)}${tooLong}${opaque.slice(half)} end`, [opaque]), `bearer ${opaque.slice(0, half)}${tooLong}${opaque.slice(half)} end`, 'a code of more than 32 parameter bytes is not read');+ // A text with colours and no token is the very string it was.+ const plain = '\u001b[32mgreen\u001b[39m and \u001b[1;31mred\u001b[0m \u001b';+ assert.equal(redactTokens(plain, [TOKEN]), plain);+});++// The synthetic token with its signature starting with a letter that is also the second character of a JSON escape, as a diagnostic that has a literal backslash right before it spells it.+const LEADING = (first) => {+ const signature = `${first}SyntheticSignaturePartNotARealCredential`;+ return { signature, token: `${PARTS[0]}.${PARTS[1]}.${signature}` };+};++test('a backslash right before a part of the token — a literal one, which JSON writes `\\\\` — does not hide the letter after it: `\\n` is a line break or a backslash and an `n`, and both are read', () => {+ for (const first of ['n', 'r', 't', 'f', 'b', 'v', 'u', 'x', 'S', '0', '-', '_']) {+ const { signature, token } = LEADING(first);+ // The span of a letter that begins an escape takes the backslashes with it — it never leaves half of an escape (a JSON `\b` is one as much as `\n`); a stray before any other character stays where it was.+ const begins = 'nrtfbv'.includes(first);+ for (const run of ['\\', '\\\\', '\\\\\\', '\\\\\\\\']) {+ const text = `Rejected signature ${run}${signature} end`;+ assert.equal(redactTokens(text, [token]), `Rejected signature ${begins ? '' : run}${MARK} end`, JSON.stringify(text));+ }+ // As JSON writes a literal backslash: the message is still read, and the JSON is still JSON.+ const json = JSON.stringify({ message: `Rejected signature \\${signature}`, note: 'kept' });+ const cleaned = redactTokens(json, [token]);+ assert.deepEqual(JSON.parse(cleaned), { message: `Rejected signature ${begins ? '' : '\\'}${MARK}`, note: 'kept' }, `${first}: ${cleaned}`);+ }+ // A line break and then a signature that really starts with `n` is read as it is: the fold is the escape, and the `n` is the character.+ const { signature, token } = LEADING('n');+ assert.equal(redactTokens(JSON.stringify(`Rejected\n${signature}`), [token]), JSON.stringify(`Rejected\n${MARK}`));+ assert.deepEqual(JSON.parse(redactTokens(JSON.stringify({ message: `Rejected\n${signature}` }), [token])), { message: `Rejected\n${MARK}` });+ // `\u` and four hex digits, or `\x` and two (util.inspect's escape of a control character), is the character they spell or the characters themselves.+ for (const hexLike of ['u00a1SyntheticSignaturePartNotARealCredential', 'x41SyntheticSignaturePartNotARealCredential']) {+ const hexToken = `${PARTS[0]}.${PARTS[1]}.${hexLike}`;+ assert.equal(redactTokens(`Rejected signature \\${hexLike} end`, [hexToken]), `Rejected signature ${MARK} end`);+ assert.equal(redactTokens(`Rejected signature \\\\${hexLike} end`, [hexToken]), `Rejected signature ${MARK} end`);+ }+ assert.equal(redactTokens(`bearer ${[...TOKEN].map((char, i) => (i % 4 === 2 ? `\\x${char.charCodeAt(0).toString(16).padStart(2, '0')}` : char)).join('')} end`, [TOKEN]), `bearer ${MARK} end`, '`\\x..` is the character it spells');+});++test('a backslash between the characters of a token, before every one of them or before some, with folds and escapes and colour codes in the same token, is the token', () => {+ const before = (text, backslashes) => [...text].map((char) => backslashes + char).join('');+ for (const backslashes of ['\\', '\\\\', '\\\\\\']) {+ const text = `bearer ${before(TOKEN, backslashes)} end`;+ const cleaned = redactTokens(text, [TOKEN]);+ assert.deepEqual(leaksIn(cleaned, SECRETS), [], JSON.stringify(text));+ assert.equal(cleaned, reference(text, [TOKEN]));+ assert.ok(cleaned.includes(MARK));+ // Some, before the characters that begin an escape most of all.+ const some = `bearer ${[...TOKEN].map((char, i) => (i % 3 === 0 || 'nrtfu'.includes(char) ? backslashes : '') + char).join('')} end`;+ assert.deepEqual(leaksIn(redactTokens(some, [TOKEN]), SECRETS), []);+ assert.equal(redactTokens(some, [TOKEN]), reference(some, [TOKEN]));+ }+ // One token that has all of them: a stray backslash before a letter that begins an escape, a real escape and a fold in the same token.+ const last = TOKEN.length - 1;+ const mixed = [...TOKEN].map((char, i) => {+ let spelled = char;+ if (i % 4 === 1) spelled = unicode(char);+ if ('nrtfu'.includes(char) && i % 2 === 0) spelled = `\\${spelled}`;+ return spelled + (i < last && i % 6 === 5 ? '\\r\\n ' : '') + (i < last && i % 9 === 8 ? '\u001b[2m' : '');+ }).join('');+ assert.equal(redactTokens(`bearer ${mixed} end`, [TOKEN]), reference(`bearer ${mixed} end`, [TOKEN]));+ assert.equal(redactTokens(`bearer ${mixed} end`, [TOKEN]), `bearer ${MARK} end`);+});++test('the text around a token is kept as it was — multi-byte characters, surrogate pairs, the escapes and white space beside it — and spellings that only touch stay two markers, as plain ones do', () => {+ const text = `Accès refusé 日本語 🧪 \\u00e9 ${TOKEN.match(/.{1,10}/g).join('\n ')} — fin \\/ 🧪`;+ assert.equal(redactTokens(text, [TOKEN]), `Accès refusé 日本語 🧪 \\u00e9 ${MARK} — fin \\/ 🧪`);+ assert.equal(redactTokens(`${TOKEN}${TOKEN}`, [TOKEN]), `${MARK}${MARK}`, 'plain spellings are each taken out, as the one scrubber takes them');+ const folded = TOKEN.match(/.{1,10}/g).join('\n ');+ assert.equal(redactTokens(`${folded}${folded}`, [TOKEN]), `${MARK}${MARK}`, 'and so are folded ones');+ assert.equal(redactTokens(`${TOKEN} ${TOKEN}`, [TOKEN]), `${MARK} ${MARK}`);+ assert.equal(redactTokens(`${TOKEN}\n${OTHER}`, [TOKEN, OTHER]), `${MARK}\n${MARK}`);+ // White space inside a token is ignored wherever it is: a column wrapped with a plain space is the token too.+ assert.equal(redactTokens(`bearer ${PARTS[0].slice(0, 23)} ${PARTS[0].slice(23)} end`, [TOKEN]), `bearer ${MARK} end`);+ // A token that has white space of its own is looked for literally, as the one scrubber looks for it.+ assert.equal(redactTokens('bearer opaque token with spaces in it end', ['opaque token with spaces in it']), `bearer ${MARK} end`);+ assert.equal(redactTokens('bearer opaque\\token\\with\\backslashes\\in it end', ['opaque\\token\\with\\backslashes\\in it']), `bearer ${MARK} end`);+});++// ── JSON stays JSON ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// A small seeded generator, so a failure names a case that can be run again.+function generator(seed) {+ let state = seed >>> 0;+ const next = () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };+ return { next, int: (n) => Math.floor(next() * n), pick: (list) => list[Math.floor(next() * list.length)] };+}++// The VALUE of a JSON string, as the SDK holds it, with the token in it spelled in one of the ways a diagnostic spells it: whole, a part, folded, with `\uXXXX` left in the decoded text (a body that was JSON inside JSON), and with+// both. The file or the stream then holds what JSON.stringify makes of it — `\r\n` for a fold, `\\u0073` for the left-over escape.+function spelledValue(random) {+ const NOISE = ['a', ' ', '"', '\\', '\\\\', '/', 'u0041', '\n', '\r\n', '\t', 'é', '日', '🧪', "'", ' +\n', '{', ']', ',', ':'];+ const GAPS = ['', '', '', ' ', '\n', '\r\n ', '\t', '\\r\\n', '\\n ', ' '];+ const token = random.pick([TOKEN, OTHER, PARTS[1]]);+ const gapRate = random.next() * 0.5;+ const escapeRate = random.next() * 0.4;+ const spelled = [...token].map((char) => (random.next() < escapeRate ? unicode(char, random.next() < 0.5) : char) + (random.next() < gapRate ? random.pick(GAPS) : '')).join('');+ let around = '';+ for (let i = 0; i < random.int(6); i += 1) around += random.pick(NOISE);+ return `${around}${spelled}${random.pick(NOISE)}`;+}++test('JSON written with a token in it is still JSON when the token is taken out — in a string, in a key, nested, pretty-printed, and JSON inside JSON — and the value no longer holds the token', () => {+ const tokens = [TOKEN, OTHER];+ for (let seed = 1; seed <= 600; seed += 1) {+ const random = generator(seed);+ const document = { list: [spelledValue(random), { [spelledValue(random)]: spelledValue(random), n: 1 }], plain: spelledValue(random), done: true };+ document.inner = JSON.stringify({ message: spelledValue(random), deeper: JSON.stringify({ message: spelledValue(random) }) });+ for (const indent of [undefined, 2]) {+ const written = JSON.stringify(document, null, indent);+ const cleaned = redactTokens(written, tokens);+ let parsed;+ assert.doesNotThrow(() => { parsed = JSON.parse(cleaned); }, `seed ${seed}, indent ${indent}: ${cleaned}`);+ assert.deepEqual(leaksIn(cleaned, [TOKEN, ...PARTS]), [], `seed ${seed}: ${cleaned}`);+ assert.equal(Object.keys(parsed).length, 4, 'the document keeps its shape');+ assert.equal(parsed.done, true);+ }+ }+});++// ── The matcher against an exact reference ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// The text read into REGIONS, each a list of the ways it can be read — a way is the characters it spells, none at all for a fold — and every alignment of a needle followed through them with no limit on how many readings+// are followed at once. It shares no code with the module; what it holds is the specification:+// a backslash run (any length) and then `u` and four hex digits → the character they spell (nothing if it is white space), or the literal `u` and the four digits+// a backslash run and then `x` and two hex digits → the character they spell (nothing if it is white space), or the literal `x` and the two digits+// a backslash run and then `/` → `/`+// a backslash run and then `b` `f` `n` `r` `t` or `v` → nothing (a control character or white space), or the literal letter+// a backslash run and anything else, or the end of the text → nothing: a stray backslash between two characters of a token is a fold+// a terminal colour code (ESC [ and up to 32 bytes of 0x20–0x3f and a byte of 0x40–0x7e), or an ESC alone → nothing+// white space → nothing; a quote that is no character of a needle and starts `util.inspect`'s join of the pieces of a long string (a quote, a plus sign and a line break, the colour codes and the indentation+// between them) → nothing+// anything else → itself+// A match is spelled from the first region it reads a character of to the last: the whole regions, which is what keeps half an escape from being left behind.+const COLOUR = '\\x1b\\[[\\x20-\\x3f]{0,32}[\\x40-\\x7e]';+function regionsOf(text, alphabet) {+ const regions = [];+ for (let i = 0; i < text.length;) {+ const begin = i;+ const char = text[i];+ let alternatives = [[char]];+ let end = i + 1;+ if (char === '\\') {+ end = i;+ while (text[end] === '\\') end += 1;+ const letter = text[end];+ const hex = text.slice(end + 1, end + 5);+ const two = text.slice(end + 1, end + 3);+ if (letter === 'u' && /^[0-9a-fA-F]{4}$/.test(hex)) {+ const decoded = String.fromCharCode(parseInt(hex, 16));+ alternatives = [/\s/.test(decoded) ? [] : [decoded], ['u', ...hex]];+ end += 5;+ } else if (letter === 'x' && /^[0-9a-fA-F]{2}$/.test(two)) {+ const decoded = String.fromCharCode(parseInt(two, 16));+ alternatives = [/\s/.test(decoded) ? [] : [decoded], ['x', ...two]];+ end += 3;+ } else if (letter === '/') {+ alternatives = [['/']];+ end += 1;+ } else if (letter !== undefined && 'bfnrtv'.includes(letter)) {+ alternatives = [[], [letter]];+ end += 1;+ } else {+ alternatives = [[]];+ }+ } else if (char === '\u001b') {+ const colour = new RegExp(`^${COLOUR}`).exec(text.slice(i, i + 40));+ alternatives = [[]];+ end = i + (colour ? colour[0].length : 1);+ } else if (/\s/.test(char)) {+ alternatives = [[]];+ } else if ("\"'`".includes(char) && !alphabet.has(char)) {+ const between = `(?:[ \\t]|${COLOUR})*`;+ const join = new RegExp(`^${char}${between}\\+${between}\\r?\\n${between}${char}`).exec(text.slice(i));+ if (join) {+ alternatives = [[]];+ end = i + join[0].length;+ }+ }+ regions.push({ begin, end, alternatives });+ i = end;+ }+ return regions;+}++function reference(text, tokens) {+ const needles = [...new Set(tokens.filter(Boolean).flatMap((token) => needlesOf(token)))].filter((needle) => !/[\s\\\u001b]/.test(needle));+ const regions = regionsOf(text, new Set(needles.join('')));+ const spans = [];+ for (const needle of needles) {+ // `alive` maps how many characters of the needle an alignment has spelled to where the earliest such alignment began: of two alignments in the same state only the earlier one can make a longer match, and the+ // spans of two that end together merge into the longer.+ let alive = new Map();+ for (const region of regions) {+ const after = new Map();+ for (const alternative of region.alternatives) {+ let current = new Map(alive);+ for (const char of alternative) {+ const next = new Map();+ const keep = (state, began) => { if (!next.has(state) || began < next.get(state)) next.set(state, began); };+ for (const [state, began] of [...current, [0, region.begin]]) {+ if (needle[state] !== char) continue;+ if (state + 1 === needle.length) spans.push([began, region.end]);+ else keep(state + 1, began);+ }+ current = next;+ }+ for (const [state, began] of current) if (!after.has(state) || began < after.get(state)) after.set(state, began);+ }+ alive = after;+ }+ }+ spans.sort((a, b) => a[0] - b[0] || b[1] - a[1]);+ const merged = [];+ for (const span of spans) {+ const last = merged[merged.length - 1];+ if (last && span[0] < last[1]) last[1] = Math.max(last[1], span[1]);+ else merged.push([...span]);+ }+ let out = '';+ let at = 0;+ for (const [start, end] of merged) { out += text.slice(at, start) + MARK; at = end; }+ out += text.slice(at);+ return tokens.filter((token) => token && needlesOf(token).some((needle) => /[\s\\\u001b]/.test(needle))).reduce((current, token) => scrub(current, token), out);+}++test('the matcher agrees with an exact reference over a few thousand random texts: tokens spelled with folds, escapes, stray backslashes, colour codes and continuations, near misses, noise, and three tokens at once', () => {+ const NOISE = ['a', 'Z', '0', '9', '.', '-', '_', '/', ' ', '\n', '\r\n', '\t', '\\', '\\\\', 'u', '0073', '\\u0041', '\\/', '\\n', '\\\\r', 'é', '日', '🧪', '<token>', 'Bearer ', '"', "'", "' +\n '", '{', '}', '\u00a0',+ '\u001b[32m', '\u001b[39m', '\u001b', '\\q', '\\\\\\n', "'\u001b[39m +\n \u001b[32m'", 'n', 'r', 't', 'f', 'b', 'v', 'x', '\\b', '\\v', '\\x41', '\\x0B', '\\\\x7a', 'x0'];+ const GAPS = ['', '', '', ' ', '\n', '\r\n ', '\t', '\\r\\n', '\\n ', '\n\n', ' ', "' +\n '", '\\\\r\\\\n ', '\\u000a',+ '\u001b[32m', '\u001b[39m', '\u001b[1;32m\u001b[4m', "'\u001b[39m +\n \u001b[32m'", '\\', '\\\\', '\\q', '\\\\\\', '\u001b', '\\b', '\\x0b', '\\v'];+ const STRAYS = ['\\', '\\', '\\\\', '\\\\\\'];+ const tokens = [TOKEN, OTHER, 'aaa.bbb.ccc-and-a-longer-opaque-token-value'];+ for (let seed = 1; seed <= 3000; seed += 1) {+ const random = generator(seed);+ let text = '';+ for (let piece = 0; piece < 1 + random.int(6); piece += 1) {+ const roll = random.next();+ if (roll < 0.45) {+ const token = random.pick(tokens);+ const chars = [...(random.next() < 0.3 ? token.split('.')[random.int(3)] : token)];+ if (random.next() < 0.2) chars[random.int(chars.length)] = 'Q';+ const gapRate = random.next() * 0.5;+ const escapeRate = random.next() * 0.3;+ const strayRate = random.next() < 0.5 ? 0 : random.next() * 0.3;+ text += chars.map((char) => {+ let spelled = char;+ if (random.next() < escapeRate) spelled = `${random.next() < 0.3 ? '\\\\' : ''}${unicode(char, random.next() < 0.5)}`;+ else if (char === '/' && random.next() < 0.5) spelled = '\\/';+ if (random.next() < strayRate) spelled = random.pick(STRAYS) + spelled;+ return spelled + (random.next() < gapRate ? random.pick(GAPS) : '');+ }).join('');+ } else {+ for (let i = 0; i < 1 + random.int(8); i += 1) text += random.pick(NOISE);+ }+ }+ assert.equal(redactTokens(text, tokens), reference(text, tokens), `seed ${seed}: ${JSON.stringify(text)}`);+ }+});++// ── Cost ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('past its bound of readings followed at once the search does not guess which to drop — it fails, and a guarded stream writes a notice and not the text; a real token never comes near the bound', () => {+ // A needle that is one letter 300 times, against a text in which every escape may be that letter or nothing: every count of letters so far is a reading that is alive. Only a text made for the needle does this.+ const needle = `${'n'.repeat(300)}Z`;+ const crafted = `${'\\n'.repeat(400)}Z`;+ assert.throws(() => redactTokens(crafted, [needle]), (error) => error instanceof RangeError && /too many ways to read a token/.test(error.message));+ const stream = fakeStream();+ guardStream(stream, (text) => redactTokens(text, [needle]));+ stream.write(crafted);+ assert.equal(stream.chunks.length, 1);+ assert.match(stream.chunks[0], /^\[output withheld/, 'fail closed: what could not be checked is not written');+ // The search is whole again after the failure, with the same prepared needles.+ assert.equal(redactTokens(`a ${needle} b`, [needle]), `a ${MARK} b`);+ // Just under the bound: followed to the end, and the match found.+ const fits = `${'n'.repeat(120)}Z`;+ assert.equal(redactTokens(`${'\\n'.repeat(150)} ${fits}`, [fits]), `${'\\n'.repeat(150)} ${MARK}`);+ assert.equal(redactTokens(`${'\\n'.repeat(119)}nZ`, [fits]), MARK, 'the escapes read as the letters they are: the needle');+ // The synthetic token, spelled with every escape that can be read two ways, among text that is nothing but such escapes: far below the bound.+ const { token } = LEADING('n');+ const noisy = `${'\\n\\t\\b\\f\\r\\v\\u006e\\x6e'.repeat(20000)}${[...token].map((char) => `\\n${char}`).join('')}${'\\n'.repeat(20000)}`;+ assert.equal(redactTokens(noisy, [token]).endsWith(`${MARK}${'\\n'.repeat(20000)}`), true);+});++test('a token is found in a text of any size in time that grows with the text — a long text, a text that is nearly the token over and over, a long run of backslashes, and a text full of tokens', (t) => {+ const filler = 'The platform answered with a diagnostic that says nothing about credentials.\r\n';+ const big = filler.repeat(30000);+ const middle = big.length / 2;+ const started = Date.now();+ assert.equal(redactTokens(`${big.slice(0, middle)}${TOKEN.match(/.{1,50}/g).join('\r\n ')}${big.slice(middle)}`, [TOKEN]), `${big.slice(0, middle)}${MARK}${big.slice(middle)}`);+ assert.equal(redactTokens(big, [TOKEN]), big);+ // The text that is the needle's first 2,999 characters over and over: a matcher that restarts at every character takes seconds on it.+ const needle = `${'a'.repeat(2999)}Z`;+ const nearly = 'a'.repeat(65536);+ assert.equal(redactTokens(nearly, [needle]), nearly);+ assert.equal(redactTokens(`${nearly}${needle}`, [needle]), `${nearly}${MARK}`);+ // A run of backslashes is read once, as one item, and not again from each of them.+ const slashes = '\\'.repeat(2000000);+ assert.equal(redactTokens(`${slashes}${TOKEN}${slashes}`, [TOKEN]), `${slashes}${MARK}${slashes}`);+ assert.equal(redactTokens(`${slashes}n${slashes}u00${slashes}`, [TOKEN]), `${slashes}n${slashes}u00${slashes}`);+ // Fifty thousand tokens in one text.+ assert.equal(redactTokens(`${TOKEN}\n`.repeat(50000), [TOKEN]), `${MARK}\n`.repeat(50000));+ t.diagnostic(`${Date.now() - started} ms for all of the above`);+ assert.ok(Date.now() - started < 20000, 'a linear scan: tens of megabytes and the worst case of a restarting one finish in a moment');+});++// The signature of the synthetic token starts with `n`, so every `\n` of a text could be the first character of it: the worst text for the readings that follow both ways.+test('a backslash that can be read two ways and a colour code cost no more than the rest — a text of nothing else, one in which every escape could begin a match, a needle of one letter over and over, a code that never ends — in time that grows with the text', (t) => {+ const started = Date.now();+ const { signature, token } = LEADING('n');+ const escapes = '\\n'.repeat(1000000);+ assert.equal(redactTokens(escapes, [token]), escapes);+ const half = '\\n'.repeat(500000);+ assert.equal(redactTokens(`${half}Rejected signature \\${signature}${half}`, [token]), `${half}Rejected signature ${MARK}${half}`);+ // A needle that is `n` sixty times and then a `Z`: after each `\n` there is a reading in which it is the next `n`, and the readings that are alive could all be extended by the next one.+ const needle = `${'n'.repeat(60)}Z`;+ assert.equal(redactTokens(escapes, [needle]), escapes);+ assert.equal(redactTokens(`${escapes}${needle}${escapes}`, [needle]), `${escapes}${MARK}${escapes}`);+ assert.equal(redactTokens(`${'\\n'.repeat(30)}${needle}`, [needle]), `${'\\n'.repeat(30)}${MARK}`, 'the same on a text that is short enough to be followed in every way');+ const stray = '\\'.repeat(1000000);+ assert.equal(redactTokens(`${stray}${token}${stray}`, [token]), `${stray}${MARK}${stray}`);+ assert.equal(redactTokens(`\\n${'\\'.repeat(1000)}n`.repeat(1000), [token]), `\\n${'\\'.repeat(1000)}n`.repeat(1000));+ // Colour codes: a million of them, a million starts of one, and one that has a million parameters and no end.+ assert.equal(redactTokens('\u001b[0m'.repeat(1000000), [TOKEN]), '\u001b[0m'.repeat(1000000));+ assert.equal(redactTokens('\u001b['.repeat(1000000), [TOKEN]), '\u001b['.repeat(1000000));+ assert.equal(redactTokens(`\u001b[${'1;'.repeat(1000000)}`, [TOKEN]), `\u001b[${'1;'.repeat(1000000)}`);+ assert.equal(redactTokens(`${'\u001b[0m'.repeat(100000)}${TOKEN}${'\u001b[0m'.repeat(100000)}`, [TOKEN]), `${'\u001b[0m'.repeat(100000)}${MARK}${'\u001b[0m'.repeat(100000)}`);+ t.diagnostic(`${Date.now() - started} ms for all of the above`);+ assert.ok(Date.now() - started < 30000, 'a linear scan: the readings that are followed are bounded, and a text that is nothing but ways to read it finishes in a moment');+});++// ── The list of what is taken out of a token ──────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('needlesOf is the one list of what is taken out of a token: the token and each dot-separated part of 24 characters or more, longest first, once each', () => {+ assert.deepEqual(needlesOf(TOKEN), [TOKEN, PARTS[2], PARTS[1], PARTS[0]]);+ assert.deepEqual(needlesOf('aaa.bbb.ccc-and-a-longer-opaque-token-value'), ['aaa.bbb.ccc-and-a-longer-opaque-token-value', 'ccc-and-a-longer-opaque-token-value']);+ assert.deepEqual(needlesOf('opaque-token-without-any-dot-in-it'), ['opaque-token-without-any-dot-in-it']);+ assert.deepEqual(needlesOf(`${PARTS[0]}.${PARTS[0]}`), [`${PARTS[0]}.${PARTS[0]}`, PARTS[0]]);+ assert.equal(TOKEN_MARKER, MARK);+});++// ── The registry, in a process of its own: it is process-wide, and noting a token guards the streams ───────────────────────────────────────────────────────────++const SCRIPTS = path.resolve(__dirname, '..');+function inChild(source, env = {}) {+ const run = spawnSync(process.execPath, ['-e', source], { cwd: SCRIPTS, encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1', ...env } });+ assert.equal(run.status, 0, run.stderr);+ return run;+}++test('a token is noted once, the first time installs the guards, and a value shorter than 16 characters is no token', () => {+ const run = inChild(`+ const writeBefore = [process.stdout.write, process.stderr.write];+ const listenersBefore = process.listenerCount('uncaughtException');+ const r = require('./lib/output-redaction.js');+ const states = [];+ states.push(r.redactOutput('bearer ${TOKEN}'));+ r.noteToken('short-token'); r.noteToken(42); r.noteToken(undefined);+ states.push(r.obtainedTokens().length, process.stdout.write === writeBefore[0], process.listenerCount('uncaughtException') === listenersBefore);+ r.noteToken('${TOKEN}'); r.noteToken('${TOKEN}'); r.noteToken('${OTHER}');+ const after = [process.stdout.write !== writeBefore[0], process.stderr.write !== writeBefore[1], process.listenerCount('uncaughtException') === listenersBefore + 1];+ r.noteToken('${TOKEN}');+ require('node:fs').writeSync(1, JSON.stringify({ states, tokens: r.obtainedTokens().length, after, wrappedOnce: process.stdout.write.name, cleaned: r.redactOutput('bearer ${TOKEN} and ${OTHER}'), bytes: r.redactOutput(Buffer.from('${TOKEN}')).toString(), number: r.redactOutput(7) }));+ `);+ const out = JSON.parse(run.stdout);+ assert.deepEqual(out.states, ['bearer ' + TOKEN, 0, true, true], 'before a token is noted: nothing is cleaned, nothing is guarded, no listener is added');+ assert.equal(out.tokens, 2, 'two different tokens, each once');+ assert.deepEqual(out.after, [true, true, true], 'after the first: both streams are guarded and the process gets one handler for an error that ends it');+ assert.equal(out.wrappedOnce, 'writeWithoutTokens');+ assert.equal(out.cleaned, `bearer ${MARK} and ${MARK}`);+ assert.equal(out.bytes, TOKEN, 'bytes are passed as they are');+ assert.equal(out.number, 7);+});++test('a process that never notes a token is untouched: no stream is wrapped, no listener is added — loading the plugin\'s auth and client modules does not note one', () => {+ const run = inChild(`+ const before = [process.stdout.write, process.stderr.write, process.listenerCount('uncaughtException')];+ require('./lib/dataverse-auth.js'); require('./lib/sdk-http-client.js'); require('./lib/maker-sdk.js'); require('./lib/safe-fs.js');+ const { getAuthToken } = require('./lib/dataverse-auth.js');+ const missing = getAuthToken('https://contoso.crm.dynamics.com', { exec: () => { throw new Error('az is not here'); } });+ const r = require('./lib/output-redaction.js');+ require('node:fs').writeSync(1, JSON.stringify({ same: process.stdout.write === before[0] && process.stderr.write === before[1], listeners: process.listenerCount('uncaughtException') === before[2], missing, tokens: r.obtainedTokens().length }));+ `);+ assert.deepEqual(JSON.parse(run.stdout), { same: true, listeners: true, missing: null, tokens: 0 });+});++test('a token read from the Azure CLI — synchronously or not — and a token a client sends are noted; one that is not a token is not', async () => {+ const run = inChild(`+ (async () => {+ const auth = require('./lib/dataverse-auth.js');+ const r = require('./lib/output-redaction.js');+ const { createAzHttpClient } = require('./lib/sdk-http-client.js');+ const seen = [];+ const url = 'https://contoso.crm.dynamics.com';+ seen.push(auth.getAuthToken(url, { exec: () => '${TOKEN}\\n' }) === '${TOKEN}', r.obtainedTokens().length);+ seen.push(await auth.getPowerAppsTokenAsync({ execFile: (cmd, args, options, done) => { done(null, '${OTHER}\\n'); return {}; } }) === '${OTHER}', r.obtainedTokens().length);+ const client = createAzHttpClient(url, { getToken: () => 'sent-by-a-client-and-long-enough', request: async () => ({ statusCode: 200, headers: {}, body: '{}' }) });+ await client.get(url + '/api/data/v9.2/WhoAmI');+ seen.push(r.obtainedTokens().includes('sent-by-a-client-and-long-enough'));+ await auth.dataverseRequest(url, 'GET', 'WhoAmI', null, { getToken: () => 'sent-by-dataverse-request-long', request: async () => ({ statusCode: 200, body: '{}' }) });+ seen.push(r.obtainedTokens().includes('sent-by-dataverse-request-long'));+ await client.get(url + '/api/data/v9.2/WhoAmI');+ auth.getAuthToken(url, { exec: () => 'short' });+ seen.push(r.obtainedTokens().length);+ require('node:fs').writeSync(1, JSON.stringify(seen));+ })();+ `);+ assert.deepEqual(JSON.parse(run.stdout), [true, 1, true, 2, true, true, 4], 'both reads from the Azure CLI, and both clients, note what they sent; a short value is no token');+});++// ── The error that ends the process ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('the handler for an error that ends the process is added only when nothing else handles one, and leaves the decision to a handler that is added after it', () => {+ const { guardFatalErrors } = require('../lib/output-redaction.js');+ const other = () => {};+ process.on('uncaughtException', other);+ try {+ const before = process.listenerCount('uncaughtException');+ assert.equal(guardFatalErrors(), false, 'a process that already has a handler (a test runner has one) keeps it alone');+ assert.equal(process.listenerCount('uncaughtException'), before);+ } finally {+ process.off('uncaughtException', other);+ }+ const run = inChild(`+ require('./lib/output-redaction.js').noteToken('${TOKEN}');+ process.on('uncaughtException', (error) => { process.stdout.write('the host handled: ' + error.message + '\\n'); });+ setTimeout(() => { throw new Error('bearer ${TOKEN}'); }, 1);+ setTimeout(() => process.stdout.write('and the process went on\\n'), 50);+ `);+ assert.equal(run.stdout, `the host handled: bearer ${MARK}\nand the process went on\n`, 'the host\'s handler ran, its text was cleaned by the guard on stdout, and the process was not ended by the guard');+ assert.equal(run.stderr, '', 'and the guard printed nothing');+});++// ── A guard on a stream ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++const fakeStream = () => {+ const stream = { chunks: [], writes: [], write(chunk, ...rest) { this.chunks.push(chunk); this.writes.push(rest); return 'returned'; } };+ return stream;+};+const redactToken = (text) => redactTokens(text, [TOKEN]);++test('a guarded stream is given the text with the token taken out — and everything else as it was: the encoding, the callback, what write returns, the receiver', () => {+ const stream = fakeStream();+ assert.equal(guardStream(stream, redactToken), true);+ const done = () => {};+ assert.equal(stream.write(`bearer ${TOKEN}\n`, 'utf8', done), 'returned');+ assert.deepEqual(stream.chunks, [`bearer ${MARK}\n`]);+ assert.deepEqual(stream.writes, [['utf8', done]]);+ stream.write('no token\n');+ assert.deepEqual(stream.chunks, [`bearer ${MARK}\n`, 'no token\n']);+ assert.equal(stream.write.name, 'writeWithoutTokens');+});++test('a guarded stream passes bytes and text that is not text as they are, and says so when it is already guarded or is no stream', () => {+ const stream = fakeStream();+ assert.equal(guardStream(stream, redactToken), true);+ const bytes = Buffer.from(`bearer ${TOKEN}`);+ stream.write(bytes);+ stream.write(new Uint8Array([1, 2, 3]));+ stream.write(Buffer.from(TOKEN).toString('hex'), 'hex');+ stream.write(Buffer.from(TOKEN).toString('base64'), 'base64');+ stream.write(`bearer ${TOKEN}`, 'latin1');+ assert.equal(stream.chunks[0], bytes, 'a Buffer is the very Buffer: a test runner\'s frames are bytes');+ assert.deepEqual([...stream.chunks[1]], [1, 2, 3]);+ assert.equal(stream.chunks[2], Buffer.from(TOKEN).toString('hex'));+ assert.equal(stream.chunks[3], Buffer.from(TOKEN).toString('base64'));+ assert.equal(stream.chunks[4], `bearer ${MARK}`, 'a text in another text encoding is a text');+ assert.equal(guardStream(stream, redactToken), false, 'wrapped once');+ assert.equal(guardStream({}, redactToken), false);+ assert.equal(guardStream(null, redactToken), false);+ assert.equal(guardStream({ write: 3 }, redactToken), false);+});++test('a guard that cannot clean a text writes a notice and not the text; the guard sits where the stream\'s own write was, so a caller that wraps it wraps it whole', () => {+ const stream = fakeStream();+ guardStream(stream, () => { throw new Error('the matcher failed'); });+ stream.write(`bearer ${TOKEN}`);+ assert.equal(stream.chunks.length, 1);+ assert.match(stream.chunks[0], /^\[output withheld/);+ assert.ok(!stream.chunks[0].includes(TOKEN));+ // A caller that swaps `write` swaps the guard, and one that wraps it keeps it.+ const wrapped = fakeStream();+ guardStream(wrapped, redactToken);+ const guarded = wrapped.write;+ wrapped.write = function wrapper(chunk, ...rest) { return guarded.call(this, `<${chunk}>`, ...rest); };+ wrapped.write(`bearer ${TOKEN}`);+ assert.deepEqual(wrapped.chunks, [`<bearer ${MARK}>`]);+});++// ── A guard on the SDK's workspace ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('a guarded workspace storage writes every text with the token taken out, and is the storage in everything else — its folder, its paths, its class, its other methods', async () => {+ const dir = makeTempDir('workspace-guard-');+ const storage = bundle.createNodeWorkspaceStorage(dir);+ const guarded = guardWorkspaceStorage(storage, redactToken);+ assert.notEqual(guarded, storage);+ await guarded.writeTextAtomic(['forms', 'one.json'], JSON.stringify({ label: `Rejected bearer ${TOKEN.match(/.{1,8}/g).join('\r\n ')}`, [TOKEN]: 1 }));+ const written = fs.readFileSync(path.join(dir, 'forms', 'one.json'), 'utf8');+ assert.deepEqual(leaksIn(written, SECRETS), []);+ assert.deepEqual(JSON.parse(written), { label: `Rejected bearer ${MARK}`, [MARK]: 1 });+ assert.equal(await guarded.readText(['forms', 'one.json']), written, 'what is read is what is on disk');+ assert.equal(await guarded.exists(['forms', 'one.json']), true);+ assert.equal(guarded.getRoot(), dir);+ assert.equal(guarded.pathFor(['forms', 'one.json']), path.join(dir, 'forms', 'one.json'));+ assert.ok(guarded instanceof bundle.NodeFileSystemStorage, 'the SDK\'s own look for a file-system storage still finds one');+ await guarded.writeTextAtomic(['forms', 'two.json'], '{"plain":true}');+ assert.equal(fs.readFileSync(path.join(dir, 'forms', 'two.json'), 'utf8'), '{"plain":true}', 'a text that holds no token is written as it is');+ await guarded.deleteFile(['forms', 'two.json']);+ assert.equal(fs.existsSync(path.join(dir, 'forms', 'two.json')), false);+ for (const value of [null, undefined, 'storage', {}, { writeTextAtomic: 3 }]) assert.equal(guardWorkspaceStorage(value, redactToken), value, 'what is no storage is returned as it is');+});++// A valid WorkspaceStorage may keep its state in `#private` fields, which a method reads only on the object it was made for: the wrapper must run every member it does not judge on the STORAGE, never on itself.+class PrivateStorage {+ #files = new Map();+ #label = 'private';+ get label() { return this.#label; }+ get size() { return this.#files.size; }+ async readText(key) { return this.#files.get(key.join('/')) ?? null; }+ async writeTextAtomic(key, text) { this.#files.set(key.join('/'), text); }+ async exists(key) { return this.#files.has(key.join('/')); }+ async ensureContainer() { this.#files.size; }+ async deleteFile(key) { this.#files.delete(key.join('/')); }+ async deleteByPrefix(prefix) { for (const name of [...this.#files.keys()]) if (name.startsWith(prefix.join('/'))) this.#files.delete(name); }+}++test('a guarded workspace storage whose methods keep private state still works — every member but the writer runs on the storage itself, an accessor too — and what it writes is clean', async () => {+ const storage = new PrivateStorage();+ const guarded = guardWorkspaceStorage(storage, redactToken);+ assert.notEqual(guarded, storage);+ await guarded.writeTextAtomic(['a.json'], JSON.stringify({ message: `Rejected bearer ${TOKEN.match(/.{1,8}/g).join('\r\n ')}` }));+ await guarded.writeTextAtomic(['b.json'], '{"plain":true}');+ assert.deepEqual(JSON.parse(await storage.readText(['a.json'])), { message: `Rejected bearer ${MARK}` }, 'the storage holds the clean text');+ assert.equal(await storage.readText(['b.json']), '{"plain":true}');+ assert.equal(await guarded.readText(['a.json']), await storage.readText(['a.json']));+ assert.equal(await guarded.exists(['b.json']), true);+ assert.equal(await guarded.ensureContainer(), undefined);+ assert.equal(guarded.size, 2, 'an accessor reads the storage\'s private state');+ assert.equal(guarded.label, 'private');+ await guarded.deleteByPrefix(['a']);+ assert.equal(await storage.exists(['a.json']), false);+ await guarded.deleteFile(['b.json']);+ assert.equal(guarded.size, 0);+ assert.ok(guarded instanceof PrivateStorage, 'and it is still one');+ assert.ok('readText' in guarded && !('nothing' in guarded));+ assert.equal(guarded.nothing, undefined);+});++test('REAL BUNDLE: the SDK made by the factory works over a storage whose methods keep private state — as it does made by the bundle — and writes its manifest through it', async () => {+ const { createMakerSdk } = require('../lib/maker-sdk.js');+ const httpClient = { get: async () => { throw new Error('no service call is expected'); } };+ for (const [label, create] of [['the bundle', bundle.createMakerSdk], ['the factory', createMakerSdk]]) {+ const storage = new PrivateStorage();+ const sdk = create({ workspaceStorage: storage, instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await sdk.initWorkspace();+ assert.equal(await storage.exists(['manifest.json']), true, `${label}: the manifest is written`);+ }+});diff --git a/plugins/model-apps/scripts/tests/output-token-boundary.test.js b/plugins/model-apps/scripts/tests/output-token-boundary.test.jsnew file mode 100644index 000000000..82749b3a9--- /dev/null+++ b/plugins/model-apps/scripts/tests/output-token-boundary.test.js@@ -0,0 +1,245 @@+'use strict';+// The access tokens a process obtained never reach what a script WRITES: its stdout, its stderr — what Node prints when an error ends the script included — and the files it writes (the build's journal, its baseline, a result,+// a download, the SDK's workspace). Each test runs the scenarios of helpers/token-boundary-child.js in a REAL process, with the production SDK factory over the real vendored bundle and the production az-token HTTP client, and+// reads back what reached the process's file descriptors and its folder — not what a function was handed. (A test that swaps `process.stderr.write` in its own process swaps the very function that keeps the token out, and+// measures its own replacement.)+//+// The token is taken out of the TEXT a script writes, wherever the text came from: an SDK error that quotes a refused part of a change set, a warning an SDK method returns, the data of a successful answer, an error of an odd+// shape (frozen, an accessor for a message, a stack that writes). Nothing is done to the error, the warning or the answer: they stay exactly what the SDK and the service made, and the strict readers of a `$batch` answer, and+// the retry they decide, see what they always saw (tests/output-token-real-bundle.test.js).+const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { SECRETS, FOLDED, REFUSALS, LEADING_N_PARTS, LEADING_N_SECRETS } = require('./helpers/synthetic-token.js');+const { leaksIn } = require('./helpers/token-leaks.js');++const CHILD = path.join(__dirname, 'helpers', 'token-boundary-child.js');+const MARK = '<token>';++function filesUnder(root, base = root, out = new Map()) {+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {+ const full = path.join(root, entry.name);+ if (entry.isDirectory()) filesUnder(full, base, out);+ else out.set(path.relative(base, full).split(path.sep).join('/'), fs.readFileSync(full, 'utf8'));+ }+ return out;+}++// One scenario, in a real process: what it printed on each descriptor, how it ended, what it knew (`facts`: booleans and counts, never the token), and every file it wrote. `env` is added to the process's environment+// (FORCE_COLOR=1 makes the console print in colours, as it does on a terminal, which a pipe's reader would never see).+function run(scenario, parameters = {}, env = {}) {+ const dir = makeTempDir('token-boundary-');+ const work = path.join(dir, 'work');+ fs.mkdirSync(work);+ const factsFile = path.join(dir, 'facts.json');+ const result = spawnSync(process.execPath, [CHILD, scenario, JSON.stringify(parameters)], {+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1', TOKEN_BOUNDARY_DIR: work, TOKEN_BOUNDARY_FACTS: factsFile, ...env },+ encoding: 'utf8',+ timeout: 120000,+ });+ const facts = fs.existsSync(factsFile) ? JSON.parse(fs.readFileSync(factsFile, 'utf8')) : {};+ assert.ok(!facts.harnessFailure, `the scenario itself failed: ${facts.harnessFailure}`);+ return { status: result.status, stdout: result.stdout, stderr: result.stderr, facts, files: filesUnder(work) };+}++const writtenBy = (ran) => [['stdout', ran.stdout], ['stderr', ran.stderr], ...[...ran.files].map(([name, text]) => [`the file ${name}`, text])];++// Nothing that reached a descriptor or a file holds the token in any spelling; and what is still JSON is still JSON — a journal line, a status file, a baseline and the SDK's own workspace files are read back by the next run.+// `jsonStdout` is false for a scenario whose stdout is not JSON (an object printed with console.log). `secrets` is what must not be readable (the synthetic token and its parts unless a scenario sends another).+function assertNothingLeaks(ran, what, { jsonStdout = true, secrets = SECRETS } = {}) {+ for (const [where, text] of writtenBy(ran)) {+ assert.deepStrictEqual(leaksIn(text, secrets), [], `${what}: ${where} holds the token, or a part of it, in some spelling`);+ if (/^the file .*\.json$/.test(where)) assert.doesNotThrow(() => JSON.parse(text), `${what}: ${where} is still JSON`);+ if (/^the file .*\.jsonl$/.test(where)) for (const line of text.split('\n').filter(Boolean)) assert.doesNotThrow(() => JSON.parse(line), `${what}: a line of ${where} is still JSON`);+ }+ if (jsonStdout) for (const line of ran.stdout.split('\n').filter((l) => l.startsWith('{'))) assert.doesNotThrow(() => JSON.parse(line), `${what}: a JSON line of stdout is still JSON`);+}++const wroteMark = (ran) => writtenBy(ran).some(([, text]) => text.includes(MARK));++// ── A change set the service refuses as a whole: the SDK quotes the refused part into the error it raises ──────────────────────────────────────────────────────────────────++for (const [index, { name }] of REFUSALS.entries()) {+ test(`a change set refused as a whole, the part repeating the access token — ${name} — is reported without it: on both descriptors, in the journal, the baseline and the result files`, () => {+ const ran = run('change-set', { index });+ assert.strictEqual(ran.facts.refused, true, 'the edit is refused');+ assert.strictEqual(ran.status, 1, 'and the script ends as it did: with the failure');+ assertNothingLeaks(ran, name);+ assert.ok(wroteMark(ran), 'the token stood where the marker is: the scenario did write what quoted it');+ assert.match(ran.stderr, /HTTP 403 from \S+\/workflows\([^)]+\): /, 'what the service said is still there');+ assert.ok(ran.files.has('journal/build-log.jsonl') && ran.files.has('journal/build-status.json') && ran.files.has('baseline.json') && ran.files.has('result.json'), 'the journal, the status, the baseline and the result were written');+ });+}++// ── A console that prints in colours ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// On a terminal (and with FORCE_COLOR=1) `console.error(error)` prints the body an error keeps with `util.inspect`'s colours: a long string is cut after each line break, each piece wrapped in its own colour codes, and the+// pieces joined by a quote, a plus sign and a line break with the codes between them. A pipe's reader never sees it, a person at a console does.+for (const [index, name] of [[5, 'JSON with the token folded onto several lines'], [9, 'plain text with the token folded onto several lines'], [3, 'JSON with the first character of each part spelled as a \\u escape']]) {+ test(`a change set refused as a whole, ${name}, printed by a console that prints in colours — the codes between the pieces of a long string do not hide the token`, () => {+ const ran = run('change-set', { index }, { FORCE_COLOR: '1' });+ assert.strictEqual(ran.facts.refused, true);+ assert.strictEqual(ran.status, 1);+ assert.match(ran.stderr, /\u001b\[\d+m/, 'the console printed in colours: this is the scenario');+ assertNothingLeaks(ran, `${name}, in colours`);+ assert.ok(wroteMark(ran), 'the token stood where the marker is');+ assert.match(ran.stderr, /HTTP 403 from \S+\/workflows\([^)]+\): /, 'what the service said is still there');+ });+}++for (const how of ['console-log-folded-object', 'console-error-object']) {+ test(`${how} on a console that prints in colours reaches stdout and stderr without the token`, () => {+ const ran = run('print', { how }, { FORCE_COLOR: '1' });+ assert.strictEqual(ran.status, 0);+ assert.match(`${ran.stdout}${ran.stderr}`, /\u001b\[\d+m/, 'in colours');+ assertNothingLeaks(ran, how, { jsonStdout: false });+ assert.ok(wroteMark(ran));+ });+}++// ── A literal backslash right before a part of the token ───────────────────────────────────────────────────────────────────────────────────────────────────────────++// A diagnostic that says `... \nSyntheticSignature...` with a LITERAL backslash — JSON writes it `\\n` — is not a line break followed by `ySyntheticSignature...`: the `n` is the first character of the signature.+const LEADING_N = [+ ['signature', 'the signature alone, with a literal backslash right before it'],+ ['folded', 'the whole token folded onto several lines, with a literal backslash before the signature'],+ ['escaped-fold', 'the whole token with a JSON-escaped fold, and a literal backslash before the signature'],+];+// The token as `child 'leading-n'` quotes it — the backslash before the signature included — cut where it is folded: no piece of it may be left in anything the script wrote, which is what a person reassembling a folded+// token reads (the pieces are the fold's own, and a text can spell them with escapes no view of `leaksIn` joins).+const [, , SIGNATURE] = LEADING_N_PARTS;+const PIECES = `${LEADING_N_PARTS[0]}.${LEADING_N_PARTS[1]}.\\${SIGNATURE}`.match(/.{1,8}/g).filter((piece) => /^[A-Za-z0-9_-]{8}$/.test(piece));+for (const colours of [false, true]) {+ for (const [spelling, what] of LEADING_N) {+ test(`a change set refused as a whole, quoting ${what}${colours ? ', on a console that prints in colours' : ''}, is reported without the token — on both descriptors, in the journal, the baseline and the result files`, () => {+ const ran = run('leading-n', { spelling }, colours ? { FORCE_COLOR: '1' } : {});+ assert.strictEqual(ran.facts.refused, true, 'the edit is refused');+ assert.strictEqual(ran.status, 1);+ assertNothingLeaks(ran, what, { secrets: LEADING_N_SECRETS });+ if (spelling !== 'signature') for (const [where, text] of writtenBy(ran)) for (const piece of PIECES) assert.ok(!text.includes(piece), `${what}: ${where} holds the piece ${piece} of the token`);+ if (spelling === 'signature') for (const [where, text] of writtenBy(ran)) assert.ok(!text.includes(SIGNATURE) && !text.includes(SIGNATURE.slice(1)), `${what}: ${where} holds the signature, or all of it but its first character`);+ assert.ok(wroteMark(ran), 'the token stood where the marker is');+ assert.match(ran.stderr, /HTTP 403 from \S+\/workflows\([^)]+\): /, 'what the service said is still there');+ if (colours) assert.match(ran.stderr, /\u001b\[\d+m/, 'in colours');+ });+ }+}++// ── A warning the SDK RETURNS: no error object carries it ─────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('a form saved whose read-back is refused with the token folded onto several lines: the warning the SDK returns reaches stderr, the result, the journal and the baseline without it', () => {+ const ran = run('form');+ assert.strictEqual(ran.facts.saved, true, 'the push is saved');+ assert.strictEqual(ran.facts.refusedReads, 1, 'the read-back was refused');+ assert.strictEqual(ran.facts.warnings, 1, 'and the SDK said so in a warning');+ assert.strictEqual(ran.facts.warningHoldsToken, true, 'the warning the SDK returned holds the token: it is not rewritten, it is what is written that is clean');+ assert.strictEqual(ran.status, 0);+ assertNothingLeaks(ran, 'the read-back warning');+ assert.match(ran.stderr, /WARNING: form Main: The form was saved, but its new version could not be read \(HTTP 403 from /, 'the warning is said on stderr');+ assert.match(ran.stderr, /Rejected bearer <token>\)\./);+ assert.match(ran.stdout, /Rejected bearer <token>\)\./, 'and is in the result');+ const journal = ran.files.get('journal/build-log.jsonl').split('\n').filter(Boolean).map((line) => JSON.parse(line));+ assert.ok(journal.some((entry) => entry.status === 'warning' && /Rejected bearer <token>\)/.test(entry.detail)), 'and in the journal');+});++// ── An error of an odd shape, carried as the SDK's cause ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────++const ODD_ERRORS = {+ plain: 'an ordinary transport error',+ frozen: 'a frozen transport error',+ accessor: 'a transport error whose message is an accessor',+ 'stack-getter': 'a transport error whose stack is a getter that writes',+};+for (const [shape, what] of Object.entries(ODD_ERRORS)) {+ test(`${what} is reported without the token, and nothing but the transport's own code reads it while the SDK call runs`, () => {+ const ran = run('error-shape', { shape });+ assert.strictEqual(ran.facts.refused, true);+ // The transport itself reads the message once, to name the failure; the error is not walked by anything else, so a getter is not run on a script's behalf, and the one that writes is not run at all before it is printed.+ assert.ok(ran.facts.getterReadsDuringCall <= (shape === 'accessor' ? 1 : 0), `the getter ran ${ran.facts.getterReadsDuringCall} time(s) during the SDK call`);+ assert.strictEqual(ran.status, 1);+ assertNothingLeaks(ran, shape);+ assert.ok(wroteMark(ran), 'the token stood where the marker is');+ });+}++// ── A successful answer, and a token obtained from the Azure CLI ──────────────────────────────────────────────────────────────────────────────────────────────────────────++test('a success answer that repeats the token — the data a script prints and a download writes — reaches stdout and its file without it, valid JSON still, and the token the process obtained from the Azure CLI is known', () => {+ const ran = run('answer');+ assert.strictEqual(ran.facts.obtained, true, 'the token came from `az`, as it does for a script');+ assert.strictEqual(ran.status, 0);+ assertNothingLeaks(ran, 'the answer');+ const printed = JSON.parse(ran.stdout);+ assert.strictEqual(printed.value[0].name, 'Account', 'the rest of the data is what it was');+ assert.strictEqual(printed.value[0].plain, 'bearer <token>');+ assert.strictEqual(printed.value[0].note, 'Rejected bearer <token>', 'a token folded onto several lines is one marker');+ assert.strictEqual(printed.value[0]['<token>'], 'as a key', 'a key too');+ assert.deepStrictEqual(JSON.parse(ran.files.get('answer.json')), printed, 'the file holds what stdout does');+});++// ── Every way a script prints ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++const PRINTS = [+ ['stdout-write', 0], ['stderr-write', 0], ['console-log', 0], ['console-info', 0], ['console-debug', 0], ['console-warn', 0], ['console-error', 0], ['console-error-object', 0],+ ['console-log-folded-object', 0], ['json-line', 0], ['write-callback', 0], ['emit-ok', 0], ['emit-ok-ascii', 0], ['emit-error', 1], ['emit-text', 1], ['emit-structured', 1],+];+for (const [how, status] of PRINTS) {+ test(`a script that prints the token it obtained with ${how} writes the marker, and the script ends as it did`, () => {+ const ran = run('print', { how });+ assert.strictEqual(ran.facts.obtained, true);+ assert.strictEqual(ran.status, status);+ assertNothingLeaks(ran, how, { jsonStdout: how !== 'console-log-folded-object' });+ assert.ok(wroteMark(ran), 'the marker stands where the token stood');+ });+}++// ── What Node prints when an error ends the script: not through process.stderr.write ───────────────────────────────────────────────────────────────────────────────────────++for (const how of ['throw', 'reject', 'async-main']) {+ test(`an error that ends the script (${how}) is printed without the token — and still printed — and the script ends with status 1`, () => {+ for (const source of ['plain', 'change-set']) {+ const ran = run('fatal', { source, index: 5, how });+ assert.strictEqual(ran.status, 1, `${source}: an uncaught error ends the process with 1`);+ assertNothingLeaks(ran, `${how} of ${source}`);+ assert.match(ran.stderr, source === 'plain' ? /push form failed: Rejected bearer <token>/ : /HTTP 403 from \S+\/workflows\(/, `${source}: the error is still reported, with its message`);+ }+ });+}++test('an error that ends the script still lets the script\'s own handlers for the end of the process run — the ones that clean up a work folder — with the status 1', () => {+ const ran = run('fatal', { source: 'plain', how: 'throw', exitHandler: true });+ assert.strictEqual(ran.status, 1);+ assert.strictEqual(ran.files.get('exit-handler.txt'), 'ran with 1');+ assertNothingLeaks(ran, 'the end of the process');+});++// ── A large result ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('a result of several megabytes with the token in one row is written whole — one JSON document, every row, the token out of the one that held it — when the script exits right after writing it', () => {+ const rows = 30000;+ const dir = makeTempDir('token-boundary-big-');+ const factsFile = path.join(dir, 'facts.json');+ const work = path.join(dir, 'work');+ fs.mkdirSync(work);+ const started = Date.now();+ const result = spawnSync(process.execPath, [CHILD, 'big', JSON.stringify({ rows })], {+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1', TOKEN_BOUNDARY_DIR: work, TOKEN_BOUNDARY_FACTS: factsFile },+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ timeout: 120000,+ });+ const facts = JSON.parse(fs.readFileSync(factsFile, 'utf8'));+ assert.strictEqual(result.status, 0, result.stderr);+ assert.ok(facts.bytes > 3 * 1024 * 1024, `the result is several megabytes (${facts.bytes} characters)`);+ assert.deepStrictEqual(leaksIn(result.stdout, SECRETS), []);+ const printed = JSON.parse(result.stdout);+ assert.strictEqual(printed.length, rows, 'every row');+ assert.strictEqual(printed[rows / 2].note, 'Rejected bearer <token>');+ assert.strictEqual(printed[0].note, 'The platform answered with a diagnostic that says nothing about credentials.');+ const escaped = JSON.stringify(FOLDED).slice(1, -1);+ assert.strictEqual(result.stdout.length, facts.bytes - escaped.length + MARK.length + 1, 'and nothing else was changed: the folded token, as JSON writes it, became the marker, and a line break ends the text');+ assert.ok(Date.now() - started < 60000, 'in a moment');+});diff --git a/plugins/model-apps/scripts/tests/output-token-real-bundle.test.js b/plugins/model-apps/scripts/tests/output-token-real-bundle.test.jsnew file mode 100644index 000000000..b1358fa73--- /dev/null+++ b/plugins/model-apps/scripts/tests/output-token-real-bundle.test.js@@ -0,0 +1,160 @@+'use strict';+// A change set the service refuses as a whole, over the REAL vendored SDK and the production az-token HTTP client: what the SDK raises, and that the ANSWER stays exactly what the service sent.+//+// A change set the service refuses as a whole is answered HTTP 200 with the one part that failed. The SDK raises an error that QUOTES that part's body when it writes a flow's definition (`sendChangeSet`), and a token the+// service repeats in the part reaches the error. The HTTP client takes the access token out of every answer that is not a success, but a 2xx answer is the caller's data and is returned byte for byte: the strict readers that+// prove from an answer what a change set did (completeBatchStatus, isBatchThrottled, the page backend's refusal proof) count the bytes a part declares, and a refused write is sent again, or not, on what they prove. So neither the+// answer nor the error is rewritten: the token is taken out of what the process WRITES (tests/output-token-boundary.test.js reads what reached its stdout, stderr and files). These tests hold the other half: the SDK's own error+// is the SDK's own, and the answer, the strict reader's proof and the sends that follow from it are those of a client that takes nothing out.+const { test } = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const bundle = require('../vendor/cds-maker-sdk.cjs');+const { createMakerSdk, withVendoredCompiler } = require('../lib/maker-sdk.js');+const { makeGenpageSdk } = require('../lib/genpage-sdk.js');+const { completeBatchStatus } = require('../lib/sdk-http-client.js');+const { FakeGenPageServer, INSTANCE, ACCOUNT_TABLE } = require('./helpers/fake-genpage-server.js');+const { productionClient, flowEdit, refusedEdit } = require('./helpers/bpf-batch-service.js');+const { TOKEN, SECRETS, NL, CODE, REFUSALS } = require('./helpers/synthetic-token.js');+const { leaksIn } = require('./helpers/token-leaks.js');+const { makeTempDir } = require('./helpers/temp-dirs.js');++const SOURCE = "import * as React from 'react';\nexport default function Page() { return <div>Hello</div>; }\n";+const makeDir = () => makeTempDir('batch-failure-bpf-');++// The SDK exactly as the bundle ships it, apart from the compiler every script's SDK is given: the factory without the wiring a script's SDK has on top of it.+const bundled = withVendoredCompiler(bundle.createMakerSdk);++// A withheld id is minted for each run, so it is the one thing that differs between two runs of the same edit.+const withoutId = (text) => String(text).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '<id>');++for (const { name, body, typed } of REFUSALS) {+ test(`REAL BUNDLE: a change set refused as a whole, the refused part repeating the access token — ${name} — fails with the SDK's own error, and the SDK is handed the answer as the service sent it`, async () => {+ const control = await refusedEdit(body, bundled, makeDir);+ assert.ok(control.error, 'the control: the edit is refused');+ assert.ok(leaksIn(control.error, SECRETS).length > 0, 'the control: the SDK as the bundle ships it quotes the token — so this scenario is the exposure, and not a vacuous one');++ const { error, seen, given } = await refusedEdit(body, createMakerSdk, makeDir);+ assert.ok(error, 'the edit is refused');+ assert.strictEqual(error.code, 'CONNECTION_ERROR');+ assert.strictEqual(error.statusCode, 403, 'the SDK still reads the part: its status is the one the service gave');+ assert.match(error.message, /^HTTP 403 from \S+\/workflows\([^)]+\): /, 'what the service said is there');+ // The error is not rewritten: what a script writes is cleaned where it is written (tests/output-token-boundary.test.js), and an error keeps every word the SDK gave it.+ assert.ok(leaksIn(error, SECRETS).length > 0, 'the error holds what the SDK quoted');+ assert.deepStrictEqual([withoutId(error.message), error.cause, error.code, error.statusCode, withoutId(error.url)], [withoutId(control.error.message), control.error.cause, control.error.code, control.error.statusCode, withoutId(control.error.url)], 'and is the one the bundle makes');+ assert.strictEqual(typeof error.cause, typeof control.error.cause, 'the body the SDK kept is the kind of value it was');+ if (typed) assert.strictEqual(error.cause.error.code, typed, 'a JSON body is still the parsed object, with the platform\'s own code in it');+ // The answer is the one the service sent: the strict readers that prove a refusal from it, and the retry that follows from the proof, see what they always saw.+ assert.strictEqual(given.length, 1, 'one change set was sent');+ assert.strictEqual(given[0], seen[0], 'and the SDK was handed the answer exactly as the service sent it, byte for byte');+ assert.strictEqual(completeBatchStatus({ body: given[0] }), completeBatchStatus({ body: control.given[0] }), 'the strict reader reads it as it reads the control\'s');+ });+}++test('REAL BUNDLE: a refusal that holds no token is the SDK\'s own, unchanged — its message, the body it kept, its code and its status', async () => {+ const body = JSON.stringify({ error: { code: CODE, message: 'The record is locked by another process' } });+ const control = await refusedEdit(body, bundled, makeDir);+ const { error } = await refusedEdit(body, createMakerSdk, makeDir);+ assert.deepStrictEqual([withoutId(error.message), error.cause, error.code, error.statusCode, withoutId(error.url)], [withoutId(control.error.message), control.error.cause, control.error.code, control.error.statusCode, withoutId(control.error.url)]);+ assert.strictEqual(withoutId(error.stack.split('\n')[0]), withoutId(control.error.stack.split('\n')[0]), 'and so is the first line of its stack');+ assert.strictEqual(error.cause.error.message, 'The record is locked by another process');+});++test('REAL BUNDLE: a change set that succeeds, one part of which repeats the token, is applied all the same — and the SDK is handed the answer as the service sent it', async () => {+ const state = { refuse: false, refusal: '', echo: false };+ const { apply, seen, given } = await flowEdit(state, createMakerSdk, makeDir);+ state.echo = true;+ const pushed = await apply();+ assert.strictEqual(pushed.saved, true, 'the edit is saved');+ assert.strictEqual(given.length, 1);+ assert.ok(seen[0].includes(TOKEN), 'the service did repeat the token, in a part that succeeded');+ assert.strictEqual(given[0], seen[0], 'a success is the caller\'s data: the answer is the very text the service sent');+});++// ── A page: the backend sends a refused change set once, or again, on what the answer PROVES — so the answer must stay the answer ───────────────────────────────────────────+function makeServer() {+ const server = new FakeGenPageServer();+ server.serveTable(ACCOUNT_TABLE);+ return server;+}++// A backend on a throwaway workspace whose folders are recorded, so the test can prove they are gone after dispose().+async function withBackend(client, fn) {+ const made = [];+ const genpage = makeGenpageSdk(INSTANCE, { httpClient: client, sleep: async () => {}, random: () => 0, mkdtempSync: (prefix) => { const dir = fs.mkdtempSync(prefix); made.push(dir); return dir; } });+ try {+ return await fn(genpage);+ } finally {+ await genpage.dispose();+ for (const dir of made) assert.ok(!fs.existsSync(dir), `the throwaway workspace ${dir} is removed by dispose()`);+ }+}++// The page write refused as a whole: the fake's refused part has no body, so the answer is rewritten to give it one (`detail`, of `contentType`, counted in a `Content-Length`), as a service that explains the refusal does.+// `proofs` is what the strict reader proves from each such answer, as the backend reads it.+async function refusedPageWrite({ status, detail, contentType }) {+ const server = makeServer();+ const refusedPart = `HTTP/1.1 ${status} Failed${NL}OData-Version: 4.0${NL}${NL}`;+ const proofs = [];+ let refusing = false;+ const rewrite = (text) => {+ if (!refusing || !text.includes(refusedPart)) return text;+ const answer = text.replace(refusedPart, `HTTP/1.1 ${status} Refused${NL}Content-Type: ${contentType}${NL}Content-Length: ${Buffer.byteLength(detail)}${NL}${NL}${detail}${NL}`);+ proofs.push(completeBatchStatus({ body: answer }));+ return answer;+ };+ return withBackend(productionClient(server.http(), { rewrite }), async (genpage) => {+ const { pageId } = await genpage.create({ name: 'Overview', source: SOURCE, prompt: 'first', agentMessage: 'ok' });+ const before = server.batches.length;+ server.failOn = (_method, _path, batched) => (batched ? status : undefined);+ refusing = true;+ const error = await genpage.update(pageId, { source: SOURCE.replace('Hello', 'Second'), prompt: 'second', agentMessage: 'done' }).then(() => null, (e) => e);+ return { error, sends: server.batches.length - before, proofs };+ });+}++const COUNTED_REFUSAL = JSON.stringify({ error: { code: CODE, message: `Principal user rejected bearer ${TOKEN} for this write` } });++test('REAL BUNDLE: a page write refused as a whole by a part that counts its bytes and repeats the token is still proven a refusal — one send, nothing written', async () => {+ const { error, sends, proofs } = await refusedPageWrite({ status: 403, detail: COUNTED_REFUSAL, contentType: 'application/json' });+ assert.ok(error, 'the update is refused');+ assert.deepStrictEqual(proofs, [403], 'the strict reader proves the refusal from the answer as it came: the part counts the bytes it has');+ assert.strictEqual(error.outcome, 'nothing', 'so the backend says nothing was written');+ assert.strictEqual(sends, 1, 'and the change set was sent once');+ assert.match(error.message, /the service refused the change set with HTTP 403/);+});++// What the strict reader cannot prove, the backend does not take for a refusal: a part whose body is a line that looks like a delimiter is read as an answer that proves nothing, so the write may have+// committed and is looked for before it is sent again — once more, for a 403 and for a 429 alike: a 429 is not sent six times over on a proof the answer does not give.+for (const status of [403, 429]) {+ test(`REAL BUNDLE: a page write refused with HTTP ${status} by a part whose body looks like a delimiter proves nothing — it is sent twice and its outcome is unknown, whether the body holds the token or not`, async () => {+ const withToken = await refusedPageWrite({ status, detail: `--${TOKEN}`, contentType: 'text/plain' });+ const withoutToken = await refusedPageWrite({ status, detail: '--the-gateway-says-no', contentType: 'text/plain' });+ for (const run of [withToken, withoutToken]) {+ assert.strictEqual(run.sends, 2, 'the backend looks for the write and sends it once more');+ assert.ok(run.proofs.length === 2 && run.proofs.every((proof) => proof === 0), 'the strict reader proves nothing from either answer');+ assert.strictEqual(run.error.outcome, 'unknown');+ }+ });+}++test('REAL BUNDLE: a page write refused with HTTP 429 by a part that proves the refusal is sent again on the schedule of a throttle — six sends in all', async () => {+ const { error, sends, proofs } = await refusedPageWrite({ status: 429, detail: COUNTED_REFUSAL, contentType: 'application/json' });+ assert.ok(error, 'the update is refused in the end');+ assert.ok(proofs.length === 6 && proofs.every((proof) => proof === 429), 'every answer proves the throttle');+ assert.strictEqual(sends, 6, 'the first send and five more, as for any throttled page write');+});++test('REAL BUNDLE: a change set that succeeds is read from the very bytes the service answered — through the production client, with a token long enough to be taken out of an answer', async () => {+ const server = makeServer();+ const seen = [];+ const client = productionClient(server.http(), { seen });+ const given = [];+ const watched = { ...client, postRaw: async (...args) => { const answer = await client.postRaw(...args); given.push(answer.body); return answer; } };+ await withBackend(watched, async (genpage) => {+ const out = await genpage.create({ name: 'Overview', source: SOURCE, prompt: 'p', agentMessage: 'r' });+ assert.ok(out.pageId, 'the page is created');+ assert.strictEqual(server.batches.length, 1);+ assert.deepStrictEqual(given, seen, 'every $batch answer the SDK was given is the text the service sent, byte for byte');+ });+});diff --git a/plugins/model-apps/scripts/tests/output-token-writers.test.js b/plugins/model-apps/scripts/tests/output-token-writers.test.jsnew file mode 100644index 000000000..5eff3fd73--- /dev/null+++ b/plugins/model-apps/scripts/tests/output-token-writers.test.js@@ -0,0 +1,199 @@+'use strict';+// The files the plugin writes hold no access token the process obtained: the build's journal and status, a download's files, the baseline and the records beside it, and the SDK's workspace. Every writer of text that a service's+// words can reach goes through lib/output-redaction.js — `writeFileSafe` and `appendFileSafe` (lib/safe-fs.js), `writeFileAtomic` (lib/apply-snapshot-store.js) and the workspace storage the SDK factory wraps — and this file holds+// each of them, and LISTS every other write in the plugin with the reason none of them can carry a token, so a new writer fails here until someone has decided which it is.+const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const bundle = require('../vendor/cds-maker-sdk.cjs');+const { createMakerSdk } = require('../lib/maker-sdk.js');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const { writeFileSafe, appendFileSafe } = require('../lib/safe-fs.js');+const { writeFileAtomic } = require('../lib/apply-snapshot-store.js');+const { noteToken } = require('../lib/output-redaction.js');+const ai = require('../lib/artifact-intent.js');+const { createHarness, seedForm, NOTES_CLASS_ID } = require('./helpers/form-store-harness.js');+const { scriptsMatching, productionScripts, scriptLabel, withoutComments } = require('./helpers/production-scripts.js');+const { TOKEN, SECRETS, FOLDED } = require('./helpers/synthetic-token.js');+const { leaksIn } = require('./helpers/token-leaks.js');+const { makeTempDir } = require('./helpers/temp-dirs.js');++const MARK = '<token>';+// A process that has obtained a token: this is what the first read from the Azure CLI, or the first request a client sends, does.+noteToken(TOKEN);++const FOLDED_JSON = (extra = {}) => JSON.stringify({ message: `Rejected bearer ${FOLDED}`, [TOKEN]: 'as a key', nested: { list: [`bearer ${TOKEN}`] }, ...extra });++// ── The writers ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('lib/safe-fs.js writes a text with the token taken out of it — replaced, created exclusively, appended — and JSON that was written is still JSON; what holds none is written as it is, and bytes are bytes', () => {+ const dir = makeTempDir('safe-fs-tokens-');+ const replaced = writeFileSafe(path.join(dir, 'result.json'), `${FOLDED_JSON()}\n`);+ assert.deepStrictEqual(leaksIn(fs.readFileSync(replaced, 'utf8'), SECRETS), []);+ assert.deepStrictEqual(JSON.parse(fs.readFileSync(replaced, 'utf8')), { message: `Rejected bearer ${MARK}`, [MARK]: 'as a key', nested: { list: [`bearer ${MARK}`] } });+ writeFileSafe(path.join(dir, 'result.json'), `${FOLDED_JSON({ again: true })}\n`, { encoding: 'utf8' });+ assert.strictEqual(JSON.parse(fs.readFileSync(path.join(dir, 'result.json'), 'utf8')).again, true, 'a file is replaced as it was');+ writeFileSafe(path.join(dir, 'settings.json'), `${FOLDED_JSON()}\n`, { exclusive: true, encoding: 'utf8' });+ assert.deepStrictEqual(leaksIn(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8'), SECRETS), [], 'an exclusive write too');+ appendFileSafe(path.join(dir, 'build-log.jsonl'), `${FOLDED_JSON({ line: 1 })}\n`);+ appendFileSafe(path.join(dir, 'build-log.jsonl'), `${JSON.stringify({ line: 2, note: 'nothing secret here' })}\n`);+ const lines = fs.readFileSync(path.join(dir, 'build-log.jsonl'), 'utf8').split('\n').filter(Boolean);+ assert.deepStrictEqual(leaksIn(lines.join('\n'), SECRETS), []);+ assert.deepStrictEqual(lines.map((line) => JSON.parse(line).line), [1, 2], 'every line is JSON still');+ writeFileSafe(path.join(dir, 'plain.txt'), 'No secret here, only text.\r\nA second line.\r\n');+ assert.strictEqual(fs.readFileSync(path.join(dir, 'plain.txt'), 'utf8'), 'No secret here, only text.\r\nA second line.\r\n', 'a text that holds no token is written as it is');+ const bytes = Buffer.from([0x00, 0xff, 0x10, 0x80]);+ writeFileSafe(path.join(dir, 'bytes.bin'), bytes);+ assert.deepStrictEqual(fs.readFileSync(path.join(dir, 'bytes.bin')), bytes, 'bytes are written as they are');+});++test('lib/apply-snapshot-store.js writes the snapshot, the baseline and the records beside them with the token taken out, and JSON that was written is still JSON', () => {+ const dir = makeTempDir('snapshot-tokens-');+ writeFileAtomic(path.join(dir, 'last-applied.json'), FOLDED_JSON({ app: { uniqueName: 'contoso_app' } }));+ const written = fs.readFileSync(path.join(dir, 'last-applied.json'), 'utf8');+ assert.deepStrictEqual(leaksIn(written, SECRETS), []);+ assert.strictEqual(JSON.parse(written).app.uniqueName, 'contoso_app');+ writeFileAtomic(path.join(dir, 'clean.json'), '{"a":1}');+ assert.strictEqual(fs.readFileSync(path.join(dir, 'clean.json'), 'utf8'), '{"a":1}');+ assert.deepStrictEqual(fs.readdirSync(dir).sort(), ['clean.json', 'last-applied.json'], 'no temporary file is left');+ assert.deepStrictEqual(scriptsMatching(/\bwriteFileAtomic\s*\(/), ['lib/apply-snapshot-store.js', 'lib/deployed-baseline.js', 'lib/page-ownership-records.js', 'lib/page-publish-records.js'], 'the baseline and the records are written by it, and by nothing else');+});++// A form whose labels hold the token — as a label a maker typed could, or an answer that echoes a header — read by the SDK, which writes the form, its metadata and the manifest into the workspace: the SDK factory's storage keeps+// the token out of every one of those files, and the SDK as the bundle ships it does not.+test('REAL BUNDLE: a success answer that repeats the token — a form whose labels hold it — reaches no file of the SDK\'s workspace made by the factory; the bundle\'s own storage writes it', async () => {+ const withToken = (formxml) => formxml+ .replace('<label description="Main" languagecode="1033" />', `<label description="Rejected bearer ${TOKEN}" languagecode="1033" />`)+ .replace('<label description="Main" languagecode="1033" />', `<label description="${FOLDED.replace(/\r\n/g, ' ')}" languagecode="1033" />`);+ const filesUnder = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => (entry.isDirectory() ? filesUnder(path.join(dir, entry.name)) : [path.join(dir, entry.name)]));+ const read = async (makeSdk) => {+ const h = createHarness({ createSdk: makeSdk });+ try {+ const spec = {+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] }],+ forms: [{ entity: 'new_ticket', name: 'Main', tabs: [{ name: 'tab_main', label: 'Main', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }] }] }],+ };+ await seedForm(h, ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID }).tabs);+ h.store.row = { ...h.store.row, formxml: withToken(h.store.row.formxml) };+ const dir = makeTempDir('sdk-workspace-tokens-');+ const { sdk } = await h.freshSdk(dir);+ await sdk.fetchArtifact('form', h.formId);+ return filesUnder(dir).map((file) => [path.relative(dir, file), fs.readFileSync(file, 'utf8')]);+ } finally {+ h.cleanup();+ }+ };+ // The factory, over the production client (which sends the token, so the process has obtained it) — and the bundle's own factory over the same.+ const overProductionClient = (create) => (options) => create({ ...options, httpClient: createAzHttpClient(options.instanceUrl, { getToken: () => TOKEN, request: async ({ method, url, headers, body }) => {+ const verb = method.toLowerCase();+ const res = method === 'GET' || method === 'DELETE' ? await options.httpClient[verb](url, { headers }) : await options.httpClient[verb](url, typeof body === 'string' ? JSON.parse(body) : body, { headers });+ return { statusCode: res.status, headers: res.headers || {}, body: typeof res.body === 'string' ? res.body : JSON.stringify(res.body ?? null) };+ } }) });+ const control = await read(overProductionClient(bundle.createMakerSdk));+ assert.ok(control.some(([, text]) => leaksIn(text, SECRETS).length > 0), 'the control: the bundle\'s own storage writes the token into the workspace — so the scenario is the exposure');+ const guarded = await read(overProductionClient(createMakerSdk));+ assert.ok(guarded.length >= 3, 'the form, its metadata and the manifest are written');+ for (const [name, text] of guarded) {+ assert.deepStrictEqual(leaksIn(text, SECRETS), [], `${name} holds the token`);+ assert.doesNotThrow(() => JSON.parse(text), `${name} is still JSON`);+ }+ assert.ok(guarded.some(([, text]) => text.includes(MARK)), 'and the marker stands where the token was');+});++// ── Every other write in the plugin ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// A call that writes or copies a file's content: `fs.writeFileSync`, `fsx.writeFileSync(fd, …)`, `fs.promises.writeFile`, `appendFileSync`, `createWriteStream`, `writeSync`, `copyFileSync`, `cpSync`.+const WRITES = /\.(?:writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|writeSync|copyFileSync|copyFile|cpSync)\s*\(/;++// The writers that clean a text first, and what makes each one so.+const GUARDED_WRITERS = {+ 'lib/safe-fs.js': /redactOutput\(data\)/,+ 'lib/apply-snapshot-store.js': /fs\.writeFileSync\(fd, redactOutput\(text\)\)/,+};++// The writers that are not guarded, and why none of them can write a token: each writes what the plugin made itself, or what a person gave it, never a word of a service's, or runs in a process that obtains no token.+const OTHER_WRITERS = {+ 'solution-settings.js': 'its template goes through `writeFileSafe(… leaving(text))` and both streams through its own `guardOutput`; the copy of the settings and the package it hands pac are data for another program, never altered',+ 'lib/private-folder.js': 'the copy of the settings file the person gave, made private for pac: their own bytes',+ 'lib/temp-workspace.js': 'the owner record of a temporary folder: a process id, a host and a time',+ 'lib/telemetry/lib/emit-dispatcher.js': 'telemetry events, in a hook process that obtains no token, limited to the approved fields',+ 'lib/telemetry/lib/local-log.js': 'the local mirror of those events',+ 'lib/telemetry/lib/user-config.js': 'the telemetry choice a person made',+ 'lib/telemetry/region/region-cache.js': 'a cached region name',+ 'capture-fixture.js': 'a developer tool that copies test fixtures; it reads nothing from a service',+ 'generate-page-manifest.js': 'writes the manifest of a page from its own source; it reads nothing from a service',+ 'genpage-worker-output.js': 'a sidecar of the page worker\'s own file path and state; it reads nothing from a service',+ 'promote-intent-pages.js': 'writes the spec the agent gave back with pages added from its intent; it calls no service',+ 'regenerate-verified-icons.js': 'a developer tool that regenerates a list of icon names',+ 'smoke-eval.js': 'a developer tool that writes a spec for an eval',+ 'write-page-plan.js': 'writes the plan the agent gave; it calls no service',+};+// Every one of those that runs in a process that could hold a token is checked to call nothing that obtains one.+const TOKEN_CALLS = /\b(?:getAuthToken|getAuthTokenAsync|getPowerAppsToken|getPowerAppsTokenAsync|dataverseRequest|preflightAuth|createMakerSdk|createAzHttpClient|makeGenpageSdk|sdkFirst)\b/;++test('every write of file content in the plugin is a guarded writer or one of a listed few that cannot carry a token — a new writer fails here until it is one or the other', () => {+ const found = scriptsMatching(WRITES);+ assert.deepStrictEqual(found, [...Object.keys(GUARDED_WRITERS), ...Object.keys(OTHER_WRITERS)].sort(), 'a writer was added or removed: say which kind it is');+ for (const [label, evidence] of Object.entries(GUARDED_WRITERS)) {+ const file = productionScripts().find((candidate) => scriptLabel(candidate) === label);+ assert.match(withoutComments(fs.readFileSync(file, 'utf8')), evidence, `${label} cleans the text it writes`);+ }+ for (const label of ['capture-fixture.js', 'generate-page-manifest.js', 'genpage-worker-output.js', 'promote-intent-pages.js', 'regenerate-verified-icons.js', 'smoke-eval.js', 'write-page-plan.js', 'lib/temp-workspace.js', 'lib/private-folder.js']) {+ const file = productionScripts().find((candidate) => scriptLabel(candidate) === label);+ assert.doesNotMatch(withoutComments(fs.readFileSync(file, 'utf8')), TOKEN_CALLS, `${label} calls nothing that obtains a token`);+ }+});++test('the plugin writes to its descriptors only through the streams a script prints on — the one raw write is guarded by its own, and no child inherits them in a script that obtains a token', () => {+ assert.deepStrictEqual(scriptsMatching(/\bwriteSync\(\s*[12]\b/), ['solution-settings.js'], 'its note at the end of a run goes through its own `leaving`');+ assert.deepStrictEqual(scriptsMatching(/\.pipe\(\s*process\.std(?:out|err)|process\.std(?:out|err)\.(?:_|fd\b)|\.writeSync\(\s*process\.std/), [], 'nothing is piped to a stream, and none is written below `write`');+ // A child that inherits the streams writes to them without passing through this process: these are developer tools and the test runner, which obtain no token.+ assert.deepStrictEqual(scriptsMatching(/stdio\s*:\s*(?:'inherit'|"inherit"|\[[^\]]*['"]inherit['"])/), ['launch-playwright-mcp.js', 'regenerate-verified-icons.js', 'run-tests.js']);+ for (const label of ['launch-playwright-mcp.js', 'regenerate-verified-icons.js', 'run-tests.js']) {+ const file = productionScripts().find((candidate) => scriptLabel(candidate) === label);+ assert.doesNotMatch(withoutComments(fs.readFileSync(file, 'utf8')), TOKEN_CALLS, `${label} obtains no token`);+ }+});++test('every place a token is read from the Azure CLI or sent to a service notes it: both reads of the Azure CLI and the two senders', () => {+ const notes = (label) => withoutComments(fs.readFileSync(productionScripts().find((file) => scriptLabel(file) === label), 'utf8')).match(/noteToken\(/g) || [];+ assert.strictEqual(notes('lib/dataverse-auth.js').length, 3, 'the synchronous and the asynchronous read of the Azure CLI, and the loop of dataverseRequest');+ assert.strictEqual(notes('lib/sdk-http-client.js').length, 1, 'the SDK\'s HTTP client, before each request');+ assert.deepStrictEqual(scriptsMatching(/account['"],\s*['"]get-access-token/), ['lib/dataverse-auth.js'], 'and the Azure CLI is asked for a token in one place');+});++test('emitResult cleans the text it prints, where the stream\'s write has been replaced — a host that runs a script in its own process, a test that captures it', () => {+ const { emitResult } = require('../lib/dataverse-auth.js');+ const printed = { stdout: [], stderr: [] };+ const ended = { code: null };+ const real = { exit: process.exit, stdout: process.stdout.write, stderr: process.stderr.write };+ process.exit = (code) => { ended.code = code; throw ended; };+ process.stdout.write = (chunk) => { printed.stdout.push(String(chunk)); return true; };+ process.stderr.write = (chunk) => { printed.stderr.push(String(chunk)); return true; };+ const codes = [];+ try {+ for (const [ok, payload, options] of [+ [true, { message: `Rejected bearer ${FOLDED}`, [TOKEN]: 'key', list: [TOKEN] }],+ [true, { accent: 'é', message: `bearer ${TOKEN}` }, { ascii: true }],+ [false, new Error(`push failed: Rejected bearer ${FOLDED}`)],+ [false, { ok: false, error: `Rejected bearer ${TOKEN}`, detail: FOLDED }],+ [false, { ok: false, errors: [`bearer ${TOKEN}`] }],+ [false, `plain text ${TOKEN}`],+ ]) {+ try { emitResult(ok, payload, options); } catch (thrown) { if (thrown !== ended) throw thrown; }+ codes.push(ended.code);+ }+ } finally {+ process.exit = real.exit;+ process.stdout.write = real.stdout;+ process.stderr.write = real.stderr;+ }+ assert.deepStrictEqual(codes, [0, 0, 1, 1, 1, 1]);+ assert.deepStrictEqual(leaksIn(printed.stdout.join(''), SECRETS), []);+ assert.deepStrictEqual(leaksIn(printed.stderr.join(''), SECRETS), []);+ assert.deepStrictEqual(JSON.parse(printed.stdout[0]), { message: `Rejected bearer ${MARK}`, [MARK]: 'key', list: [MARK] }, 'the result is JSON still, and says what it said');+ assert.strictEqual(printed.stdout[1], `{"accent":"\\u00e9","message":"bearer ${MARK}"}\n`);+ assert.strictEqual(printed.stderr[0], `push failed: Rejected bearer ${MARK}\n`);+ assert.ok(printed.stderr.some((line) => line === `Rejected bearer ${MARK}\n`) && printed.stderr.some((line) => line === `plain text ${MARK}\n`));+});diff --git a/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js b/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.jsnew file mode 100644index 000000000..489079290--- /dev/null+++ b/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js@@ -0,0 +1,388 @@+'use strict';+// A script that writes and then ends the process at once must make its writes blocking first (lib/output-redaction.js makeWritesBlocking), or a pipe+// on Linux and macOS takes only what fits at once. result-whole-before-exit.test.js holds emitResult, the printer of an error that ends the process+// and dataverse-request.js; this file holds every printer a script has of its OWN — check-auth.js, genpage-plan-provenance.js,+// promote-intent-pages.js, check-page-files.js, genpage-worker-output.js — every usage error and last-resort handler of the scripts, the "last+// writes" a script makes right before its result, and the hooks' messages. exit-writes-inventory.test.js is a syntactic tripwire for a new exit.+//+// Each case runs as a real process, with a text a megabyte long and with a small one, and is checked two ways:+// - THE ORDER (helpers/write-order-preload.js): the process records when it makes stdout or stderr blocking and when it writes to them, and each+// stream it wrote to must have been made blocking before its first write. An order does not depend on the platform, the runtime or how far+// anything reads ahead, so this is the check that fails, on every run, for a printer left without the call (or with it after its write, or on+// the other stream). With the unchanged printers it failed on Windows under Node 20 and Node 22 alike.+// - THE TEXT: what a reader receives is the whole text, with the exit status it always had — over the kind of pipe Linux and macOS give a script+// (helpers/queued-stdio-preload.js), whose reader holds back: its streams are paused until the process has ended, or has written and then+// written nothing more for a while; and over the process's own stdout and stderr (queued pipes on Linux and macOS, synchronous ones on Windows),+// the reference the queued run must equal. Pausing stops the test from taking what arrives, not the runtime from reading ahead below it, so how+// much a printer without the call loses here depends on the runtime: on Windows, 65,536 characters of a megabyte arrived under Node 22, and all+// of it under Node 20. The text check shows what a reader gets; it is not what proves the fix.+// The texts are made without a command line that long (Windows allows 32,767 characters): helpers/huge-failure-preload.js makes the plugin's flag+// check answer with such a message, or its argument parser throw one; helpers/fake-auth-check-preload.js refuses check-auth.js's WhoAmI with such a+// diagnostic; plans, specs and pages are files. A small text's bytes and exit status must be what they always were.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { spawn } = require('node:child_process');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { hugeFailureText } = require('./helpers/huge-failure-preload.js');+const { validateFlags } = require('../lib/dataverse-auth.js');++const SCRIPTS = path.join(__dirname, '..');+const HOOKS = path.join(SCRIPTS, '..', 'hooks');+const QUEUED = path.join(__dirname, 'helpers', 'queued-stdio-preload.js');+const ORDER = path.join(__dirname, 'helpers', 'write-order-preload.js');+const HUGE = path.join(__dirname, 'helpers', 'huge-failure-preload.js');+const FAKE_AUTH = path.join(__dirname, 'helpers', 'fake-auth-check-preload.js');+const ENV_URL = 'https://contoso.crm.dynamics.com';+// A megabyte: some eight times what a pipe and its reader's buffer take before the writer has to wait.+const BIG = 1024 * 1024;+const MODES = ['queued', 'own'];+// A held process that has written something and then written nothing more for this long, while still running, is taken to be waiting for its reader.+const QUIET_MS = 300;+const CAP_MS = 10000;++// Where each run's record of the order of its writes goes (helpers/write-order-preload.js): one file a run, in a folder of this test file's.+let orderDir = null;+let orderRuns = 0;+const orderFile = () => path.join(orderDir || (orderDir = makeTempDir('write-order-')), `${orderRuns += 1}.json`);++// Runs `node <args>` and reads what it printed, and the order of its writes (`order`). `queued`: stdout and stderr are descriptors 3 and 4 (the+// preload), held back as described above; `own`: the process's own stdout and stderr, read as they come. `input` is written to stdin (a hook's payload).+function runScript(args, { mode = 'queued', preloads = [], env = {}, cwd, input } = {}) {+ return new Promise((resolve, reject) => {+ const queued = mode === 'queued';+ const record = orderFile();+ const child = spawn(process.execPath, [...(queued ? ['--require', QUEUED] : []), ...preloads.flatMap((p) => ['--require', p]), '--require', ORDER, ...args], {+ cwd,+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1', ...env, WRITE_ORDER_FILE: record },+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe', ...(queued ? ['pipe', 'pipe'] : [])],+ });+ if (input !== undefined) child.stdin.end(input);+ const readers = queued ? [child.stdio[3], child.stdio[4]] : [child.stdout, child.stderr];+ const read = [[], []];+ const own = [];+ readers.forEach((reader, i) => reader.on('data', (chunk) => read[i].push(chunk)));+ if (queued) for (const reader of [child.stdout, child.stderr]) reader.on('data', (chunk) => own.push(chunk));+ let held = queued;+ let timer = null;+ const release = () => {+ if (!held) return;+ held = false;+ clearInterval(timer);+ for (const reader of readers) reader.resume();+ };+ if (held) {+ for (const reader of readers) reader.pause();+ const started = Date.now();+ let seen = -1;+ let quietSince = started;+ timer = setInterval(() => {+ const taken = readers.reduce((sum, reader) => sum + reader.readableLength, 0);+ if (taken !== seen) {+ seen = taken;+ quietSince = Date.now();+ }+ if ((taken > 0 && Date.now() - quietSince >= QUIET_MS) || Date.now() - started >= CAP_MS) release();+ }, 25);+ }+ child.on('exit', release);+ child.on('error', reject);+ child.on('close', (status, signal) => resolve({+ status,+ signal,+ stdout: Buffer.concat(read[0]).toString('utf8'),+ stderr: Buffer.concat(read[1]).toString('utf8'),+ own: Buffer.concat(own).toString('utf8'),+ order: fs.existsSync(record) ? JSON.parse(fs.readFileSync(record, 'utf8')).events : null,+ }));+ });+}++// Runs `task` over `items`, at most `width` at a time — the cases are independent processes, and one after another would take long.+async function eachAtOnce(items, task, width = 6) {+ const results = new Array(items.length);+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(width, items.length) }, async () => {+ while (next < items.length) {+ const index = next++;+ results[index] = await task(items[index], index);+ }+ }));+ return results;+}++// Compares a long text by its length and its two ends first, so that a text cut short fails with a message a person can read.+function assertSameText(actual, expected, what) {+ assert.equal(typeof actual, 'string', `${what}: nothing was read`);+ if (actual === expected) return;+ const ending = (text) => JSON.stringify(text.slice(-60));+ assert.fail(`${what}: ${actual.length} characters arrived of the ${expected.length} expected; it ends with ${ending(actual)} where the text ends with ${ending(expected)}`);+}++// Each stream the process wrote to was made blocking before its first write — the order the fix is, read from the process itself.+function assertBlockingFirst(ran, what) {+ assert.ok(Array.isArray(ran.order), `${what}: the process left no record of its writes`);+ for (const name of ['stdout', 'stderr']) {+ const firstWrite = ran.order.indexOf(`write ${name}`);+ if (firstWrite === -1) continue;+ const blocking = ran.order.indexOf(`blocking ${name}`);+ assert.ok(blocking !== -1 && blocking < firstWrite, `${what}: ${name} is made blocking before it is written to — ${blocking === -1 ? 'it never was' : 'only after'} (${ran.order.slice(0, 8).join(', ')})`);+ }+}++function assertPrinted(ran, expected, what) {+ assert.equal(ran.status, expected.status, `${what}: the exit status (${ran.own || ''}${ran.status === 0 ? '' : ran.stderr.slice(0, 300)})`);+ assertSameText(ran.stdout, expected.stdout, `${what}: stdout`);+ assertSameText(ran.stderr, expected.stderr, `${what}: stderr`);+ assertBlockingFirst(ran, what);+}++// The same script, the same text, through both kinds of stream: the queued run held back must equal the reference, both must hold `text` whole, and+// both must have made each stream blocking before writing to it.+async function assertWholeBothWays(args, { preloads, env, cwd, input, status, stream, text }, what) {+ const [queued, own] = await Promise.all(MODES.map((mode) => runScript(args, { mode, preloads, env, cwd, input })));+ for (const [ran, mode] of [[queued, 'queued'], [own, 'own']]) {+ assert.equal(ran.status, status, `${what}, ${mode}: the exit status (${ran.own}${ran.stderr.slice(0, 300)})`);+ assertBlockingFirst(ran, `${what}, ${mode}`);+ assert.ok(ran[stream].includes(text), `${what}, ${mode}: the whole text is on ${stream} — ${ran[stream].length} characters arrived, and they do not hold the ${text.length}-character text that ends it`);+ assert.ok(ran[stream].endsWith('\n'), `${what}, ${mode}: ${stream} ends with its line break`);+ }+ assertSameText(queued.stdout, own.stdout, `${what}: stdout, queued and own`);+ assertSameText(queued.stderr, own.stderr, `${what}: stderr, queued and own`);+ return { queued, own };+}++// ── check-auth.js: one JSON line on stdout, exit 0 whatever it says ─────────────────────────────────────────────────────────────────────────────────++const CHECK_AUTH = path.join(SCRIPTS, 'check-auth.js');+const CHECK_AUTH_USAGE = 'Usage: node check-auth.js --env <url> [--require-pac]';+const usageBlocker = (flagError) => ({ ok: false, blocker: 'usage', message: `${flagError}. ${CHECK_AUTH_USAGE}`, warnings: [], azUser: null, pacUser: null, envUrl: null, identitiesMatch: false, whoAmI: null });++test('check-auth.js prints a usage blocker that quotes a message of a megabyte whole, and still exits 0 — through both kinds of stream; a mistyped flag exactly as before', async () => {+ const text = hugeFailureText('flag', BIG);+ const expected = { status: 0, stdout: `${JSON.stringify(usageBlocker(text))}\n`, stderr: '' };+ for (const mode of MODES) {+ assertPrinted(await runScript([CHECK_AUTH, '--env', ENV_URL], { mode, preloads: [HUGE], env: { HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: String(BIG) } }), expected, `a megabyte, ${mode}`);+ }+ const argv = ['--env', ENV_URL, '--requir-pac'];+ const small = { status: 0, stdout: `${JSON.stringify(usageBlocker(validateFlags(argv, { known: ['env', 'require-pac'], needValue: ['env'] })))}\n`, stderr: '' };+ for (const mode of MODES) assertPrinted(await runScript([CHECK_AUTH, ...argv], { mode }), small, `--requir-pac, ${mode}`);+});++test('check-auth.js prints a refused WhoAmI whose diagnostic is a megabyte long whole, and still exits 0; a short diagnostic exactly as before', async () => {+ for (const size of [BIG, 12]) {+ const text = hugeFailureText('whoami', size);+ const { queued } = await assertWholeBothWays([CHECK_AUTH, '--env', ENV_URL], { preloads: [FAKE_AUTH], env: { FAKE_WHOAMI_DIAGNOSTIC_SIZE: String(size) }, status: 0, stream: 'stdout', text }, `${size} characters`);+ assert.equal(queued.stdout.indexOf('\n'), queued.stdout.length - 1, 'one line');+ const result = JSON.parse(queued.stdout);+ assert.equal(result.ok, false);+ assert.equal(result.blocker, 'whoami_error');+ assert.equal(result.whoAmI.message, text, 'the service\'s whole diagnostic, as the result has always carried it');+ assert.equal(queued.stderr, '');+ }+});++// ── genpage-plan-provenance.js: a mismatch carries both change lists, exit 3 ────────────────────────────────────────────────────────────────────────++test('genpage-plan-provenance.js prints a mismatch whose two change lists are megabytes long whole, with exit 3; a mismatch of two changes exactly as before', async () => {+ const dir = makeTempDir('provenance-whole-');+ const id = '11111111-2222-3333-4444-555555555555';+ for (const changes of [12000, 2]) {+ const details = Array.from({ length: changes }, (_, i) => `- Change ${i}: update the grid, filter, empty state, row actions, and keyboard navigation for the named field.`).join('\n');+ const written = path.join(dir, `written-${changes}.md`);+ const approved = path.join(dir, `approved-${changes}.txt`);+ fs.writeFileSync(written, `# Genpage Edit Plan\n## File Being Edited\n- **Page ID:** ${id}\n## Requested Changes\n${details}\n`);+ fs.writeFileSync(approved, `## Genpage Edit Plan\n### Current State\n- **File:** ${id}/page.tsx\n### Proposed Changes\n${details}\n- Change the title.\n`);+ const lastChange = `- Change ${changes - 1}: update the grid`;+ const { queued } = await assertWholeBothWays([path.join(SCRIPTS, 'genpage-plan-provenance.js'), 'verify', '--plan', written, '--approved', `@${approved}`], { status: 3, stream: 'stdout', text: 'Change the title.' }, `${changes} changes`);+ const result = JSON.parse(queued.stdout);+ assert.equal(result.ok, false);+ assert.match(result.error, /do not match the approved Proposed Changes/);+ assert.ok(JSON.stringify(result.writtenChanges).includes(lastChange.slice(2)) && JSON.stringify(result.approvedChanges).includes('Change the title.'), 'both lists, whole');+ if (changes > 2) assert.ok(queued.stdout.length > 2 * 1024 * 1024, `megabytes were written (${queued.stdout.length})`);+ }+});++// ── promote-intent-pages.js: every failed page's diagnostics on both streams, exit 3 ─────────────────────────────────────────────────────────────────++test('promote-intent-pages.js prints the diagnostics of a page with forty thousand stray page references whole on both streams, with exit 3; one reference exactly as before', async () => {+ for (const refs of [40000, 1]) {+ const dir = makeTempDir('promote-whole-');+ fs.writeFileSync(path.join(dir, 'app-spec.json'), JSON.stringify({ app: { name: 'Probe' }, pages: [{ key: 'overview', name: 'Overview', source: { kind: 'intent' } }] }));+ fs.writeFileSync(path.join(dir, 'overview.tsx'), `export default function Page(){ return <div>${Array.from({ length: refs }, (_, i) => `<p>PAGEREF_detail${i}</p>`).join('\n')}</div>; }\n`);+ const last = `PAGEREF_detail${refs - 1}`;+ const args = [path.join(SCRIPTS, 'promote-intent-pages.js'), '--spec', `@${path.join(dir, 'app-spec.json')}`, '--working-dir', dir];+ const { queued } = await assertWholeBothWays(args, { status: 3, stream: 'stdout', text: last, cwd: dir }, `${refs} references, stdout`);+ assert.ok(queued.stderr.includes(last) && queued.stderr.endsWith('\n'), `${refs} references: stderr whole too — ${queued.stderr.length} characters`);+ assert.match(queued.stderr, /^promotion aborted — 1 of 1 page\(s\) failed validation; app-spec\.json was NOT modified\n {2}- overview\.tsx: /);+ const result = JSON.parse(queued.stdout);+ assert.equal(result.ok, false);+ assert.deepEqual(result.promoted, []);+ assert.equal(result.failed.length, 1);+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'app-spec.json'), 'utf8')).pages[0].source.kind, 'intent', 'the spec was not touched');+ }+});++// ── check-page-files.js: every file and problem of the plan, exit 3 ─────────────────────────────────────────────────────────────────────────────────++test('check-page-files.js prints the files and problems of a plan of twenty thousand pages whole, with exit 3; a plan of two pages exactly as before', async () => {+ for (const pages of [20000, 2]) {+ const dir = makeTempDir('page-files-whole-');+ const plan = path.join(dir, 'genpage-plan.md');+ fs.writeFileSync(plan, `# Plan\n\n## Pages\n\n| Page | File |\n|---|---|\n${Array.from({ length: pages }, (_, i) => `| Page ${i} | ../escape-${i}.tsx |`).join('\n')}\n`);+ const { queued } = await assertWholeBothWays([path.join(SCRIPTS, 'check-page-files.js'), '--plan', plan, '--working-dir', dir], { status: 3, stream: 'stdout', text: `escape-${pages - 1}.tsx` }, `${pages} pages`);+ const result = JSON.parse(queued.stdout);+ assert.equal(result.ok, false);+ assert.equal(result.files.length, pages);+ assert.equal(result.problems.length, pages, 'a problem for every page that leaves the working directory');+ }+});++// ── genpage-worker-output.js: its result quotes the path it was given ───────────────────────────────────────────────────────────────────────────────++test('genpage-worker-output.js prints a result that quotes the longest path a command line can carry whole, with exit 3; a short one exactly as before', async () => {+ // Bounded by the command line (32,767 characters on Windows): three bytes a character make the longest text the platform allows, some 90 KB —+ // more than a pipe takes at once, though not the megabyte of the other cases.+ const dir = makeTempDir('worker-output-whole-');+ for (const name of [`${'\u20ac'.repeat(30000)}.tsx`, 'missing.tsx']) {+ const file = path.join(dir, name);+ const { queued } = await assertWholeBothWays([path.join(SCRIPTS, 'genpage-worker-output.js'), '--file', file], { status: 3, stream: 'stdout', text: JSON.stringify(file).slice(1, -1) }, `${name.length} characters`);+ const result = JSON.parse(queued.stdout);+ assert.equal(result.ok, false);+ assert.equal(result.filePath, file);+ }+});++// ── Every script's own usage error ────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// The script, the arguments that reach its flag check (a verb where it takes one), and the environment it needs to get there.+const USAGE_CASES = [+ ['add-page-to-solution.js'], ['ai-preflight.js'], ['apps.js', ['list']], ['build-model-app.js'], ['connector.js', ['operations']],+ ['create-connection-reference.js'], ['dataverse-request.js'], ['download-model-app.js'], ['genpage.js', ['list']], ['list-connections.js'],+ ['list-custom-apis.js', [], { GENPAGE_ENABLE_CUSTOM_API: '1' }], ['list-languages.js'], ['list-tables.js'], ['preview-app.js'], ['preview-form.js'],+ ['promote-intent-pages.js'], ['provision-entities.js'], ['provision-solution.js'], ['solution-settings.js', ['template']], ['teardown-model-app.js'],+ ['verify-model-app.js'], ['write-app-spec-doc.js'], ['write-page-plan.js'],+].map(([script, args = [], env = {}]) => ({ script, args, env }));++test('every script prints a usage error that quotes a message of a megabyte whole on stderr, with exit 1 — through both kinds of stream', async () => {+ const text = hugeFailureText('flag', BIG);+ await eachAtOnce(USAGE_CASES, ({ script, args, env }) => assertWholeBothWays([path.join(SCRIPTS, script), ...args], {+ preloads: [HUGE], env: { ...env, HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: String(BIG) }, status: 1, stream: 'stderr', text: `✗ ${text}\n`,+ }, script).then(({ queued }) => assert.equal(queued.stdout, '', `${script}: nothing on stdout`)));+});++test('every script\'s usage error is what it always was: the message, then the usage text, on stderr, with exit 1', async () => {+ const text = hugeFailureText('flag', 10);+ await eachAtOnce(USAGE_CASES, async ({ script, args, env }) => {+ const ran = await runScript([path.join(SCRIPTS, script), ...args], { preloads: [HUGE], env: { ...env, HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: '10' } });+ assert.equal(ran.status, 1, `${script}: ${ran.own}${ran.stderr}`);+ assert.equal(ran.stdout, '', `${script}: nothing on stdout`);+ assert.match(ran.stderr, new RegExp(`^✗ ${text.replace(/[<>]/g, '\\$&')}\\n\\S[^]*\\n$`), `${script}: ${JSON.stringify(ran.stderr.slice(0, 200))}`);+ assertBlockingFirst(ran, script);+ });+});++// ── Every script's last-resort handler ───────────────────────────────────────────────────────────────────────────────────────────────────────────++// A script whose main rejects when its argument parser throws: the handlers of the scripts' own (`Error: <message>` or the message) and, for the+// scripts that hand the error to emitResult, emitResult's.+const THROW_CASES = [+ ['ai-preflight.js'], ['apps.js', ['list']], ['connector.js', ['operations']], ['genpage.js', ['list']], ['genpage-base.js', ['check']], ['genpage-upload.js'],+ ['list-languages.js'], ['list-tables.js'], ['build-model-app.js'], ['download-model-app.js'], ['provision-entities.js'], ['provision-solution.js'],+ ['teardown-model-app.js'], ['verify-model-app.js'], ['write-app-spec-doc.js'],+].map(([script, args = []]) => ({ script, args }));++test('every script\'s last-resort handler prints an error of a megabyte whole on stderr, with exit 1 — through both kinds of stream', async () => {+ const text = hugeFailureText('throw', BIG);+ await eachAtOnce(THROW_CASES, ({ script, args }) => assertWholeBothWays([path.join(SCRIPTS, script), ...args], {+ preloads: [HUGE], env: { HUGE_FAILURE: 'throw', HUGE_FAILURE_SIZE: String(BIG) }, status: 1, stream: 'stderr', text: `${text}\n`,+ }, script).then(({ queued }) => assert.match(queued.stderr, /^(?:Error: )?throw-failure</, `${script}: the message, as the handler always printed it`)));+});++test('every script\'s last-resort handler prints a small error as it always did, with exit 1; solution-settings.js names only the kind of failure', async () => {+ const text = hugeFailureText('throw', 10);+ await eachAtOnce(THROW_CASES, async ({ script, args }) => {+ const ran = await runScript([path.join(SCRIPTS, script), ...args], { preloads: [HUGE], env: { HUGE_FAILURE: 'throw', HUGE_FAILURE_SIZE: '10' } });+ assert.equal(ran.status, 1, `${script}: ${ran.own}${ran.stderr}`);+ assert.match(ran.stderr, new RegExp(`^(?:Error: )?${text.replace(/[<>]/g, '\\$&')}\\n$`), `${script}: ${JSON.stringify(ran.stderr.slice(0, 200))}`);+ assertBlockingFirst(ran, script);+ });+ const settings = await runScript([path.join(SCRIPTS, 'solution-settings.js'), 'template'], { preloads: [HUGE], env: { HUGE_FAILURE: 'throw', HUGE_FAILURE_SIZE: String(BIG) } });+ assertPrinted(settings, { status: 1, stdout: '', stderr: 'Error: solution-settings.js failed unexpectedly (Error).\n' }, 'solution-settings.js');+});++// ── The hooks' messages ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('validate-icon-imports.js blocks a page that imports sixty thousand unverified icons with its whole message, exit 2; one unverified icon as before', async () => {+ for (const icons of [60000, 1]) {+ const dir = makeTempDir('icon-hook-whole-');+ const names = Array.from({ length: icons }, (_, i) => `NotAVerifiedIcon${i}Regular`);+ const content = `import * as React from 'react';\nimport { ${names.join(', ')} } from '@fluentui/react-icons';\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;\n`;+ const input = JSON.stringify({ tool_name: 'Write', tool_input: { file_path: path.join(dir, 'page.tsx'), content }, cwd: dir });+ const { queued } = await assertWholeBothWays([path.join(HOOKS, 'validate-icon-imports.js')], { input, cwd: dir, status: 2, stream: 'stderr', text: ` - ${names[icons - 1]}\n` }, `${icons} icons`);+ assert.match(queued.stderr, new RegExp(`^\\[model-apps\\] The write was blocked: it imported ${icons} icon name\\(s\\)`));+ assert.equal(queued.stdout, '');+ }+});++test('validate-write-safety.js flags a write outside the project whose path is a megabyte long with its whole message, exit 1; a short path as before', async () => {+ for (const size of [BIG, 10]) {+ const dir = makeTempDir('write-safety-whole-');+ fs.writeFileSync(path.join(dir, 'app-spec.json'), '{}');+ const target = path.join(path.parse(dir).root, `outside-${'p'.repeat(size)}.tsx`);+ const input = JSON.stringify({ tool_name: 'Write', tool_input: { file_path: target, content: '' }, cwd: dir });+ const { queued } = await assertWholeBothWays([path.join(HOOKS, 'validate-write-safety.js')], { input, cwd: dir, status: 1, stream: 'stderr', text: `targeted "${target}", which is outside your project folder` }, `${size} characters`);+ assert.match(queued.stderr, /^\[model-apps\] Heads up: a model-apps Write targeted "/);+ assert.match(queued.stderr, /Silence with MODEL_APPS_SKIP_WRITE_GUARD=1 or MODEL_APPS_DISABLE_HOOKS=1\.\n$/);+ }+});++// ── launch-playwright-mcp.js: a server that cannot be started ────────────────────────────────────────────────────────────────────────────────────++// A stand-in for a pipe whose reader is reading but has not caught up: a write puts at most `capacity` characters in the pipe at once and queues the+// rest for a later turn of the event loop — unless the handle was made blocking, when the write returns with all of it taken.+function queuingPipe(capacity = 64 * 1024) {+ const pipe = { written: '', taken: '', queued: '', blocking: false };+ pipe.stream = {+ _handle: { setBlocking(flag) { pipe.blocking = flag === true; return 0; } },+ write(chunk) {+ const text = String(chunk);+ pipe.written += text;+ if (pipe.queued) {+ pipe.queued += text;+ } else {+ const now = pipe.blocking ? text : text.slice(0, capacity);+ pipe.taken += now;+ pipe.queued = text.slice(now.length);+ if (pipe.queued) setImmediate(() => { pipe.taken += pipe.queued; pipe.queued = ''; });+ }+ return !pipe.queued;+ },+ };+ return pipe;+}++test('launch-playwright-mcp.js reports a server that cannot be started with its whole message before it exits 1 — in this process, over a pipe that queues what it cannot take at once', () => {+ const { launch } = require('../launch-playwright-mcp.js');+ for (const size of [BIG, 10]) {+ const message = hugeFailureText('spawn', size);+ const err = queuingPipe();+ const out = queuingPipe();+ const saved = { stdout: Object.getOwnPropertyDescriptor(process, 'stdout'), stderr: Object.getOwnPropertyDescriptor(process, 'stderr'), exit: process.exit };+ const END = new Error('process.exit');+ let ended;+ Object.defineProperty(process, 'stdout', { configurable: true, enumerable: true, get: () => out.stream });+ Object.defineProperty(process, 'stderr', { configurable: true, enumerable: true, get: () => err.stream });+ process.exit = (code) => { ended = { code, taken: err.taken }; throw END; };+ try {+ assert.throws(() => launch({ browser: 'chrome', spawnFn: () => { throw new Error(message); } }), (e) => e === END);+ } finally {+ Object.defineProperty(process, 'stdout', saved.stdout);+ Object.defineProperty(process, 'stderr', saved.stderr);+ process.exit = saved.exit;+ }+ assert.equal(ended.code, 1);+ assert.equal(ended.taken, `Failed to launch Playwright MCP server: ${message}\n`, `${size} characters: the whole message was taken before process.exit`);+ }+});diff --git a/plugins/model-apps/scripts/tests/provision-entities.test.js b/plugins/model-apps/scripts/tests/provision-entities.test.jsindex 5a4276189..374656e82 100644--- a/plugins/model-apps/scripts/tests/provision-entities.test.js+++ b/plugins/model-apps/scripts/tests/provision-entities.test.js@@ -191,9 +191,10 @@ test('apply surfaces fallback metadata for existing columns and relationships',d.provision.fetchEntityMetadata = async (logical) => ({logicalName: logical,entitySetName: `${logical}s`,+ // The SDK's projection rows: the other table and its attribute; an existing 1:N is skipped only when they say which one it is.relationships: [- { schemaName: 'cr_parent_children' },- { schemaName: 'cr_parent_child_nn' },+ { schemaName: 'cr_parent_children', type: 'OneToMany', relatedEntity: 'cr_child', relatedAttribute: 'cr_parentid' },+ { schemaName: 'cr_parent_child_nn', type: 'ManyToMany', relatedEntity: 'cr_child', relatedAttribute: '' },],});@@ -202,7 +203,10 @@ test('apply surfaces fallback metadata for existing columns and relationships',assert.deepStrictEqual(r.columns, [{ table: 'cr_parent', schemaName: 'cr_code', logicalName: 'cr_code' }]);assert.deepStrictEqual(r.relationships, [{ kind: '1n', schemaName: 'cr_parent_children' },- { kind: 'nn', schemaName: 'cr_parent_child_nn' },+ // The projection lists the N:N but says nothing of its intersect table, so it cannot show which N:N the name belongs to: the build tries the create,+ // as it does for any relationship it could not prove. A real environment answers that create with a collision and the relationship is read then+ // (relationship-identity.test.js); this double has no collision, so the create succeeds.+ { kind: 'nn', schemaName: 'cr_parent_child_nn', metadataId: 'rel-cr_parent_child_nn' },]);assert.ok(!d.calls.includes('createColumn'), 'existing columns are not recreated');});diff --git a/plugins/model-apps/scripts/tests/relationship-identity.test.js b/plugins/model-apps/scripts/tests/relationship-identity.test.jsnew file mode 100644index 000000000..d763c901b--- /dev/null+++ b/plugins/model-apps/scripts/tests/relationship-identity.test.js@@ -0,0 +1,929 @@+'use strict';+// A relationship is called the one the spec declares — reused by the build, present for verify — only when the+// environment's answer states its whole identity: its schema name, its type, both of its tables and, for a 1:N, the+// lookup column, for an N:N the intersect table and the column each table has in it. A part the answer leaves out is+// not "nothing contradicts": it is a part nobody checked, and a relationship whose name matches while its ends are+// unstated has not been shown to be the declared one.+//+// The inputs are the shapes a SUCCESSFUL answer takes with part of that missing: a collection row without its+// referencing table and lookup (for an N:N, without its intersect table), and a typed read that answers 200 with an+// empty body (or without the intersect table) after a create collided on the name; and, for an N:N, a complete answer+// on another intersect table than the spec names. The first group is the rule itself; the next groups drive the build,+// the dry run and verify with the fakes those shapes need; the last runs the real vendored bundle over a stub transport.+const { test } = require('node:test');+const assert = require('node:assert');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { makeRunner, provisionDataModel, relationshipExists } = require('../lib/entity-provision.js');+const { compareRelationship, sameRelationship } = require('../lib/relationship-metadata.js');+const { annotateLivePlan } = require('../lib/sdk-build.js');+const { verifySpec } = require('../lib/verify-spec.js');+const { readerFor } = require('../verify-model-app.js');+const { isTransientHalt } = require('../build-model-app.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const SCHEMA = 'contoso_project_contoso_task';++const ONE_TO_MANY = {+ type: 'OneToMany', schemaName: SCHEMA, referenced: 'contoso_project', referencing: 'contoso_task',+ lookup: { schemaName: 'contoso_ProjectId', displayName: 'Project' },+};+const MANY_TO_MANY = { type: 'ManyToMany', schemaName: SCHEMA, entity1: 'contoso_project', entity2: 'contoso_task' };+// The same N:N with the intersect table the spec names (`intersectEntityName`). The SDK creates the intersect table under that name, and+// under the relationship's own lower-cased schema name when the spec names none.+const INTERSECT = 'contoso_project_task_links';+const MANY_TO_MANY_LINKED = { ...MANY_TO_MANY, intersectEntityName: INTERSECT };+const HOLDER_1N = {+ schemaName: SCHEMA, type: 'OneToMany', referencedEntity: 'contoso_project', referencingEntity: 'contoso_task', referencingAttribute: 'contoso_projectid',+};+const HOLDER_NN = {+ schemaName: SCHEMA, type: 'ManyToMany', entity1: 'contoso_task', entity2: 'contoso_project',+ intersectEntityName: INTERSECT, entity1IntersectAttribute: 'contoso_taskid', entity2IntersectAttribute: 'contoso_projectid',+};++const specOf = (...relationships) => ({ solution: { uniqueName: 'Offline', publisherPrefix: 'contoso' }, entities: [], relationships });++// ── 1. The rule ─────────────────────────────────────────────────────────────────────────────────────────────────++test('identity: a complete holder is the same relationship whatever its case, and an N:N whichever order its tables come in', () => {+ const shouting = { schemaName: SCHEMA.toUpperCase(), type: 'OneToMany', referencedEntity: 'CONTOSO_PROJECT', referencingEntity: 'Contoso_Task', referencingAttribute: 'CONTOSO_PROJECTID' };+ assert.strictEqual(sameRelationship(ONE_TO_MANY, shouting), true);+ assert.strictEqual(sameRelationship(MANY_TO_MANY, HOLDER_NN), true, 'the pair is unordered');+ assert.deepStrictEqual(compareRelationship(ONE_TO_MANY, shouting), { state: 'same', missing: [] });+ assert.deepStrictEqual(compareRelationship(MANY_TO_MANY, HOLDER_NN), { state: 'same', missing: [] });+});++test('identity: a part the holder does not state leaves the relationship unproven — each part, whether missing, empty or null', () => {+ const cases = [+ [ONE_TO_MANY, HOLDER_1N, 'schemaName', 'schema name'],+ [ONE_TO_MANY, HOLDER_1N, 'referencedEntity', 'referenced table'],+ [ONE_TO_MANY, HOLDER_1N, 'referencingEntity', 'referencing table'],+ [ONE_TO_MANY, HOLDER_1N, 'referencingAttribute', 'lookup column'],+ [MANY_TO_MANY, HOLDER_NN, 'schemaName', 'schema name'],+ [MANY_TO_MANY, HOLDER_NN, 'entity1', 'first table'],+ [MANY_TO_MANY, HOLDER_NN, 'entity2', 'second table'],+ ];+ // An empty string is what the vendored SDK's own relationship projection writes for a value the answer lacked.+ for (const [declared, holder, field, part] of cases) {+ for (const absent of [undefined, '', null]) {+ const partial = { ...holder, [field]: absent };+ assert.strictEqual(sameRelationship(declared, partial), false, `${field} = ${JSON.stringify(absent)} is no proof`);+ assert.deepStrictEqual(compareRelationship(declared, partial), { state: 'incomplete', missing: [part] }, `${field} = ${JSON.stringify(absent)}`);+ }+ }+});++test('identity: a holder that says nothing about itself is unproven, not "nothing contradicts"', () => {+ for (const holder of [{}, { schemaName: SCHEMA }, { schemaName: SCHEMA, type: 'OneToMany' }, { type: 'OneToMany' }]) {+ assert.strictEqual(sameRelationship(ONE_TO_MANY, holder), false, JSON.stringify(holder));+ assert.strictEqual(compareRelationship(ONE_TO_MANY, holder).state, 'incomplete', JSON.stringify(holder));+ }+ assert.ok(compareRelationship(ONE_TO_MANY, { schemaName: SCHEMA }).missing.includes('relationship type'), 'a name alone does not even say which kind it is');+ assert.strictEqual(sameRelationship(MANY_TO_MANY, { schemaName: SCHEMA, type: 'ManyToMany', entity1: 'contoso_project' }), false, 'an N:N that names one table');+ for (const holder of [null, undefined, SCHEMA]) assert.strictEqual(sameRelationship(ONE_TO_MANY, holder), false);+});++test('identity: a part that differs makes a different relationship, even when other parts are unstated', () => {+ const cases = {+ 'another lookup and no referencing table': { ...HOLDER_1N, referencingAttribute: 'contoso_ownerid', referencingEntity: undefined },+ 'another referenced table and nothing else': { schemaName: SCHEMA, type: 'OneToMany', referencedEntity: 'contoso_other' },+ 'another schema name': { ...HOLDER_1N, schemaName: 'contoso_other_contoso_task' },+ 'an N:N under the name of a 1:N': { schemaName: SCHEMA, type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_task' },+ };+ for (const [what, holder] of Object.entries(cases)) {+ assert.strictEqual(sameRelationship(ONE_TO_MANY, holder), false, what);+ assert.strictEqual(compareRelationship(ONE_TO_MANY, holder).state, 'different', what);+ }+ assert.strictEqual(compareRelationship(MANY_TO_MANY, { schemaName: SCHEMA, type: 'ManyToMany', entity1: 'contoso_tag' }).state, 'different', 'a table the declared pair does not have');+ assert.strictEqual(compareRelationship(MANY_TO_MANY, { ...HOLDER_NN, entity2: 'contoso_tag' }).state, 'different');+});++test('identity: an N:N is compared on the tables each side states, and a self-referencing one names its table twice', () => {+ const self = { type: 'ManyToMany', schemaName: 'contoso_item_contoso_item', entity1: 'contoso_item', entity2: 'contoso_item' };+ const held = {+ schemaName: 'contoso_item_contoso_item', type: 'ManyToMany', entity1: 'Contoso_Item', entity2: 'contoso_item',+ intersectEntityName: 'contoso_item_contoso_item', entity1IntersectAttribute: 'contoso_itemidone', entity2IntersectAttribute: 'contoso_itemidtwo',+ };+ assert.strictEqual(sameRelationship(self, held), true);+ assert.strictEqual(compareRelationship(self, { ...held, entity2: 'contoso_other' }).state, 'different');+ // A declaration that names one table is held to that one, and the holder still has to state both of its own.+ const named = { type: 'ManyToMany', schemaName: SCHEMA, entity1: 'contoso_project' };+ assert.strictEqual(compareRelationship(named, HOLDER_NN).state, 'same');+ assert.strictEqual(compareRelationship({ ...named, entity1: 'contoso_tag' }, HOLDER_NN).state, 'different');+ assert.deepStrictEqual(compareRelationship(named, { ...HOLDER_NN, entity1: undefined }), { state: 'incomplete', missing: ['first table'] });+});++test('identity: an N:N states its intersect table and the column each table has in it, or it is unproven — each part, whether missing, empty or null', () => {+ const parts = [+ ['intersectEntityName', 'intersect table'],+ ['entity1IntersectAttribute', 'first intersect column'],+ ['entity2IntersectAttribute', 'second intersect column'],+ ];+ // Whether or not the spec names an intersect table: the answer has to state its own.+ for (const declared of [MANY_TO_MANY, MANY_TO_MANY_LINKED]) {+ for (const [field, part] of parts) {+ for (const absent of [undefined, '', null]) {+ const partial = { ...HOLDER_NN, [field]: absent };+ assert.strictEqual(sameRelationship(declared, partial), false, `${field} = ${JSON.stringify(absent)} is no proof`);+ assert.deepStrictEqual(compareRelationship(declared, partial), { state: 'incomplete', missing: [part] }, `${field} = ${JSON.stringify(absent)}`);+ }+ }+ }+ // What the narrow reads used to ask for — the name and the two tables — is not the whole identity of an N:N.+ const bare = { schemaName: SCHEMA, type: 'ManyToMany', entity1: 'contoso_task', entity2: 'contoso_project' };+ assert.deepStrictEqual(compareRelationship(MANY_TO_MANY_LINKED, bare), { state: 'incomplete', missing: ['intersect table', 'first intersect column', 'second intersect column'] });+ assert.strictEqual(sameRelationship(MANY_TO_MANY_LINKED, bare), false);+});++test('identity: an N:N on another intersect table than the one the spec names is a different relationship, whatever else the answer leaves out', () => {+ const other = { ...HOLDER_NN, intersectEntityName: 'contoso_other_links' };+ assert.strictEqual(sameRelationship(MANY_TO_MANY_LINKED, other), false);+ assert.deepStrictEqual(compareRelationship(MANY_TO_MANY_LINKED, other), { state: 'different', missing: [] });+ // A contradiction is a proof, whatever else is unstated.+ const sparse = { schemaName: SCHEMA, type: 'ManyToMany', intersectEntityName: 'contoso_other_links' };+ assert.strictEqual(compareRelationship(MANY_TO_MANY_LINKED, sparse).state, 'different');+ // The platform lower-cases the name of a table, so the comparison does not tell cases apart.+ assert.strictEqual(compareRelationship(MANY_TO_MANY_LINKED, { ...HOLDER_NN, intersectEntityName: INTERSECT.toUpperCase() }).state, 'same');+ assert.strictEqual(compareRelationship({ ...MANY_TO_MANY, intersectEntityName: 'Contoso_Project_Task_Links' }, HOLDER_NN).state, 'same');+});++test('identity: a spec that names no intersect table is held to none — any intersect table the answer states is the declared relationship', () => {+ // The reference says "intersect auto-named", a download never writes one, and a relationship adopted from the environment (`existing: true`)+ // has the intersect table its maker chose: none of them contradicts a spec that is silent about it.+ for (const intersect of ['contoso_other_links', SCHEMA, 'systemuserroles']) {+ assert.deepStrictEqual(compareRelationship(MANY_TO_MANY, { ...HOLDER_NN, intersectEntityName: intersect }), { state: 'same', missing: [] }, intersect);+ }+ // …and an authored one is the only thing that makes another intersect table a contradiction. Another part still does.+ assert.strictEqual(compareRelationship(MANY_TO_MANY, { ...HOLDER_NN, entity2: 'contoso_tag' }).state, 'different');+});++test('identity: the intersect table is read from the answer however it is spelled, and a 1:N is not asked for one', () => {+ const raw = {+ SchemaName: SCHEMA, RelationshipType: 'ManyToManyRelationship', Entity1LogicalName: 'contoso_task', Entity2LogicalName: 'contoso_project',+ IntersectEntityName: INTERSECT, Entity1IntersectAttribute: 'contoso_taskid', Entity2IntersectAttribute: 'contoso_projectid',+ };+ assert.strictEqual(compareRelationship(MANY_TO_MANY_LINKED, raw).state, 'same');+ assert.strictEqual(compareRelationship(MANY_TO_MANY_LINKED, { ...raw, IntersectEntityName: 'contoso_other_links' }).state, 'different');+ assert.deepStrictEqual(compareRelationship(MANY_TO_MANY_LINKED, { ...raw, IntersectEntityName: undefined }), { state: 'incomplete', missing: ['intersect table'] });+ assert.deepStrictEqual(compareRelationship(ONE_TO_MANY, HOLDER_1N), { state: 'same', missing: [] }, 'a complete 1:N still needs no intersect table');+});++// ── 2. What the environment says ────────────────────────────────────────────────────────────────────────────────+// The three reads the build and verify make of a relationship, in the shapes the platform answers them (a contoso name):+// GET /EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute+// → 200 { "value": [ { "SchemaName": "contoso_project_contoso_task", "ReferencingEntity": "contoso_task", "ReferencingAttribute": "contoso_projectid" } ] }+// GET /RelationshipDefinitions(SchemaName='contoso_project_contoso_task')?$select=SchemaName,RelationshipType+// → 200 { "SchemaName": "contoso_project_contoso_task", "RelationshipType": "OneToManyRelationship" }+// GET /RelationshipDefinitions(SchemaName='contoso_project_contoso_task')/Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute+// → 200 { "SchemaName": "contoso_project_contoso_task", "ReferencedEntity": "contoso_project", "ReferencingEntity": "contoso_task", "ReferencingAttribute": "contoso_projectid" }+// and for an N:N: …/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute+// → 200 { "value": [ { "SchemaName": "contoso_project_contoso_task", "Entity1LogicalName": "contoso_project", "Entity2LogicalName": "contoso_task",+// "IntersectEntityName": "contoso_project_task_links", "Entity1IntersectAttribute": "contoso_projectid", "Entity2IntersectAttribute": "contoso_taskid" } ] }+// RelationshipType "ManyToManyRelationship", and the ManyToManyRelationshipMetadata cast with the same six properties.+const BASE_1N = { SchemaName: SCHEMA, RelationshipType: 'OneToManyRelationship' };+const BASE_NN = { SchemaName: SCHEMA, RelationshipType: 'ManyToManyRelationship' };+const ROW_1N = { SchemaName: SCHEMA, ReferencedEntity: 'contoso_project', ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid' };+const ROW_NN = {+ SchemaName: SCHEMA, Entity1LogicalName: 'contoso_project', Entity2LogicalName: 'contoso_task',+ IntersectEntityName: INTERSECT, Entity1IntersectAttribute: 'contoso_projectid', Entity2IntersectAttribute: 'contoso_taskid',+};+// What a row without its intersect identity looks like: the name and the two tables, and nothing about the table that holds the links.+const ROW_NN_BARE = { SchemaName: SCHEMA, Entity1LogicalName: 'contoso_project', Entity2LogicalName: 'contoso_task' };+const ROW_NN_OTHER = { ...ROW_NN, IntersectEntityName: 'contoso_other_links' };++// An environment: what each collection lists, and what the keyed read of the name and its typed cast answer. A keyed read+// that is not given answers 404, as the platform does for a name it does not hold.+function environment({ oneToMany = [], manyToOne = [], manyToMany = [], base, cast, onRead } = {}) {+ return (url) => {+ if (onRead) { const answer = onRead(url); if (answer) return answer; }+ if (/\/OneToManyRelationships\?/.test(url)) return { status: 200, body: { value: oneToMany } };+ if (/\/ManyToOneRelationships\?/.test(url)) return { status: 200, body: { value: manyToOne } };+ if (/\/ManyToManyRelationships\?/.test(url)) return { status: 200, body: { value: manyToMany } };+ if (/^\/RelationshipDefinitions\(SchemaName='[^']*'\)\?\$select=SchemaName,RelationshipType$/.test(url)) {+ return base ? { status: 200, body: base } : { status: 404, body: { error: { code: '0x80060888', message: 'RelationshipMetadataBase With Id does not exist.' } } };+ }+ if (/^\/RelationshipDefinitions\(SchemaName='[^']*'\)\/Microsoft\.Dynamics\.CRM\./.test(url)) {+ return cast !== undefined ? { status: 200, body: cast } : { status: 404, body: { error: { code: '0x80060888', message: 'does not exist' } } };+ }+ return { status: 200, body: { value: [] } };+ };+}++// The four answers the 1:N build and verify are held to: a complete match, a complete row on another lookup, a row without+// its referencing table and lookup, and a typed read that answers an empty body after the name collided.+const SHAPES = {+ 'complete-same': environment({ oneToMany: [ROW_1N], manyToOne: [ROW_1N], base: BASE_1N, cast: ROW_1N }),+ 'complete-wrong-lookup': environment({ oneToMany: [{ ...ROW_1N, ReferencingAttribute: 'contoso_ownerid' }], manyToOne: [{ ...ROW_1N, ReferencingAttribute: 'contoso_ownerid' }], base: BASE_1N, cast: { ...ROW_1N, ReferencingAttribute: 'contoso_ownerid' } }),+ 'missing-end-and-lookup': (() => {+ const row = { SchemaName: SCHEMA, ReferencedEntity: 'contoso_project' };+ return environment({ oneToMany: [row], manyToOne: [row], base: BASE_1N, cast: row });+ })(),+ 'malformed-cast': environment({ oneToMany: [], manyToOne: [], base: BASE_1N, cast: {} }),+};++// A real answer holds only the properties the request selected (`$select=SchemaName,Entity1LogicalName,…`), so this gives a row only what was+// asked for: a read that leaves a property out of its select can never be told it. The N:N fakes below go through it, because the whole of+// an N:N's identity has to be ASKED for — a fake that handed over the full row whatever was selected would pass a build that never asked.+function selecting(answer) {+ return (url) => {+ const reply = answer(url);+ const asked = /[?&]\$select=([^&]*)/.exec(url);+ if (!asked || !reply || reply.status !== 200) return reply;+ const keep = new Set(asked[1].split(','));+ const only = (row) => (row && typeof row === 'object' ? Object.fromEntries(Object.entries(row).filter(([key]) => keep.has(key))) : row);+ const body = reply.body;+ return { ...reply, body: body && Array.isArray(body.value) ? { ...body, value: body.value.map(only) } : only(body) };+ };+}++// The answers the N:N build and verify are held to, each on both ways a holder is read: from the collection of its table (`row`), and from+// the keyed read of its name and its typed cast, which is what the build falls back on after its create collided (`cast`).+const nnEnvironment = (row, how) => selecting(environment(how === 'row' ? { manyToMany: [row], base: BASE_NN, cast: row } : { base: BASE_NN, cast: row }));+const NN_SHAPES = {+ 'complete-row': nnEnvironment(ROW_NN, 'row'),+ 'complete-cast': nnEnvironment(ROW_NN, 'cast'),+ 'missing-intersect-row': nnEnvironment(ROW_NN_BARE, 'row'),+ 'missing-intersect-cast': nnEnvironment(ROW_NN_BARE, 'cast'),+ 'wrong-intersect-row': nnEnvironment(ROW_NN_OTHER, 'row'),+ 'wrong-intersect-cast': nnEnvironment(ROW_NN_OTHER, 'cast'),+};++// The build's data-model step over fakes whose create ALWAYS collides on the name, so that a relationship the probe could+// not prove has only its re-read to be reused by. `reads` is every request path the build made, `creates` every create it tried.+async function runBuild({ spec, answer, sleeps = [] }) {+ const events = [];+ const reads = [];+ const creates = [];+ const sdk = {+ createRelationship: async (o) => {+ creates.push(o.schemaName);+ const err = new Error('Relationship with the same name already exists');+ err.statusCode = 409;+ throw err;+ },+ };+ const provision = {+ findTables: async () => [],+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: `${l}s`, relationships: [] }),+ dataverse: { get: async (url) => { reads.push(url); return answer(url); } },+ };+ let result;+ let error;+ try {+ result = await provisionDataModel({ sdk, provision, runner: makeRunner({ emit: (e) => events.push(e), total: 8 }), spec, apply: true, sleep: async (ms) => { sleeps.push(ms); } });+ } catch (e) { error = e; }+ return { result, error, events, reads, creates, sleeps };+}+const reused = (run) => run.events.some((e) => e.status === 'skip' && /\(exists\)/.test(e.label));++// ── 3. The build ────────────────────────────────────────────────────────────────────────────────────────────────++test('build: a complete matching relationship is reused, proven by its own row, and nothing is created', async () => {+ const run = await runBuild({ spec: specOf(ONE_TO_MANY), answer: SHAPES['complete-same'] });+ assert.strictEqual(run.error, undefined);+ assert.ok(reused(run), JSON.stringify(run.events));+ assert.deepStrictEqual(run.creates, []);+ // The healthy path costs what it always did: one narrow collection read — no re-read of the relationship, no create.+ assert.deepStrictEqual(run.reads, ["/EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute"]);+});++test('build: a complete relationship on another lookup halts — the name is held by a different relationship', async () => {+ const run = await runBuild({ spec: specOf(ONE_TO_MANY), answer: SHAPES['complete-wrong-lookup'] });+ assert.ok(run.error);+ assert.strictEqual(run.error.code, 'relationship-name-taken');+ assert.match(run.error.message, /already used by 1:N contoso_project -> contoso_task \(lookup contoso_ownerid\)/);+ assert.strictEqual(isTransientHalt(run.error), false);+ assert.deepStrictEqual(run.creates, []);+});++test('build: a relationship whose row leaves out its referencing table and lookup is not reused — the exact read is no better, so the build halts', async () => {+ const run = await runBuild({ spec: specOf(ONE_TO_MANY), answer: SHAPES['missing-end-and-lookup'] });+ assert.ok(run.error, 'a relationship nobody could identify must not be skipped as reused');+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.match(run.error.message, /relationship schema name 'contoso_project_contoso_task' already exists, but the environment's answer for it is incomplete/);+ assert.match(run.error.message, /does not state its referencing table and its lookup column/);+ assert.match(run.error.message, /declared 1:N contoso_project -> contoso_task \(lookup contoso_projectid\)/);+ assert.ok(run.reads.some((u) => /OneToManyRelationshipMetadata/.test(u)), 'the relationship was re-read before the build gave up');+ assert.strictEqual(isTransientHalt(run.error), false, 'a run again reads the same answer');+ assert.strictEqual(run.error.cause && run.error.cause.transient, false);+});++test('build: a typed read that answers 200 with an empty body after the name collided halts — the name alone is not proof', async () => {+ const run = await runBuild({ spec: specOf(ONE_TO_MANY), answer: SHAPES['malformed-cast'] });+ assert.ok(run.error, 'an empty answer is not the declared relationship');+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.deepStrictEqual(run.creates, [SCHEMA], 'the create was tried, collided, and its holder was read');+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete/);+ assert.match(run.error.message, /does not state its schema name, its referenced table, its referencing table and its lookup column/);+ assert.strictEqual(isTransientHalt(run.error), false);+});++test('build: a row that leaves out its ends is completed by a re-read of the relationship, and then reused', async () => {+ const run = await runBuild({+ spec: specOf(ONE_TO_MANY),+ answer: environment({ oneToMany: [{ SchemaName: SCHEMA }], base: BASE_1N, cast: ROW_1N }),+ });+ assert.strictEqual(run.error, undefined, run.error && run.error.message);+ assert.ok(reused(run), JSON.stringify(run.events));+ assert.ok(run.reads.some((u) => /OneToManyRelationshipMetadata/.test(u)), 'the proof came from reading the relationship itself');+});++test('build: an N:N row that names only one of its tables is not reused; its re-read completes it, or the build halts', async () => {+ const half = { SchemaName: SCHEMA, Entity1LogicalName: 'contoso_project' };+ const halted = await runBuild({ spec: specOf({ ...MANY_TO_MANY }), answer: environment({ manyToMany: [half], base: BASE_NN, cast: half }) });+ assert.ok(halted.error, 'half an N:N is not the declared N:N');+ assert.ok(!reused(halted), JSON.stringify(halted.events));+ assert.match(halted.error.message, /does not state its second table/);+ assert.match(halted.error.message, /declared N:N contoso_project <-> contoso_task/);++ const completed = await runBuild({ spec: specOf({ ...MANY_TO_MANY }), answer: environment({ manyToMany: [half], base: BASE_NN, cast: ROW_NN }) });+ assert.strictEqual(completed.error, undefined, completed.error && completed.error.message);+ assert.ok(reused(completed), JSON.stringify(completed.events));+});++test('build N:N: a complete matching N:N is reused, proven by its own row — the one narrow read it always cost, and no create', async () => {+ for (const [what, spec] of [['a spec that names its intersect table', specOf(MANY_TO_MANY_LINKED)], ['a spec that leaves it to the platform', specOf(MANY_TO_MANY)]]) {+ const run = await runBuild({ spec, answer: NN_SHAPES['complete-row'] });+ assert.strictEqual(run.error, undefined, `${what}: ${run.error && run.error.message}`);+ assert.ok(reused(run), `${what}: ${JSON.stringify(run.events)}`);+ assert.deepStrictEqual(run.creates, [], what);+ assert.strictEqual(run.reads.length, 1, `${what}: no re-read and no create — ${run.reads.join(' | ')}`);+ assert.match(run.reads[0], /^\/EntityDefinitions\(LogicalName='contoso_project'\)\/ManyToManyRelationships\?\$select=/);+ }+});++test('build N:N: the narrow reads ask for the whole identity of an N:N — its intersect table and the column each table has in it', async () => {+ // The collection read, and — after a create that collided — the keyed read of the name and its typed cast.+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: NN_SHAPES['complete-cast'] });+ assert.strictEqual(run.error, undefined, run.error && run.error.message);+ const selectOf = (pattern) => {+ const url = run.reads.find((read) => pattern.test(read));+ return url ? url.split('$select=')[1].split(',') : [];+ };+ for (const [read, props] of [['the collection read', selectOf(/ManyToManyRelationships\?/)], ['the typed read', selectOf(/ManyToManyRelationshipMetadata\?/)]]) {+ assert.ok(props.length > 0, `${read} was made`);+ for (const prop of ['SchemaName', 'Entity1LogicalName', 'Entity2LogicalName', 'IntersectEntityName', 'Entity1IntersectAttribute', 'Entity2IntersectAttribute']) {+ assert.ok(props.includes(prop), `${read} asks for ${prop}: ${props.join(',')}`);+ }+ }+});++test('build N:N: a row that does not state its intersect table is not reused — the exact read is no better, so the build halts', async () => {+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: NN_SHAPES['missing-intersect-row'] });+ assert.ok(run.error, 'an N:N whose intersect table nobody stated must not be skipped as reused');+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.deepStrictEqual(run.creates, [SCHEMA], 'the create was tried, collided, and its holder was read');+ assert.match(run.error.message, /relationship schema name 'contoso_project_contoso_task' already exists, but the environment's answer for it is incomplete/);+ assert.match(run.error.message, /does not state its intersect table, its first intersect column and its second intersect column/);+ assert.match(run.error.message, /declared N:N contoso_project <-> contoso_task \(intersect contoso_project_task_links\)/);+ assert.ok(run.reads.some((u) => /ManyToManyRelationshipMetadata/.test(u)), 'the relationship was re-read before the build gave up');+ assert.strictEqual(isTransientHalt(run.error), false, 'a run again reads the same answer');+});++test('build N:N: a typed read that leaves out the intersect table after the name collided halts too — whether or not the spec names one', async () => {+ for (const spec of [specOf(MANY_TO_MANY_LINKED), specOf(MANY_TO_MANY)]) {+ const run = await runBuild({ spec, answer: NN_SHAPES['missing-intersect-cast'] });+ assert.ok(run.error, 'a name alone is not proof');+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.deepStrictEqual(run.creates, [SCHEMA]);+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete \(it does not state its intersect table, its first intersect column and its second intersect column\)/);+ assert.strictEqual(isTransientHalt(run.error), false);+ }+});++test('build N:N: an empty typed read after the name collided halts — the tables alone are not the declared N:N either', async () => {+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: selecting(environment({ base: BASE_NN, cast: {} })) });+ assert.ok(run.error);+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.match(run.error.message, /does not state its schema name, its first table, its second table, its intersect table, its first intersect column and its second intersect column/);+});++test('build N:N: each part of the intersect identity is needed — an answer that leaves out any one of them is not reused', async () => {+ for (const part of ['IntersectEntityName', 'Entity1IntersectAttribute', 'Entity2IntersectAttribute']) {+ const row = { ...ROW_NN };+ delete row[part];+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: nnEnvironment(row, 'row') });+ assert.ok(run.error, `${part} left out`);+ assert.ok(!reused(run), `${part} left out: ${JSON.stringify(run.events)}`);+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete/, part);+ }+});++test('build N:N: a row that leaves out its intersect identity is completed by a re-read of the relationship, and then reused', async () => {+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: selecting(environment({ manyToMany: [ROW_NN_BARE], base: BASE_NN, cast: ROW_NN })) });+ assert.strictEqual(run.error, undefined, run.error && run.error.message);+ assert.ok(reused(run), JSON.stringify(run.events));+ assert.ok(run.reads.some((u) => /ManyToManyRelationshipMetadata/.test(u)), 'the proof came from reading the relationship itself');+});++test('build N:N: an N:N on another intersect table halts — the name is held by a different relationship, and nothing is created', async () => {+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: NN_SHAPES['wrong-intersect-row'] });+ assert.ok(run.error);+ assert.strictEqual(run.error.code, 'relationship-name-taken');+ assert.match(run.error.message, /already used by N:N contoso_project <-> contoso_task \(intersect contoso_other_links\)/);+ assert.match(run.error.message, /the spec declares N:N contoso_project <-> contoso_task \(intersect contoso_project_task_links\)/);+ assert.match(run.error.message, /Set "intersectEntityName" to 'contoso_other_links' \(or leave it out\) to reuse that relationship, or give the declared one an explicit "schemaName" to create another\./);+ assert.strictEqual(isTransientHalt(run.error), false);+ assert.deepStrictEqual(run.creates, []);+});++test('build N:N: the same on the exact read, after the create collided — a complete answer on another intersect table is refused', async () => {+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: NN_SHAPES['wrong-intersect-cast'] });+ assert.ok(run.error);+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.deepStrictEqual(run.creates, [SCHEMA]);+ assert.match(run.error.message, /is already used by N:N contoso_project <-> contoso_task \(intersect contoso_other_links\); the spec declares N:N contoso_project <-> contoso_task \(intersect contoso_project_task_links\)/);+ assert.match(run.error.message, /Set "intersectEntityName" to 'contoso_other_links' \(or leave it out\) to reuse that relationship/);+ assert.strictEqual(isTransientHalt(run.error), false);+});++test('build N:N: an N:N on another intersect table and ANOTHER table is not offered as reusable by naming its intersect table', async () => {+ const elsewhere = { ...ROW_NN_OTHER, Entity2LogicalName: 'contoso_tag' };+ const run = await runBuild({ spec: specOf(MANY_TO_MANY_LINKED), answer: nnEnvironment(elsewhere, 'row') });+ assert.ok(run.error);+ assert.strictEqual(run.error.code, 'relationship-name-taken');+ assert.doesNotMatch(run.error.message, /intersectEntityName/);+ assert.match(run.error.message, /Give it an explicit "schemaName"\./);+});++test('build N:N: a spec that names no intersect table reuses the relationship whichever one it has, as long as the answer states it', async () => {+ // A relationship adopted from the environment (`existing: true`) or made elsewhere has the intersect table its maker chose, and the spec says nothing against it.+ const run = await runBuild({ spec: specOf(MANY_TO_MANY), answer: NN_SHAPES['wrong-intersect-row'] });+ assert.strictEqual(run.error, undefined, run.error && run.error.message);+ assert.ok(reused(run), JSON.stringify(run.events));+ assert.deepStrictEqual(run.creates, []);+ const adopted = await runBuild({ spec: specOf({ ...MANY_TO_MANY, existing: true }), answer: NN_SHAPES['wrong-intersect-cast'] });+ assert.strictEqual(adopted.error, undefined, adopted.error && adopted.error.message);+ assert.ok(reused(adopted), JSON.stringify(adopted.events));+});++test('build: a lookup owner that carries the declared name but not its referenced table halts instead of being skipped', async () => {+ // The name is free on every read of the holder, and then the child's ManyToOne list shows the lookup under the declared name+ // with no ReferencedEntity: the lag case, whose row has to be the declared relationship to be skipped.+ let childReads = 0;+ const run = await runBuild({+ spec: specOf(ONE_TO_MANY),+ answer: environment({+ onRead: (url) => {+ if (/LogicalName='contoso_task'\)\/ManyToOneRelationships\?/.test(url)) {+ childReads += 1;+ return { status: 200, body: { value: childReads < 2 ? [] : [{ SchemaName: SCHEMA, ReferencingAttribute: 'contoso_projectid' }] } };+ }+ return null;+ },+ }),+ });+ assert.ok(run.error, 'a row without its referenced table is not the declared relationship');+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.match(run.error.message, /does not state its referenced table/);+ assert.deepStrictEqual(run.sleeps, [], 'a known lookup owner is not a lag re-read');+});++test('build: a holder that shows up on a later read without its ends halts at once — it is not waited for again', async () => {+ let keyed = 0;+ const run = await runBuild({+ spec: specOf(ONE_TO_MANY),+ answer: environment({+ base: BASE_1N,+ cast: {},+ onRead: (url) => {+ if (!/^\/RelationshipDefinitions\(/.test(url)) return null;+ keyed += 1;+ return keyed === 1 ? { status: 404, body: { error: { code: '0x80060888', message: 'RelationshipMetadataBase With Id does not exist.' } } } : null;+ },+ }),+ });+ assert.ok(run.error, 'an answer that cannot be told from the declared relationship is not proof');+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete/);+ assert.deepStrictEqual(run.sleeps, [2000], 'one wait for the name to show up, none after it did');+});++test('relationshipExists: a row that does not state its ends is inconclusive, a complete one is the relationship, another lookup is a mismatch', async () => {+ const provisionOf = (...rows) => ({ dataverse: { get: async () => ({ status: 200, body: { value: rows } }) } });+ const probe = (provision, declared = ONE_TO_MANY) => relationshipExists(provision, 'contoso_project', SCHEMA, 'OneToMany', { declared });+ assert.strictEqual(await probe(provisionOf({ SchemaName: SCHEMA, ReferencingEntity: 'contoso_task' })), null, 'no lookup');+ assert.strictEqual(await probe(provisionOf({ SchemaName: SCHEMA })), null, 'a name alone');+ assert.strictEqual(await probe(provisionOf({ SchemaName: SCHEMA, ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid' })), true);+ const wrong = await probe(provisionOf({ SchemaName: SCHEMA, ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_ownerid' }));+ assert.strictEqual(wrong && wrong.mismatch, true);+ assert.strictEqual(await probe(provisionOf({ SchemaName: 'contoso_other', ReferencingEntity: 'contoso_task' })), false, 'another name is absent');+});++test('relationshipExists: a probe that names no declared relationship still answers by name alone, as the plan of an item without one does', async () => {+ const provision = { dataverse: { get: async () => ({ status: 200, body: { value: [{ SchemaName: SCHEMA }] } }) } };+ assert.strictEqual(await relationshipExists(provision, 'contoso_project', SCHEMA, 'OneToMany'), true);+});++test('relationshipExists: a projection row that carries no type or ends cannot prove the relationship either', async () => {+ const provision = { fetchEntityMetadata: async () => ({ relationships: [{ schemaName: SCHEMA }] }) };+ assert.strictEqual(await relationshipExists(provision, 'contoso_project', SCHEMA, 'OneToMany', { declared: ONE_TO_MANY }), null);+ const typed = { fetchEntityMetadata: async () => ({ relationships: [{ schemaName: SCHEMA, type: 'OneToMany', relatedEntity: 'contoso_task', relatedAttribute: '' }] }) };+ assert.strictEqual(await relationshipExists(typed, 'contoso_project', SCHEMA, 'OneToMany', { declared: ONE_TO_MANY }), null, 'the SDK writes an empty string for a value it lacked');+ const complete = { fetchEntityMetadata: async () => ({ relationships: [{ schemaName: SCHEMA, type: 'OneToMany', relatedEntity: 'contoso_task', relatedAttribute: 'contoso_projectid' }] }) };+ assert.strictEqual(await relationshipExists(complete, 'contoso_project', SCHEMA, 'OneToMany', { declared: ONE_TO_MANY }), true);+});++test('relationshipExists: an N:N row that does not state its intersect identity is inconclusive, a complete one is the relationship, another intersect table is a mismatch', async () => {+ const provisionOf = (...rows) => ({ dataverse: { get: async () => ({ status: 200, body: { value: rows } }) } });+ const probe = (provision, declared = MANY_TO_MANY_LINKED) => relationshipExists(provision, 'contoso_project', SCHEMA, 'ManyToMany', { declared });+ assert.strictEqual(await probe(provisionOf(ROW_NN_BARE)), null, 'the tables alone');+ assert.strictEqual(await probe(provisionOf({ ...ROW_NN_BARE, IntersectEntityName: INTERSECT })), null, 'the intersect table without its columns');+ assert.strictEqual(await probe(provisionOf({ ...ROW_NN, IntersectEntityName: '' })), null, 'an empty intersect table');+ assert.strictEqual(await probe(provisionOf(ROW_NN)), true);+ assert.strictEqual(await probe(provisionOf(ROW_NN), MANY_TO_MANY), true, 'a spec that names none');+ assert.strictEqual(await probe(provisionOf(ROW_NN_OTHER), MANY_TO_MANY), true, 'a spec that names none is held to none');+ const wrong = await probe(provisionOf(ROW_NN_OTHER));+ assert.strictEqual(wrong && wrong.mismatch, true);+ assert.strictEqual(wrong.holder.intersectEntityName, 'contoso_other_links', 'the holder carries what it stated, for the message');+ assert.strictEqual(await probe(provisionOf({ ...ROW_NN, SchemaName: 'contoso_other' })), false, 'another name is absent');+});++test('relationshipExists: the SDK projection of an N:N says nothing of its intersect table, so it cannot prove an N:N', async () => {+ // fetchEntityMetadata lists an N:N as { schemaName, type: 'ManyToMany', relatedEntity: <the other table>, relatedAttribute: '' }: no intersect table, no columns.+ const projected = { fetchEntityMetadata: async () => ({ relationships: [{ schemaName: SCHEMA, type: 'ManyToMany', relatedEntity: 'contoso_task', relatedAttribute: '' }] }) };+ assert.strictEqual(await relationshipExists(projected, 'contoso_project', SCHEMA, 'ManyToMany', { declared: MANY_TO_MANY }), null);+ assert.strictEqual(await relationshipExists(projected, 'contoso_project', SCHEMA, 'ManyToMany', { declared: MANY_TO_MANY_LINKED }), null);+ const elsewhere = { fetchEntityMetadata: async () => ({ relationships: [{ schemaName: SCHEMA, type: 'ManyToMany', relatedEntity: 'contoso_tag', relatedAttribute: '' }] }) };+ const mismatch = await relationshipExists(elsewhere, 'contoso_project', SCHEMA, 'ManyToMany', { declared: MANY_TO_MANY });+ assert.strictEqual(mismatch && mismatch.mismatch, true, 'a table the declared pair does not have is still a contradiction');+});++// ── 4. The dry run ──────────────────────────────────────────────────────────────────────────────────────────────++async function planOf(answer, declared = ONE_TO_MANY) {+ const plan = [{+ phase: 'data-model',+ label: 'relationship 1:N contoso_project->contoso_task',+ key: { kind: 'relationship', entity: 'contoso_project', name: SCHEMA, relType: declared.type, declared },+ }];+ await annotateLivePlan(plan, { spec: {}, provision: { dataverse: { get: async (url) => answer(url) } } });+ return plan[0];+}++test('dry run: a complete matching relationship reads reuse, from its row or from the exact read', async () => {+ assert.strictEqual((await planOf(SHAPES['complete-same'])).state, 'reuse');+ assert.strictEqual((await planOf(environment({ base: BASE_1N, cast: ROW_1N }))).state, 'reuse', 'the typed collection cannot see it; the exact read does');+});++test('dry run: a relationship the environment answered incompletely is unknown, never reuse', async () => {+ const fromRow = await planOf(SHAPES['missing-end-and-lookup']);+ assert.strictEqual(fromRow.state, 'unknown');+ assert.match(fromRow.stateWhy, /inconclusive/);++ const fromCast = await planOf(SHAPES['malformed-cast']);+ assert.strictEqual(fromCast.state, 'unknown');+ assert.match(fromCast.stateWhy, /schema name 'contoso_project_contoso_task' exists, but the environment's answer for it is incomplete \(it does not state its schema name, its referenced table, its referencing table and its lookup column\)/);++ const holder = await planOf(environment({ base: BASE_1N, cast: { SchemaName: SCHEMA, ReferencedEntity: 'contoso_project' } }));+ assert.strictEqual(holder.state, 'unknown');+ assert.match(holder.stateWhy, /does not state its referencing table and its lookup column/);+});++test('dry run: a complete relationship on another lookup is still unknown and names the holder', async () => {+ const plan = await planOf(SHAPES['complete-wrong-lookup']);+ assert.strictEqual(plan.state, 'unknown');+ assert.match(plan.stateWhy, /already used by 1:N contoso_project -> contoso_task \(lookup contoso_ownerid\), not the declared relationship/);+});++test('dry run N:N: a complete matching N:N reads reuse, from its row or from the exact read', async () => {+ assert.strictEqual((await planOf(NN_SHAPES['complete-row'], MANY_TO_MANY_LINKED)).state, 'reuse');+ assert.strictEqual((await planOf(NN_SHAPES['complete-cast'], MANY_TO_MANY_LINKED)).state, 'reuse', 'the typed collection cannot see it; the exact read does');+ assert.strictEqual((await planOf(NN_SHAPES['wrong-intersect-row'], MANY_TO_MANY)).state, 'reuse', 'a spec that names no intersect table is held to none');+});++test('dry run N:N: an N:N whose intersect identity the environment did not state is unknown, never reuse', async () => {+ const fromRow = await planOf(NN_SHAPES['missing-intersect-row'], MANY_TO_MANY_LINKED);+ assert.strictEqual(fromRow.state, 'unknown');+ assert.match(fromRow.stateWhy, /inconclusive/);++ const fromCast = await planOf(NN_SHAPES['missing-intersect-cast'], MANY_TO_MANY_LINKED);+ assert.strictEqual(fromCast.state, 'unknown');+ assert.match(fromCast.stateWhy, /schema name 'contoso_project_contoso_task' exists, but the environment's answer for it is incomplete \(it does not state its intersect table, its first intersect column and its second intersect column\)/);+ assert.strictEqual((await planOf(NN_SHAPES['missing-intersect-cast'], MANY_TO_MANY)).state, 'unknown', 'whether or not the spec names an intersect table');+});++test('dry run N:N: an N:N on another intersect table is unknown and names the holder', async () => {+ for (const shape of ['wrong-intersect-row', 'wrong-intersect-cast']) {+ const plan = await planOf(NN_SHAPES[shape], MANY_TO_MANY_LINKED);+ assert.strictEqual(plan.state, 'unknown', shape);+ assert.match(plan.stateWhy, /already used by N:N contoso_project <-> contoso_task \(intersect contoso_other_links\), not the declared relationship/, shape);+ }+});++// ── 5. Verify ───────────────────────────────────────────────────────────────────────────────────────────────────++// The reader verify is handed. `rows` is what the child's relationships list gives (the ManyToOne rows read from the+// referencing table, with the table stamped as the referencing end); `holder` is what the exact read of the name gives.+const verifyRead = (rows, holder) => ({+ sitemapXml: async () => '',+ queryRecords: async () => [],+ entityRelationships: async () => rows,+ relationshipHolder: async () => holder,+});+const checkOf = (result) => result.checks.find((c) => c.kind === 'relationship');+const verifyOf = (spec, read) => verifySpec({ ...spec, app: { name: 'Offline' } }, read);++test('verify: a complete matching relationship passes, and so does one the typed list cannot see but the exact read gives', async () => {+ const listed = await verifyOf(specOf(ONE_TO_MANY), verifyRead([HOLDER_1N], { found: false }));+ assert.strictEqual(listed.ok, true, JSON.stringify(listed.missing));+ const exact = await verifyOf(specOf(ONE_TO_MANY), verifyRead([], { found: true, holder: HOLDER_1N }));+ assert.strictEqual(exact.ok, true, JSON.stringify(exact.missing));+});++test('verify: a complete relationship on another lookup fails and names it', async () => {+ const r = await verifyOf(specOf(ONE_TO_MANY), verifyRead([{ ...HOLDER_1N, referencingAttribute: 'contoso_ownerid' }], { found: false }));+ assert.strictEqual(r.ok, false);+ assert.match(checkOf(r).detail, /exists as 1:N contoso_project -> contoso_task \(lookup contoso_ownerid\)/);+});++test('verify: a row that leaves out its referencing table and lookup does not pass — the check fails and says what is missing', async () => {+ const holder = { schemaName: SCHEMA, type: 'OneToMany', referencedEntity: 'contoso_project' };+ const r = await verifyOf(specOf(ONE_TO_MANY), verifyRead([holder], { found: true, holder: { schemaName: SCHEMA, type: 'OneToMany' } }));+ assert.strictEqual(r.ok, false, 'a relationship that cannot be told from the declared one is not verified');+ const check = checkOf(r);+ assert.strictEqual(check.present, false);+ assert.match(check.detail, /exists, but the environment's answer for it is incomplete \(it does not state its referencing table and its lookup column\)/);+ assert.match(check.detail, /verify cannot prove it is the declared 1:N contoso_project -> contoso_task \(lookup contoso_projectid\)/);+ assert.strictEqual(r.unverified, undefined, 'a check that fails is not listed as one that could not be decided: that list leaves ok and the exit status as they were');+});++test('verify: an exact read that answers only the name and the type does not pass', async () => {+ const r = await verifyOf(specOf(ONE_TO_MANY), verifyRead([], { found: true, holder: { schemaName: SCHEMA, type: 'OneToMany' } }));+ assert.strictEqual(r.ok, false);+ assert.strictEqual(checkOf(r).present, false);+ assert.match(checkOf(r).detail, /incomplete \(it does not state its referenced table, its referencing table and its lookup column\)/);+ const empty = await verifyOf(specOf(ONE_TO_MANY), verifyRead([], { found: true, holder: {} }));+ assert.strictEqual(empty.ok, false);+ assert.match(checkOf(empty).detail, /incomplete \(it does not state its schema name, its relationship type, its referenced table, its referencing table and its lookup column\)/);+});++test('verify: an N:N passes on a complete pair and does not on a row that names one table', async () => {+ const ok = await verifyOf(specOf(MANY_TO_MANY), verifyRead([HOLDER_NN], { found: false }));+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));+ const half = await verifyOf(specOf(MANY_TO_MANY), verifyRead([{ schemaName: SCHEMA, type: 'ManyToMany', entity1: 'contoso_project' }], { found: false }));+ assert.strictEqual(half.ok, false);+ assert.match(checkOf(half).detail, /does not state its second table, its intersect table, its first intersect column and its second intersect column\), so verify cannot prove it is the declared N:N contoso_project <-> contoso_task/);+});++test('verify N:N: a complete N:N passes, from the typed list or from the exact read — and a spec that names no intersect table is held to none', async () => {+ const listed = await verifyOf(specOf(MANY_TO_MANY_LINKED), verifyRead([HOLDER_NN], { found: false }));+ assert.strictEqual(listed.ok, true, JSON.stringify(listed.missing));+ const exact = await verifyOf(specOf(MANY_TO_MANY_LINKED), verifyRead([], { found: true, holder: HOLDER_NN }));+ assert.strictEqual(exact.ok, true, JSON.stringify(exact.missing));+ const other = { ...HOLDER_NN, intersectEntityName: 'contoso_other_links' };+ const silent = await verifyOf(specOf(MANY_TO_MANY), verifyRead([other], { found: false }));+ assert.strictEqual(silent.ok, true, JSON.stringify(silent.missing));+});++test('verify N:N: an N:N that does not state its intersect table fails the check and says what the answer lacked', async () => {+ const bare = { schemaName: SCHEMA, type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_task' };+ for (const [what, read] of [['a row of the typed list', verifyRead([bare], { found: false })], ['the exact read', verifyRead([], { found: true, holder: bare })]]) {+ const r = await verifyOf(specOf(MANY_TO_MANY_LINKED), read);+ assert.strictEqual(r.ok, false, `${what} without its intersect identity is not a proof`);+ assert.strictEqual(checkOf(r).present, false, what);+ assert.match(checkOf(r).detail, /exists, but the environment's answer for it is incomplete \(it does not state its intersect table, its first intersect column and its second intersect column\), so verify cannot prove it is the declared N:N contoso_project <-> contoso_task \(intersect contoso_project_task_links\)/, what);+ assert.strictEqual(r.unverified, undefined, `${what}: a check that fails is not listed as one that could not be decided`);+ }+ for (const field of ['intersectEntityName', 'entity1IntersectAttribute', 'entity2IntersectAttribute']) {+ const r = await verifyOf(specOf(MANY_TO_MANY), verifyRead([{ ...HOLDER_NN, [field]: undefined }], { found: false }));+ assert.strictEqual(r.ok, false, `${field} left out`);+ }+});++test('verify N:N: an N:N on another intersect table fails and names it', async () => {+ const other = { ...HOLDER_NN, intersectEntityName: 'contoso_other_links' };+ for (const [what, read] of [['a row of the typed list', verifyRead([other], { found: false })], ['the exact read', verifyRead([], { found: true, holder: other })]]) {+ const r = await verifyOf(specOf(MANY_TO_MANY_LINKED), read);+ assert.strictEqual(r.ok, false, what);+ assert.match(checkOf(r).detail, /exists as N:N contoso_task <-> contoso_project \(intersect contoso_other_links\)/, what);+ }+});++test('verify: a reader that lists plain names stays a name-only reader, as it always was', async () => {+ const r = await verifyOf(specOf(ONE_TO_MANY), verifyRead([SCHEMA], { found: false }));+ assert.strictEqual(checkOf(r).present, true);+});++// ── 6. The real vendored bundle ─────────────────────────────────────────────────────────────────────────────────+// Over a stub transport, so the SDK's own create (and the error it throws when the name is taken) and its own client (the+// reads the build and verify make of a relationship) are the ones a live run uses.+async function realSdk(answer, { post } = {}) {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const dir = makeTempDir('relationship-identity-');+ const writes = [];+ const reads = [];+ const answered = (a) => ({ status: a.status, headers: {}, body: a.body });+ const httpClient = {+ get: async (url) => {+ // The client sends the origin and the api path before what the plugin asked for; the fakes answer by what it asked for.+ const asked = decodeURIComponent(url).replace(/^https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.\d+/, '');+ reads.push(asked);+ return answered(answer(asked));+ },+ post: async (url, body) => {+ writes.push({ verb: 'POST', url: decodeURIComponent(url), body });+ if (post) return post(decodeURIComponent(url), body);+ return { status: 409, headers: {}, body: { error: { code: '0x80044363', message: 'Relationship with the same name already exists' } } };+ },+ put: async () => ({ status: 204, headers: {}, body: {} }),+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await sdk.initWorkspace();+ return { sdk, writes, reads };+}++async function realBuildOf(answer, spec, options) {+ const { sdk, writes, reads } = await realSdk(answer, options);+ const events = [];+ let error;+ try {+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 8 }), spec, apply: true, preResolvedLanguageCode: 1033, sleep: async () => {} });+ } catch (e) { error = e; }+ return { error, events, writes, reads, sdk };+}+const realBuild = (shape) => realBuildOf(SHAPES[shape], specOf(ONE_TO_MANY));+const realBuildNN = (shape, declared = MANY_TO_MANY_LINKED) => realBuildOf(NN_SHAPES[shape], specOf(declared));++test('REAL BUNDLE: a build reuses the relationship whose row states its whole identity, and creates nothing', async () => {+ const run = await realBuild('complete-same');+ assert.strictEqual(run.error, undefined, run.error && run.error.message);+ assert.ok(reused(run), JSON.stringify(run.events));+ assert.deepStrictEqual(run.writes, []);+});++test('REAL BUNDLE: a build halts on a relationship whose row leaves out its ends — the SDK\'s own collision is read, and the exact read is no better', async () => {+ const run = await realBuild('missing-end-and-lookup');+ assert.ok(run.error, 'the build must not skip a relationship it could not identify');+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.strictEqual(run.writes.filter((w) => /\/RelationshipDefinitions$/.test(w.url)).length, 1, 'the SDK tried the create, and the name was taken');+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete/);+ assert.match(run.error.message, /does not state its referencing table and its lookup column/);+ assert.strictEqual(isTransientHalt(run.error), false);+});++test('REAL BUNDLE: a build halts when the typed read of the holder answers an empty body after the SDK\'s collision', async () => {+ const run = await realBuild('malformed-cast');+ assert.ok(run.error);+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.ok(run.reads.some((r) => /OneToManyRelationshipMetadata/.test(r)), 'the typed read was made');+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete/);+ assert.strictEqual(isTransientHalt(run.error), false);+});++test('REAL BUNDLE: a build halts on a complete relationship under another lookup, as it did', async () => {+ const run = await realBuild('complete-wrong-lookup');+ assert.ok(run.error);+ assert.strictEqual(run.error.code, 'relationship-name-taken');+ assert.deepStrictEqual(run.writes, [], 'a name held by a different relationship is not created over');+});++test('REAL BUNDLE: verify through the real reader passes a complete relationship and fails one whose row leaves out its lookup', async () => {+ const child = (rows) => (url) => (/LogicalName='contoso_task'\)\/ManyToOneRelationships\?/.test(url) ? { status: 200, body: { value: rows } } : { status: 200, body: { value: [] } });+ const spec = { ...specOf(ONE_TO_MANY), app: { name: 'Offline', uniqueName: 'contoso_offline' } };++ const complete = await realSdk(child([{ SchemaName: SCHEMA, ReferencedEntity: 'contoso_project', ReferencingAttribute: 'contoso_projectid' }]));+ const passed = checkOf(await verifySpec(spec, readerFor(complete.sdk, 'contoso_offline', {})));+ assert.strictEqual(passed.present, true, passed.detail);++ const partial = await realSdk(child([{ SchemaName: SCHEMA, ReferencedEntity: 'contoso_project' }]));+ const failed = checkOf(await verifySpec(spec, readerFor(partial.sdk, 'contoso_offline', {})));+ assert.strictEqual(failed.present, false, 'a row that does not say which lookup it is is not the declared relationship');+ assert.match(failed.detail, /incomplete \(it does not state its lookup column\)/);+});++// ── 6b. The real vendored bundle: an N:N and its intersect table ────────────────────────────────────────────────++test('REAL BUNDLE N:N: a build reuses an N:N whose row states its whole identity, and creates nothing', async () => {+ for (const [what, declared] of [['a spec that names its intersect table', MANY_TO_MANY_LINKED], ['a spec that leaves it to the SDK', MANY_TO_MANY]]) {+ const run = await realBuildNN('complete-row', declared);+ assert.strictEqual(run.error, undefined, `${what}: ${run.error && run.error.message}`);+ assert.ok(reused(run), `${what}: ${JSON.stringify(run.events)}`);+ assert.deepStrictEqual(run.writes, [], what);+ assert.strictEqual(run.reads.length, 1, `${what}: the healthy path is one narrow read — ${run.reads.join(' | ')}`);+ }+});++test('REAL BUNDLE N:N: a build halts on a row that leaves out its intersect identity — the SDK\'s own collision is read, and the exact read is no better', async () => {+ const run = await realBuildNN('missing-intersect-row');+ assert.ok(run.error, 'the build must not skip an N:N it could not identify');+ assert.ok(!reused(run), JSON.stringify(run.events));+ const creates = run.writes.filter((w) => /\/RelationshipDefinitions$/.test(w.url));+ assert.strictEqual(creates.length, 1, 'the SDK tried the create, and the name was taken');+ assert.strictEqual(creates[0].body.IntersectEntityName, INTERSECT, 'the SDK sends the intersect table the spec names');+ assert.ok(run.reads.some((r) => /ManyToManyRelationshipMetadata/.test(r)), 'the typed read was made');+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete \(it does not state its intersect table, its first intersect column and its second intersect column\)/);+ assert.strictEqual(isTransientHalt(run.error), false);+});++test('REAL BUNDLE N:N: a build halts when the typed read of the holder leaves out the intersect table after the SDK\'s collision', async () => {+ const run = await realBuildNN('missing-intersect-cast');+ assert.ok(run.error);+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.strictEqual(run.writes.length, 1, 'the SDK tried the create once');+ assert.match(run.error.message, /already exists, but the environment's answer for it is incomplete \(it does not state its intersect table, its first intersect column and its second intersect column\)/);+ assert.strictEqual(isTransientHalt(run.error), false);+});++test('REAL BUNDLE N:N: a build halts on a complete N:N on another intersect table, and creates nothing over it', async () => {+ const run = await realBuildNN('wrong-intersect-row');+ assert.ok(run.error);+ assert.strictEqual(run.error.code, 'relationship-name-taken');+ assert.match(run.error.message, /already used by N:N contoso_project <-> contoso_task \(intersect contoso_other_links\)/);+ assert.deepStrictEqual(run.writes, [], 'a name held by a different relationship is not created over');+});++test('REAL BUNDLE N:N: the typed read of an N:N on another intersect table is refused after the SDK\'s collision', async () => {+ const run = await realBuildNN('wrong-intersect-cast');+ assert.ok(run.error);+ assert.ok(!reused(run), JSON.stringify(run.events));+ assert.strictEqual(run.writes.length, 1, 'the SDK tried the create once');+ assert.match(run.error.message, /is already used by N:N contoso_project <-> contoso_task \(intersect contoso_other_links\)/);+ assert.strictEqual(isTransientHalt(run.error), false);+});++test('REAL BUNDLE N:N: an intersect table the answer gives as null or empty is not stated — by the row and by the typed read alike', async () => {+ for (const absent of [null, '']) {+ for (const how of ['row', 'cast']) {+ const what = `${JSON.stringify(absent)} through the ${how}`;+ const run = await realBuildOf(nnEnvironment({ ...ROW_NN, IntersectEntityName: absent }, how), specOf(MANY_TO_MANY_LINKED));+ assert.ok(run.error, what);+ assert.ok(!reused(run), `${what}: ${JSON.stringify(run.events)}`);+ assert.match(run.error.message, /does not state its intersect table\), so the build cannot tell it from the declared N:N/, what);+ }+ }+});++// A platform that remembers what the SDK created: its POST is recorded, and every later read answers as the platform does for a+// relationship with that identity — the intersect table it was given, and `<table>id` for the column each table has in it, as a custom table's+// key is named. Answers are cut to the properties the read selected, so what a read did not ask for is not told.+function platformThatRemembers() {+ const made = new Map();+ const created = [];+ const rowOf = (body) => ({+ SchemaName: body.SchemaName,+ Entity1LogicalName: body.Entity1LogicalName,+ Entity2LogicalName: body.Entity2LogicalName,+ IntersectEntityName: body.IntersectEntityName,+ Entity1IntersectAttribute: `${body.Entity1LogicalName}id`,+ Entity2IntersectAttribute: `${body.Entity2LogicalName}id`,+ });+ const answer = selecting((url) => {+ const keyed = /^\/RelationshipDefinitions\(SchemaName='([^']*)'\)/.exec(url);+ if (keyed) {+ const row = made.get(keyed[1].toLowerCase());+ if (!row) return { status: 404, body: { error: { code: '0x80060888', message: 'RelationshipMetadataBase With Id does not exist.' } } };+ return { status: 200, body: { ...row, RelationshipType: 'ManyToManyRelationship' } };+ }+ const collection = /LogicalName='([^']*)'\)\/ManyToManyRelationships\?/.exec(url);+ if (collection) return { status: 200, body: { value: [...made.values()].filter((row) => row.Entity1LogicalName === collection[1] || row.Entity2LogicalName === collection[1]) } };+ return { status: 200, body: { value: [] } };+ });+ const post = async (url, body) => {+ created.push(body);+ const key = String(body.SchemaName).toLowerCase();+ if (made.has(key)) return { status: 409, headers: {}, body: { error: { code: '0x80044363', message: 'Relationship with the same name already exists' } } };+ made.set(key, rowOf(body));+ return { status: 204, headers: { 'odata-entityid': 'https://contoso.crm.dynamics.com/api/data/v9.2/RelationshipDefinitions(11111111-2222-3333-4444-555555555555)' }, body: {} };+ };+ return { answer, post, created };+}++test('REAL BUNDLE N:N: an N:N the build made is reused by the next build and passes verify — whether the spec names its intersect table or leaves it to the SDK', async () => {+ for (const [what, declared, intersect] of [['named', MANY_TO_MANY_LINKED, INTERSECT], ['left to the SDK', MANY_TO_MANY, SCHEMA]]) {+ const platform = platformThatRemembers();+ const first = await realBuildOf(platform.answer, specOf(declared), { post: platform.post });+ assert.strictEqual(first.error, undefined, `${what}: ${first.error && first.error.message}`);+ assert.strictEqual(platform.created.length, 1, `${what}: the first build created the relationship`);+ assert.strictEqual(platform.created[0].IntersectEntityName, intersect, `${what}: the intersect table the SDK sent`);++ const second = await realBuildOf(platform.answer, specOf(declared), { post: platform.post });+ assert.strictEqual(second.error, undefined, `${what}: ${second.error && second.error.message}`);+ assert.ok(reused(second), `${what}: ${JSON.stringify(second.events)}`);+ assert.strictEqual(platform.created.length, 1, `${what}: the rebuild created nothing`);+ assert.strictEqual(second.writes.length, 0, what);++ const spec = { ...specOf(declared), app: { name: 'Offline', uniqueName: 'contoso_offline' } };+ const verified = checkOf(await verifySpec(spec, readerFor(second.sdk, 'contoso_offline', {})));+ assert.strictEqual(verified.present, true, `${what}: ${verified.detail}`);+ }+});++test('REAL BUNDLE N:N: verify through the real reader passes a complete N:N, and fails one that leaves out its intersect table or names another', async () => {+ const onProject = (row) => selecting((url) => (/LogicalName='contoso_project'\)\/ManyToManyRelationships\?/.test(url) ? { status: 200, body: { value: [row] } } : { status: 200, body: { value: [] } }));+ const spec = { ...specOf(MANY_TO_MANY_LINKED), app: { name: 'Offline', uniqueName: 'contoso_offline' } };+ const verifyWith = async (row) => checkOf(await verifySpec(spec, readerFor((await realSdk(onProject(row))).sdk, 'contoso_offline', {})));++ const passed = await verifyWith(ROW_NN);+ assert.strictEqual(passed.present, true, passed.detail);++ const bare = await verifyWith(ROW_NN_BARE);+ assert.strictEqual(bare.present, false, 'a row that does not say which intersect table it has is not the declared N:N');+ assert.match(bare.detail, /incomplete \(it does not state its intersect table, its first intersect column and its second intersect column\)/);++ const other = await verifyWith(ROW_NN_OTHER);+ assert.strictEqual(other.present, false);+ assert.match(other.detail, /exists as N:N contoso_project <-> contoso_task \(intersect contoso_other_links\)/);+});diff --git a/plugins/model-apps/scripts/tests/relationship-metadata.test.js b/plugins/model-apps/scripts/tests/relationship-metadata.test.jsindex 7d1652154..9ca74c5cd 100644--- a/plugins/model-apps/scripts/tests/relationship-metadata.test.js+++ b/plugins/model-apps/scripts/tests/relationship-metadata.test.js@@ -28,7 +28,9 @@ function client(routes) {const ONE_TO_MANY_BASE = "/RelationshipDefinitions(SchemaName='contoso_project_contoso_task')?$select=SchemaName,RelationshipType";const ONE_TO_MANY_CAST = "/RelationshipDefinitions(SchemaName='contoso_project_contoso_task')/Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute";const MANY_TO_MANY_BASE = "/RelationshipDefinitions(SchemaName='contoso_project_contoso_tag')?$select=SchemaName,RelationshipType";-const MANY_TO_MANY_CAST = "/RelationshipDefinitions(SchemaName='contoso_project_contoso_tag')/Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata?$select=SchemaName,Entity1LogicalName,Entity2LogicalName";+const MANY_TO_MANY_CAST = "/RelationshipDefinitions(SchemaName='contoso_project_contoso_tag')/Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute";+// The N:N properties beyond its two tables: the table that holds its links and the column each table has in it.+const MANY_TO_MANY_SELECT = 'SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute';test('readRelationshipsOf uses the narrow collection selects and stamps the queried end', async () => {const c = client([@@ -43,9 +45,12 @@ test('readRelationshipsOf uses the narrow collection selects and stamps the querbody: { value: [{ SchemaName: 'contoso_project_contoso_task', ReferencedEntity: 'contoso_project', ReferencingAttribute: 'contoso_projectid' }] },},{- path: "/EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName",+ path: `/EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=${MANY_TO_MANY_SELECT}`,status: 200,- body: { value: [{ SchemaName: 'contoso_project_contoso_tag', Entity1LogicalName: 'contoso_project', Entity2LogicalName: 'contoso_tag' }] },+ body: { value: [{+ SchemaName: 'contoso_project_contoso_tag', Entity1LogicalName: 'contoso_project', Entity2LogicalName: 'contoso_tag',+ IntersectEntityName: 'contoso_project_contoso_tag', Entity1IntersectAttribute: 'contoso_projectid', Entity2IntersectAttribute: 'contoso_tagid',+ }] },},]);const one = await readRelationshipsOf(c, 'contoso_project', 'OneToMany');@@ -54,7 +59,10 @@ test('readRelationshipsOf uses the narrow collection selects and stamps the querassert.deepStrictEqual(one, { ok: true, rows: [{ schemaName: 'contoso_project_contoso_task', type: 'OneToMany', referencedEntity: 'contoso_project', referencingEntity: 'contoso_task', referencingAttribute: 'contoso_projectid' }] });assert.deepStrictEqual(many.rows[0].referencingEntity, 'contoso_task');assert.strictEqual(many.rows[0].referencedEntity, 'contoso_project');- assert.deepStrictEqual(nn.rows[0], { schemaName: 'contoso_project_contoso_tag', type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_tag' });+ assert.deepStrictEqual(nn.rows[0], {+ schemaName: 'contoso_project_contoso_tag', type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_tag',+ intersectEntityName: 'contoso_project_contoso_tag', entity1IntersectAttribute: 'contoso_projectid', entity2IntersectAttribute: 'contoso_tagid',+ });});test('a 404 on the table is an empty read, not a failure', async () => {@@ -66,7 +74,7 @@ test('a 404 on the table is an empty read, not a failure', async () => {test('a quote in a logical name is escaped with odataLit', async () => {const c = client([{ test: () => true, status: 200, body: { value: [] } }]);await readRelationshipsOf(c, "contoso_o'brien", 'ManyToMany');- assert.strictEqual(c.paths[0], "/EntityDefinitions(LogicalName='contoso_o''brien')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName");+ assert.strictEqual(c.paths[0], `/EntityDefinitions(LogicalName='contoso_o''brien')/ManyToManyRelationships?$select=${MANY_TO_MANY_SELECT}`);});test('findRelationshipHolder reads the 1:N cast after the base type', async () => {@@ -83,11 +91,14 @@ test('findRelationshipHolder reads the 1:N cast after the base type', async () =test('findRelationshipHolder reads the N:N cast after the base type', async () => {const c = client([{ path: MANY_TO_MANY_BASE, status: 200, body: { '@odata.type': '#Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata', SchemaName: 'contoso_project_contoso_tag', RelationshipType: 'ManyToManyRelationship' } },- { path: MANY_TO_MANY_CAST, status: 200, body: { SchemaName: 'contoso_project_contoso_tag', Entity1LogicalName: 'contoso_tag', Entity2LogicalName: 'contoso_project' } },+ { path: MANY_TO_MANY_CAST, status: 200, body: { SchemaName: 'contoso_project_contoso_tag', Entity1LogicalName: 'contoso_tag', Entity2LogicalName: 'contoso_project', IntersectEntityName: 'contoso_project_contoso_tag', Entity1IntersectAttribute: 'contoso_tagid', Entity2IntersectAttribute: 'contoso_projectid' } },]);const found = await findRelationshipHolder(c, 'contoso_project_contoso_tag', { candidates: [] });assert.deepStrictEqual(c.paths, [MANY_TO_MANY_BASE, MANY_TO_MANY_CAST]);- assert.strictEqual(describeRelationship(found.holder), 'N:N contoso_tag <-> contoso_project');+ assert.strictEqual(describeRelationship(found.holder), 'N:N contoso_tag <-> contoso_project (intersect contoso_project_contoso_tag)');+ assert.strictEqual(found.holder.intersectEntityName, 'contoso_project_contoso_tag');+ assert.strictEqual(found.holder.entity1IntersectAttribute, 'contoso_tagid');+ assert.strictEqual(found.holder.entity2IntersectAttribute, 'contoso_projectid');});test('a case-sensitive 404 falls back to the candidate collections and finds the other casing', async () => {@@ -199,7 +210,10 @@ test('sameRelationship matches endpoints case-insensitively and rejects a differ{ schemaName: 'contoso_project_contoso_task', type: 'OneToMany', referencedEntity: 'contoso_project', referencingEntity: 'contoso_task', referencingAttribute: 'contoso_projectid' },), false);assert.strictEqual(sameRelationship(- { type: 'ManyToMany', entity1: 'contoso_tag', entity2: 'contoso_project' },- { type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_tag' },+ { type: 'ManyToMany', schemaName: 'contoso_project_contoso_tag', entity1: 'contoso_tag', entity2: 'contoso_project' },+ {+ type: 'ManyToMany', schemaName: 'contoso_project_contoso_tag', entity1: 'contoso_project', entity2: 'contoso_tag',+ intersectEntityName: 'contoso_project_contoso_tag', entity1IntersectAttribute: 'contoso_projectid', entity2IntersectAttribute: 'contoso_tagid',+ },), true);});diff --git a/plugins/model-apps/scripts/tests/result-whole-before-exit.test.js b/plugins/model-apps/scripts/tests/result-whole-before-exit.test.jsnew file mode 100644index 000000000..38b5bd53b--- /dev/null+++ b/plugins/model-apps/scripts/tests/result-whole-before-exit.test.js@@ -0,0 +1,340 @@+'use strict';+// A script prints its result and ends at once — `emitResult` exits right after its writes, and so do the output guard's printer of an error that ends the process and dataverse-request.js — and an agent reads that+// result through a pipe. Node writes to a pipe asynchronously on Linux and macOS, and `process.exit` does not wait for what is still queued (https://nodejs.org/api/process.html#a-note-on-process-io), so a large result+// reached its reader cut short there: the Linux and macOS CI jobs read the 3.5 MB result of output-token-boundary.test.js as a JSON text that ended mid-string. Windows makes a pipe on stdout and stderr synchronous,+// so that test passes there whatever the code does. lib/output-redaction.js → makeWritesBlocking is the fix: the last writes are made blocking first.+//+// These tests check it on every platform:+// - THE ORDER, in real processes (helpers/write-order-preload.js): each process records when it makes stdout or stderr blocking and when it writes+// to them, and each stream it wrote to must have been made blocking before its first write. An order does not depend on the platform, the+// runtime or how fast the reader reads, so this fails on every run for a printer without the call;+// - THE TEXT, in the same processes, whose stdout and stderr are the kind of stream Linux and macOS give a pipe (helpers/queued-stdio-preload.js:+// sockets over descriptors 3 and 4, which Node leaves asynchronous on Windows too) — every branch of emitResult, the guard's printer of a fatal+// error, dataverse-request.js and the 3.5 MB scenario of output-token-boundary.test.js, each with a text of several megabytes — and also over the+// process's own stdout and stderr, which are queued pipes on Linux and macOS. How much of a text a printer without the call loses here depends+// on the runtime and on how fast this process reads: with the code before the fix, on Windows, some branches still arrived whole (a different+// few under Node 20 and Node 22). This half shows what a reader gets; the order is what proves the fix;+// - in this process, with stand-ins for stdout and stderr that take what a pipe takes at once and queue the rest: emitResult has every text it wrote+// taken whole when it calls `process.exit`, and never returns — as deterministic as the order.+// And they pin what must not change: the bytes and exit status of every branch for a small result, and makeWritesBlocking's leaving everything but the handle as it was (the output guard stays on the path).+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { table, longText, ACCENT } = require('./helpers/exit-output-child.js');+const { TOKEN, SECRETS, FOLDED } = require('./helpers/synthetic-token.js');+const { leaksIn } = require('./helpers/token-leaks.js');+const { makeWritesBlocking, guardStream } = require('../lib/output-redaction.js');++const CHILD = path.join(__dirname, 'helpers', 'exit-output-child.js');+const QUEUED = path.join(__dirname, 'helpers', 'queued-stdio-preload.js');+const ORDER = path.join(__dirname, 'helpers', 'write-order-preload.js');+const TOKEN_CHILD = path.join(__dirname, 'helpers', 'token-boundary-child.js');+const DATAVERSE_REQUEST = path.join(__dirname, '..', 'dataverse-request.js');+const AUTH = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');+// 30,000 rows: a text of about 3.5 MB, some fifty times what a pipe takes at once (64 KiB on Linux). 2 rows: a text any pipe takes at once.+const BIG = 30000;+const SMALL = 2;++// How the output reaches its reader: `queued` — the kind of pipe Linux and macOS give a script, on every platform (the preload's sockets over descriptors 3 and 4); `own` — the process's own stdout and stderr (queued+// pipes on Linux and macOS, synchronous ones on Windows).+const MODES = ['queued', 'own'];++// Where each run's record of the order of its writes goes (helpers/write-order-preload.js): one file a run, in a folder of this test file's.+let orderDir = null;+let orderRuns = 0;+const orderFile = () => path.join(orderDir || (orderDir = makeTempDir('write-order-')), `${orderRuns += 1}.json`);++function run(args, mode, env = {}) {+ const queued = mode === 'queued';+ const record = orderFile();+ const result = spawnSync(process.execPath, [...(queued ? ['--require', QUEUED] : []), '--require', ORDER, ...args], {+ stdio: ['ignore', 'pipe', 'pipe', ...(queued ? ['pipe', 'pipe'] : [])],+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1', ...env, WRITE_ORDER_FILE: record },+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ timeout: 120000,+ });+ assert.equal(result.error, undefined, `the process could not be run: ${result.error}`);+ const order = fs.existsSync(record) ? JSON.parse(fs.readFileSync(record, 'utf8')).events : null;+ if (!queued) return { status: result.status, stdout: result.stdout, stderr: result.stderr, order };+ // With the preload, everything the script prints goes to descriptors 3 and 4; what reached 1 and 2 is Node's own (a failure to start), shown if the test fails.+ return { status: result.status, stdout: result.output[3], stderr: result.output[4], own: `${result.stdout}${result.stderr}`, order };+}++// Each stream the process wrote to was made blocking before its first write — the order the fix is, read from the process itself.+function assertBlockingFirst(ran, what) {+ assert.ok(Array.isArray(ran.order), `${what}: the process left no record of its writes`);+ for (const name of ['stdout', 'stderr']) {+ const firstWrite = ran.order.indexOf(`write ${name}`);+ if (firstWrite === -1) continue;+ const blocking = ran.order.indexOf(`blocking ${name}`);+ assert.ok(blocking !== -1 && blocking < firstWrite, `${what}: ${name} is made blocking before it is written to — ${blocking === -1 ? 'it never was' : 'only after'} (${ran.order.slice(0, 8).join(', ')})`);+ }+}++const runScenario = (scenario, rows, mode) => run([CHILD, scenario, JSON.stringify({ rows })], mode);++// What each branch of emitResult prints — the bytes and the status it always printed. `stdout` and `stderr` are exact texts; the ascii branch is checked by what it means (every character escaped, the same document).+const EXPECTED = {+ ok: (rows) => ({ status: 0, stdout: `${JSON.stringify(table(rows))}\n`, stderr: '' }),+ ascii: (rows) => ({ status: 0, document: table(rows, ACCENT), stderr: '' }),+ 'structured-error': (rows) => ({ status: 1, stdout: `${JSON.stringify({ ok: false, error: longText(rows), rows: table(rows) })}\n`, stderr: `${longText(rows)}\n` }),+ 'structured-errors': (rows) => ({ status: 1, stdout: `${JSON.stringify({ ok: false, errors: table(rows) })}\n`, stderr: `Operation completed with ${rows} error(s); see stdout JSON\n` }),+ 'structured-unexplained': (rows) => ({ status: 1, stdout: `${JSON.stringify({ ok: false, rows: table(rows) })}\n`, stderr: 'Operation failed with an unstructured error; see stdout JSON\n' }),+ error: (rows) => ({ status: 1, stdout: '', stderr: `${longText(rows)}\n` }),+ text: (rows) => ({ status: 1, stdout: '', stderr: `${longText(rows)}\n` }),+};++// Compares a long text by its length and its two ends first, so that a text cut short fails with a message a person can read (not the whole of two texts of megabytes).+function assertSameText(actual, expected, what) {+ assert.equal(typeof actual, 'string', `${what}: nothing was read`);+ if (actual === expected) return;+ const ending = (text) => JSON.stringify(text.slice(-60));+ assert.fail(`${what}: ${actual.length} characters arrived of the ${expected.length} written; it ends with ${ending(actual)} where the text ends with ${ending(expected)}`);+}++function assertPrinted(ran, expected, what) {+ assert.equal(ran.status, expected.status, `${what}: the exit status (${ran.own || ''})`);+ assertBlockingFirst(ran, what);+ if (expected.document) {+ assert.ok(ran.stdout.endsWith('\n') && ran.stdout.indexOf('\n') === ran.stdout.length - 1, `${what}: one line, ended by a line break — ${ran.stdout.length} characters arrived`);+ assert.match(ran.stdout, /^[\x00-\x7e]*$/, `${what}: every character above U+007E is escaped`);+ assert.deepEqual(JSON.parse(ran.stdout), expected.document, `${what}: the same document`);+ } else {+ assertSameText(ran.stdout, expected.stdout, `${what}: stdout`);+ }+ assertSameText(ran.stderr, expected.stderr, `${what}: stderr`);+}++// ── emitResult, in a real process ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++for (const scenario of Object.keys(EXPECTED)) {+ test(`emitResult (${scenario}) writes a result of several megabytes whole before the process ends — through a pipe that queues what it cannot take at once, and through the process's own stdout and stderr`, () => {+ for (const mode of MODES) assertPrinted(runScenario(scenario, BIG, mode), EXPECTED[scenario](BIG), `${scenario}, ${mode}`);+ });+}++test('emitResult prints a small result exactly as it always did, with the same exit status, in every branch and through both kinds of stream', () => {+ for (const scenario of Object.keys(EXPECTED)) {+ for (const mode of MODES) assertPrinted(runScenario(scenario, SMALL, mode), EXPECTED[scenario](SMALL), `${scenario}, ${mode}`);+ }+});++// ── An error that ends the process: the output guard prints it ────────────────────────────────────────────────────────────────────────────────────────────────────────++test('an error that ends the process after a token was obtained is printed whole — a message of several megabytes, the token out of it — and the process ends with status 1', () => {+ for (const mode of MODES) {+ for (const rows of [BIG, SMALL]) {+ const ran = runScenario('fatal', rows, mode);+ const what = `${rows} rows, ${mode}`;+ assert.equal(ran.status, 1, `${what}: the status of an error nothing caught (${ran.own || ''})`);+ assertBlockingFirst(ran, what);+ assert.equal(ran.stdout, '', `${what}: nothing on stdout`);+ const head = `Uncaught Error: ${longText(rows)} Rejected bearer <token>\n`;+ assertSameText(ran.stderr.slice(0, head.length), head, `${what}: the message, with the token taken out`);+ assert.match(ran.stderr.slice(head.length), /^ {4}at [^\n]+\n[\s\S]*\n$/, `${what}: then the stack, to its last line — ${ran.stderr.length} characters arrived`);+ assert.deepEqual(leaksIn(ran.stderr, SECRETS), [], `${what}: no part of the token`);+ }+ }+});++// ── The output guard stays on the path ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('the 3.5 MB result of output-token-boundary.test.js — the token in one row — is whole and clean through a pipe that queues what it cannot take at once, as it is on Linux and macOS', () => {+ const dir = makeTempDir('whole-before-exit-');+ const work = path.join(dir, 'work');+ fs.mkdirSync(work);+ const factsFile = path.join(dir, 'facts.json');+ const ran = run([TOKEN_CHILD, 'big', JSON.stringify({ rows: BIG })], 'queued', { TOKEN_BOUNDARY_DIR: work, TOKEN_BOUNDARY_FACTS: factsFile });+ const facts = JSON.parse(fs.readFileSync(factsFile, 'utf8'));+ assert.equal(facts.obtained, true, 'the token was obtained, so the output guard was on the streams');+ assert.equal(ran.status, 0, ran.stderr);+ assertBlockingFirst(ran, 'the 3.5 MB result');+ const escaped = JSON.stringify(FOLDED).slice(1, -1);+ assert.equal(ran.stdout.length, facts.bytes - escaped.length + '<token>'.length + 1, `the whole text, with only the token changed — ${ran.stdout.length} characters arrived of ${facts.bytes}`);+ assert.deepEqual(leaksIn(ran.stdout, SECRETS), []);+ const printed = JSON.parse(ran.stdout);+ assert.equal(printed.length, BIG, 'every row');+ assert.equal(printed[BIG / 2].note, 'Rejected bearer <token>');+});++// ── dataverse-request.js prints its answer itself ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// The real script, with the request replaced by an answer of `rows` rows (or a failure whose message is that long), run as a process. The request is the one thing replaced: every other export of+// lib/dataverse-auth.js is the real one, and lib/output-redaction.js is loaded as it is.+function runDataverseRequest(rows, { fail = false, mode = 'queued' } = {}) {+ const code = `+ const Module = require('node:module');+ const realAuth = require(${JSON.stringify(AUTH)});+ const { table, longText } = require(${JSON.stringify(CHILD)});+ const originalLoad = Module._load;+ Module._load = function load(request, parent, isMain) {+ if (Module._resolveFilename(request, parent, isMain) === ${JSON.stringify(AUTH)}) {+ return { ...realAuth, dataverseRequest: async () => {+ if (${fail}) throw new Error(longText(${rows}));+ return { status: 200, data: { value: table(${rows}) } };+ } };+ }+ return originalLoad.apply(this, arguments);+ };+ process.argv = [process.execPath, ${JSON.stringify(DATAVERSE_REQUEST)}, 'https://contoso.crm.dynamics.com', 'GET', 'accounts'];+ require(${JSON.stringify(DATAVERSE_REQUEST)});+ `;+ return run(['-e', code], mode);+}++test('dataverse-request.js prints an answer of several megabytes whole before it exits, and a failure as long whole on stderr — through both kinds of stream; a small one exactly as before', () => {+ for (const mode of MODES) {+ for (const rows of [BIG, SMALL]) {+ const what = `${rows} rows, ${mode}`;+ const answered = runDataverseRequest(rows, { mode });+ assert.equal(answered.status, 0, `${what}: ${answered.stderr}${answered.own || ''}`);+ assertBlockingFirst(answered, `${what}: the answer`);+ assertSameText(answered.stdout, `${JSON.stringify({ status: 200, data: { value: table(rows) } })}\n`, `${what}: the answer`);+ assert.equal(answered.stderr, '', `${what}: nothing on stderr`);+ const failed = runDataverseRequest(rows, { fail: true, mode });+ assert.equal(failed.status, 1, `${what}: a failure exits 1`);+ assertBlockingFirst(failed, `${what}: the failure`);+ assert.equal(failed.stdout, '', `${what}: nothing on stdout`);+ assertSameText(failed.stderr, `${longText(rows)}\n`, `${what}: the failure`);+ }+ }+});++// ── In this process: the order of the writes and the exit ────────────────────────────────────────────────────────────────────────────────────────────────────────────++// A stand-in for a pipe whose reader is reading but has not caught up: a write puts at most `capacity` characters in the pipe at once and queues the rest for a later turn of the event loop — unless the handle was made+// blocking, when the write returns with all of it taken (https://docs.libuv.org/en/v1.x/stream.html#c.uv_stream_set_blocking). A write made while something is queued waits behind it, blocking or not, as a real+// stream's does. `taken` is what the reader can read; `written` is what the process wrote.+function queuingPipe(capacity = 64 * 1024) {+ const pipe = { written: '', taken: '', queued: '', blocking: false, waiting: [] };+ const drain = () => {+ pipe.taken += pipe.queued;+ pipe.queued = '';+ for (const callback of pipe.waiting.splice(0)) callback();+ };+ pipe.stream = {+ _handle: { setBlocking(flag) { pipe.blocking = flag === true; return 0; } },+ write(chunk, encoding, callback) {+ const text = String(chunk);+ const done = typeof encoding === 'function' ? encoding : callback;+ pipe.written += text;+ if (!pipe.queued) {+ const now = pipe.blocking ? text : text.slice(0, capacity);+ pipe.taken += now;+ pipe.queued = text.slice(now.length);+ if (pipe.queued) setImmediate(drain);+ } else {+ pipe.queued += text;+ }+ if (typeof done === 'function') {+ if (pipe.queued) pipe.waiting.push(done);+ else process.nextTick(done);+ }+ return !pipe.queued;+ },+ };+ return pipe;+}++// Runs `fn` with the stand-ins as this process's stdout and stderr, and with a `process.exit` that records what the reader had been given when it was called — and then throws, so that nothing after it runs, as+// nothing runs after the real one. Everything is put back however `fn` ends.+function endedWith(fn) {+ const out = queuingPipe();+ const err = queuingPipe();+ const saved = { stdout: Object.getOwnPropertyDescriptor(process, 'stdout'), stderr: Object.getOwnPropertyDescriptor(process, 'stderr'), exit: process.exit };+ const END = new Error('process.exit');+ const ended = { code: undefined, returned: false, takenAtExit: undefined };+ Object.defineProperty(process, 'stdout', { configurable: true, enumerable: true, get: () => out.stream });+ Object.defineProperty(process, 'stderr', { configurable: true, enumerable: true, get: () => err.stream });+ process.exit = (code) => {+ ended.code = code;+ ended.takenAtExit = { stdout: out.taken, stderr: err.taken };+ throw END;+ };+ try {+ fn();+ ended.returned = true;+ } catch (error) {+ if (error !== END) throw error;+ } finally {+ Object.defineProperty(process, 'stdout', saved.stdout);+ Object.defineProperty(process, 'stderr', saved.stderr);+ process.exit = saved.exit;+ }+ return { ...ended, written: { stdout: out.written, stderr: err.written } };+}++test('emitResult has every text it wrote taken whole by the pipe when it calls process.exit — a pipe that takes 64 KiB at once and queues the rest — and never returns to its caller', () => {+ const { emitResult } = require('../lib/dataverse-auth.js');+ const calls = {+ ok: () => emitResult(true, table(BIG)),+ ascii: () => emitResult(true, table(BIG, ACCENT), { ascii: true }),+ 'structured-error': () => emitResult(false, { ok: false, error: longText(BIG), rows: table(BIG) }),+ 'structured-errors': () => emitResult(false, { ok: false, errors: table(BIG) }),+ error: () => emitResult(false, new Error(longText(BIG))),+ text: () => emitResult(false, longText(BIG)),+ };+ for (const [name, call] of Object.entries(calls)) {+ const ended = endedWith(call);+ assert.equal(ended.returned, false, `${name}: emitResult never returns — the exit follows its writes at once`);+ assert.equal(ended.code, name === 'ok' || name === 'ascii' ? 0 : 1, `${name}: the exit status`);+ assert.ok(ended.written.stdout.length + ended.written.stderr.length > 2 * 1024 * 1024, `${name}: a text of megabytes was written`);+ for (const stream of ['stdout', 'stderr']) {+ assert.equal(ended.takenAtExit[stream].length, ended.written[stream].length, `${name}: the pipe had taken all of ${stream} when process.exit was called`);+ }+ }+});++test('a small result was always taken at once by such a pipe, and still is: emitResult writes the same texts in the same order', () => {+ const { emitResult } = require('../lib/dataverse-auth.js');+ const ended = endedWith(() => emitResult(false, { ok: false, error: 'the build stopped: sign in with az login', rows: table(SMALL) }));+ assert.equal(ended.code, 1);+ assert.equal(ended.takenAtExit.stdout, `${JSON.stringify({ ok: false, error: 'the build stopped: sign in with az login', rows: table(SMALL) })}\n`);+ assert.equal(ended.takenAtExit.stderr, 'the build stopped: sign in with az login\n');+});++// ── makeWritesBlocking itself ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('makeWritesBlocking makes each handle blocking and leaves everything else as it was: a stream with no handle, a handle with no setBlocking, one that answers an error code and one that throws are passed over, and it never throws', () => {+ const calls = [];+ const write = function write() { return true; };+ const piped = { write, _handle: { setBlocking: (flag) => { calls.push(['piped', flag]); return 0; } } };+ // EINVAL, which libuv answers for a terminal on Windows: only a pipe can be made blocking there.+ const refusing = { _handle: { setBlocking: (flag) => { calls.push(['refusing', flag]); return -4071; } } };+ const throwing = { _handle: { setBlocking: () => { calls.push(['throwing']); throw new Error('the handle is closed'); } } };+ assert.equal(makeWritesBlocking(piped, null, undefined, {}, { _handle: null }, { _handle: {} }, refusing, throwing, piped), undefined);+ assert.deepEqual(calls, [['piped', true], ['refusing', true], ['throwing'], ['piped', true]]);+ assert.equal(piped.write, write, 'the stream\'s own write is left as it was');+ assert.doesNotThrow(() => makeWritesBlocking());+});++// The printer of an error that ends the process reads `process.stderr` inside the try that holds its write, so a stream that cannot even be read — a+// host that replaced it with an accessor that throws — ends the process as an error nothing caught always has: status 1. Read outside that try, the+// throw left the handler itself and Node ended the process with 7, its status for a handler that failed, printing that failure.+test('an error that ends the process when process.stderr cannot even be read — an accessor that throws — still ends it with status 1, printing nothing', () => {+ const redaction = path.join(__dirname, '..', 'lib', 'output-redaction.js');+ const ran = spawnSync(process.execPath, ['-e', [+ `require(${JSON.stringify(redaction)}).noteToken(${JSON.stringify(TOKEN)});`,+ 'Object.defineProperty(process, \'stderr\', { configurable: true, get() { throw new Error(\'stderr is gone\'); } });',+ 'throw new Error(\'the work failed\');',+ ].join('\n')], { encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' }, timeout: 60000 });+ assert.equal(ran.error, undefined, `the process could not be run: ${ran.error}`);+ assert.equal(ran.status, 1, `the status of an error nothing caught, not 7 (the handler failed): ${ran.stderr.slice(0, 300)}`);+ assert.equal(ran.stdout, '', 'nothing on stdout');+ assert.equal(ran.stderr, '', 'no stream to print on — and no failure of the handler printed by Node');+});++test('makeWritesBlocking leaves the output guard on the stream: what is written after it is still cleaned of the tokens the process obtained', () => {+ const taken = [];+ const stream = { write: (chunk) => { taken.push(chunk); return true; }, _handle: { setBlocking: () => 0 } };+ assert.equal(guardStream(stream, (text) => text.replace('secret-value', '<token>')), true);+ const guarded = stream.write;+ makeWritesBlocking(stream);+ assert.equal(stream.write, guarded, 'the guard is still the stream\'s write');+ stream.write('Rejected bearer secret-value\n');+ assert.deepEqual(taken, ['Rejected bearer <token>\n']);+});diff --git a/plugins/model-apps/scripts/tests/run-cleanup.test.js b/plugins/model-apps/scripts/tests/run-cleanup.test.jsindex 6b3e31924..da63714c8 100644--- a/plugins/model-apps/scripts/tests/run-cleanup.test.js+++ b/plugins/model-apps/scripts/tests/run-cleanup.test.js@@ -283,30 +283,27 @@ test('the real SDK refuses a row summary on an org with no AI template before anassert.ok(state.warnings.some((w) => /no 'GptPowerPrompt' AI template/.test(w)));});-// An org whose template list comes back without a template. The SDK takes the FIRST row of the list and reads its `msdyn_aitemplateid` without checking-// that there is a row, so it raises ROW_SUMMARY_TEMPLATE_NOT_FOUND for an empty list and for a list whose first row is no row alike:-// { "value": [] } { "value": [ {} ] } { "value": [ null ] }-// Only the empty list says the org has no template. The others are answers that cannot be read, and an answer that cannot be read stops the build, as it did-// before the skip above — so the build asks the template list itself, once, before it skips, and skips only on an empty list.+// An org whose template list comes back without a template. The SDK reads the FIRST row of+// GET /msdyn_aitemplates?$select=msdyn_aitemplateid&$filter=msdyn_uniquename eq 'GptPowerPrompt'&$top=1 -> { "value": [ { "msdyn_aitemplateid": "<guid>" } ] }+// and raises ROW_SUMMARY_TEMPLATE_NOT_FOUND for an EMPTY list and for nothing else. An answer it cannot read — no list, a first row that is no row, an id that is no GUID —+// is a ConnectionError, so it stops the build like any read that failed and is never taken for an org without the template. (Before cds-maker-sdk 9a0c9f03 it raised the+// code for `[ {} ]` and `[ null ]` too, and the build asked for the list a second time itself, to tell them apart.) The build skips on the code alone and makes no read+// of the template of its own.const TEMPLATE_LIST = "/msdyn_aitemplates?$select=msdyn_aitemplateid&$filter=msdyn_uniquename eq 'GptPowerPrompt'&$top=1";const listOf = (value) => ({ status: 200, headers: {}, body: { value } });-// The real SDK over a transport that answers the template list from `answers` and the template table's set from `entitySet` (one answer per request for each, the last one-// repeating) and records every request, writes included. An answer that is an Error is what the transport throws: the request got no answer at all, as when a connection is reset.-// The mock SDK the build drives gets the real `configureRowSummary` (the errors it throws are kept, `sdkErrors`) and `queryRecords`.-async function orgWithTemplateAnswers(t, answers, entitySet = [{ status: 200, headers: {}, body: { EntitySetName: 'msdyn_aitemplates' } }]) {+// The real SDK over a transport that answers the template list from `answers` (one answer per request, the last one repeating) and records every request, writes included.+// An answer that is an Error is what the transport throws: the request got no answer at all, as when a connection is reset. The mock SDK the build drives gets the real+// `configureRowSummary` (the errors it throws are kept, `sdkErrors`) and a `queryRecords` over the same transport that records the table each read names (`reads`): the+// table set of the template table is answered, so that a read of that table by the build itself would show up in `requests` instead of failing the transport.+async function orgWithTemplateAnswers(t, answers, { skills = listOf([]) } = {}) {const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'contoso-summary-confirm-'));+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'contoso-summary-template-'));t.after(() => fs.rmSync(dir, { recursive: true, force: true }));const requests = [];const sdkErrors = [];+ const reads = [];let templateReads = 0;- let entitySetReads = 0;- const scripted = (list, n) => {- const answer = list[Math.min(n, list.length - 1)];- if (answer instanceof Error) throw answer;- return answer;- };const seen = (method, url) => requests.push(`${method} ${decodeURIComponent(url.replace(/^https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.\d+/, ''))}`);const write = (method) => async (url) => { seen(method, url); return { status: 200, headers: {}, body: {} }; };const real = createMakerSdk({@@ -315,9 +312,13 @@ async function orgWithTemplateAnswers(t, answers, entitySet = [{ status: 200, hehttpClient: {get: async (url) => {seen('GET', url);- if (url.includes('/aiskillconfigs?')) return listOf([]);- if (url.includes('/msdyn_aitemplates?')) return scripted(answers, templateReads++);- if (url.includes("/EntityDefinitions(LogicalName='msdyn_aitemplate')")) return scripted(entitySet, entitySetReads++);+ if (url.includes('/aiskillconfigs?')) return skills;+ if (url.includes('/msdyn_aitemplates?')) {+ const answer = answers[Math.min(templateReads++, answers.length - 1)];+ if (answer instanceof Error) throw answer;+ return answer;+ }+ if (url.includes("/EntityDefinitions(LogicalName='msdyn_aitemplate')")) return { status: 200, headers: {}, body: { EntitySetName: 'msdyn_aitemplates' } };if (/\/EntityDefinitions\(LogicalName='contoso_\w+'\)/.test(url)) return { status: 200, headers: {}, body: { MetadataId: OLDEST } };throw new Error(`unexpected offline GET ${url}`);},@@ -329,11 +330,12 @@ async function orgWithTemplateAnswers(t, answers, entitySet = [{ status: 200, hesdk.configureRowSummary = async (...args) => {try { return await real.configureRowSummary(...args); } catch (err) { sdkErrors.push(err); throw err; }};- sdk.queryRecords = real.queryRecords.bind(real);+ sdk.queryRecords = async (entity, query) => { reads.push(entity); return real.queryRecords(entity, query); };return {sdk,sdkErrors,requests,+ reads,templateReads: () => requests.filter((request) => request.startsWith('GET /msdyn_aitemplates?')),writes: () => requests.filter((request) => !request.startsWith('GET ')),};@@ -346,27 +348,7 @@ const bothTables = () => {return s;};-// The build stops with the SDK's own error, whole: the halt's code and words are the SDK's, and the SDK's error is its cause.-const stoppedBySdkError = (err) => {- assert.equal(err.name, 'BuildHalt');- assert.equal(err.code, 'ROW_SUMMARY_TEMPLATE_NOT_FOUND');- assert.equal(err.cause.code, 'ROW_SUMMARY_TEMPLATE_NOT_FOUND', "the SDK's own error is what stopped the build");- assert.match(err.message, /^ai-features failed: Cannot configure the row summary of 'contoso_ticket'/);- return true;-};--// ...and for good, when the confirming read ANSWERED, however wrongly: nothing says that a run again could help (the halt's policy is `never`, and so is the check the build's own retry makes), and there is no-// failure of the read to keep or to explain, so the halt carries the SDK's words alone.-const stoppedForGood = (err) => {- stoppedBySdkError(err);- assert.equal(err.retry, 'never');- assert.equal(isTransientHalt(err), false);- assert.equal(err.cause.cause, undefined);- assert.equal(err.message, `ai-features failed: ${err.cause.message}`);- return true;-};--test('an org whose template list is empty skips every summary with one warning and writes nothing, and the build confirms it with one read of the list, however many tables ask', async (t) => {+test('an org whose template list is empty skips every summary with one warning and writes nothing, and the build reads no template list of its own, however many tables ask', async (t) => {const org = await orgWithTemplateAnswers(t, [listOf([])]);const warnings = [];const events = [];@@ -378,157 +360,120 @@ test('an org whose template list is empty skips every summary with one warning aassert.equal(warnings.length, 1, `one warning for two tables, got ${JSON.stringify(warnings)}`);assert.match(warnings[0], /no 'GptPowerPrompt' AI template/);assert.deepEqual(org.writes(), []);- // The SDK reads the list for each table (two reads) and the build asks it once more, for the first table only; every one of the three is the same request,- // so the build asks exactly what the SDK asked. The one other read names the template table's set, which the SDK looks up once and keeps.- assert.deepEqual(org.templateReads(), Array(3).fill(`GET ${TEMPLATE_LIST}`));- assert.deepEqual(org.requests.filter((request) => request.includes("LogicalName='msdyn_aitemplate'")), ["GET /EntityDefinitions(LogicalName='msdyn_aitemplate')?$select=EntitySetName"]);+ // The SDK reads the list once for each table, and that is every read of it: the build asks nothing more, and reads no table of its own — nothing was written, so there is no model inventory to report either.+ assert.deepEqual(org.templateReads(), Array(2).fill(`GET ${TEMPLATE_LIST}`));+ assert.deepEqual(org.reads, []);+ assert.deepEqual(org.requests.filter((request) => request.includes("LogicalName='msdyn_aitemplate'")), []);});-for (const [what, list] of [['a first row with no id', [{}]], ['a first row that is not a row', [null]]]) {+// What the SDK cannot read as a list of templates stops the build with the SDK's own error: a ConnectionError, the halt's cause, which says what it could not read. Nothing is skipped, so nothing says it was, and no+// run again helps (the halt's policy is `never`, and so is the check the build's own retry makes): the answer was received, and read as what it is.+const MALFORMED_TEMPLATE_ANSWERS = [+ ['a first row with no id', listOf([{}]), /the row-summary template lookup returned a malformed row — expected a GUID 'msdyn_aitemplateid' but got /],+ ['a first row that is not a row', listOf([null]), /the row-summary template lookup returned a malformed row — expected an object but got /],+ ['a first row whose id is null', listOf([{ msdyn_aitemplateid: null }]), /expected a GUID 'msdyn_aitemplateid' but got /],+ ['a first row whose id is no GUID', listOf([{ msdyn_aitemplateid: 'GptPowerPrompt' }]), /expected a GUID 'msdyn_aitemplateid' but got a string that is not a GUID/],+ ['an answer with no list', { status: 200, headers: {}, body: {} }, /the row-summary template lookup returned a malformed answer — expected an OData 'value' array but got /],+];+for (const [what, answer, words] of MALFORMED_TEMPLATE_ANSWERS) {test(`${what} in the template list is not an org without the template: the build stops with the SDK's error and skips nothing`, async (t) => {- const org = await orgWithTemplateAnswers(t, [listOf(list)]);+ const org = await orgWithTemplateAnswers(t, [answer]);const warnings = [];const events = [];- await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w), emit: (e) => events.push(e) }), stoppedForGood);+ await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w), emit: (e) => events.push(e) }), (err) => {+ assert.equal(err.name, 'BuildHalt');+ assert.equal(err.code, 'CONNECTION_ERROR');+ assert.equal(err.cause, org.sdkErrors[0], "the SDK's own error is the halt's cause");+ assert.match(err.message, /^ai-features failed: /);+ assert.match(err.message, words);+ assert.equal(err.retry, 'never');+ assert.equal(isTransientHalt(err, { spec: spec() }), false);+ return true;+ });assert.deepEqual(warnings, [], 'nothing was skipped, so nothing says it was');assert.deepEqual(events.filter((e) => e.status === 'skip'), []);assert.deepEqual(org.writes(), []);- assert.equal(org.templateReads().length, 2, 'the SDK read the list, and the build asked it once more');+ assert.equal(org.templateReads().length, 1, 'the SDK read the list once, and the build asked nothing more');+ assert.deepEqual(org.reads, []);});}-test("a template that the build finds when it asks again, after the SDK read none, is not an org without one: the build stops with the SDK's error", async (t) => {- const org = await orgWithTemplateAnswers(t, [listOf([]), listOf([{ msdyn_aitemplateid: TEMPLATE }])]);- const warnings = [];- await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), stoppedForGood);- assert.deepEqual(warnings, []);- assert.deepEqual(org.writes(), []);-});--// What a FAILURE of the confirming read does to the halt. The build runs this attempt again, by itself, for a failure the SERVICE calls transient — a throttle (429), a service that is down or overloaded-// (503), a connection that was reset — and reads that from the errors along the halt's causes (lib/retry-policy.js, judgeFailure). So the read's failure has to be on that chain, under the SDK's error, which-// stays the halt's own cause: a halt that kept only the SDK's refusal was final whatever the read had failed with. Either request of the confirming read can fail: the one that names the template table's set-// (the SDK looks it up once) and the one that reads the list. Each is scripted to fail once and then to answer, so that a second attempt can finish.-const refusedWith = (status, message) => ({ status, headers: {}, body: { error: { message } } });-const connectionReset = () => Object.assign(new Error('Request failed: read ECONNRESET'), { code: 'ECONNRESET' });-const confirmingRequests = [- ["the read that names the template table's set", (failure) => ({ answers: [listOf([])], entitySet: [failure, { status: 200, headers: {}, body: { EntitySetName: 'msdyn_aitemplates' } }] }), /could not resolve EntitySetName/],- ['the read of the template list', (failure) => ({ answers: [listOf([]), failure, listOf([])] }), /malformed page/],-];-// The halt of a failed confirmation: the SDK's error itself is its cause, the read's failure is kept under that error, and the halt's text says that the read failed, and why.-const stoppedByFailedConfirmation = (org) => (err) => {- stoppedBySdkError(err);- assert.equal(err.cause, org.sdkErrors[0], "the halt's own cause is the SDK's error itself, not a copy of it");- assert.ok(err.cause.cause, "the read's failure is kept under the SDK's error");- assert.match(err.message, /, to confirm that before skipping the row summaries, and that read failed \(/);- assert.ok(err.message.includes(err.cause.cause.message), `the halt says why the read failed: ${err.message}`);- return true;-};--for (const [where, scriptFor, malformedWords] of confirmingRequests) {- for (const [what, make, status] of [['a throttle', () => refusedWith(429, 'Contoso throttled'), 429], ['an unavailable service', () => refusedWith(503, 'Contoso unavailable'), 503], ['a reset connection', connectionReset, 0]]) {- test(`${what} on ${where} that confirms the absence is a transient halt, which a second attempt can finish`, async (t) => {- const { answers, entitySet } = scriptFor(make());- const org = await orgWithTemplateAnswers(t, answers, entitySet);- const options = (warnings) => ({ sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) });- const warnings = [];- await assert.rejects(runSdkBuild(spec(), options(warnings)), (err) => {- assert.equal(isTransientHalt(err, { spec: spec() }), true, 'the build runs this attempt again');- assert.equal(err.retry, 'service');- assert.equal(err.cause.cause.code, 'CONNECTION_ERROR');- assert.equal(err.cause.cause.statusCode, status);- return stoppedByFailedConfirmation(org)(err);- });- assert.deepEqual(warnings, [], 'nothing was skipped, so nothing says it was');- assert.deepEqual(org.writes(), []);- // The attempt after it asks again, and this time the org answers: the list is empty, so the summary is skipped, as it is for any org without the template.- const again = [];- const r = await runSdkBuild(spec(), options(again));- assert.equal(r.ok, true);- assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket']);- assert.equal(again.length, 1);- assert.match(again[0], /no 'GptPowerPrompt' AI template/);- });- }-- // A refusal, and an answer with nothing in it (a 200 whose body has no list, no table set): neither is the service saying that a run again can help.- for (const [what, answer, words] of [['a refusal (403)', refusedWith(403, 'Contoso permission denied'), /Contoso permission denied/], ['an answer with nothing in it (a 200 without its content)', { status: 200, headers: {}, body: {} }, malformedWords]]) {- test(`${what} on ${where} that confirms the absence is final, and the halt says the read failed and why`, async (t) => {- const { answers, entitySet } = scriptFor(answer);- const org = await orgWithTemplateAnswers(t, answers, entitySet);- const warnings = [];- await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), (err) => {- assert.equal(err.retry, 'never');- assert.equal(isTransientHalt(err, { spec: spec() }), false);- stoppedByFailedConfirmation(org)(err);- assert.match(err.message, words);- return true;- });- assert.deepEqual(warnings, []);- assert.deepEqual(org.writes(), []);+// The SDK's lookup of an existing row-summary skill is as strict: a first row that is no row is an answer it cannot read, never "no row summary yet" — which used to go on to publish a model and bind a+// skill. The build stops with the SDK's own error, and nothing is written (the template is not even read: the skill lookup comes first).+for (const [what, answer, words] of [+ ['a first row that is no row', listOf([null]), /the existing row-summary skill lookup returned a malformed row — expected an object but got /],+ ['an answer with no list', { status: 200, headers: {}, body: {} }, /the existing row-summary skill lookup returned a malformed answer — expected an OData 'value' array but got /],+]) {+ test(`${what} in the skill lookup is not "no row summary yet": the build stops with the SDK's error and writes nothing`, async (t) => {+ const org = await orgWithTemplateAnswers(t, [listOf([{ msdyn_aitemplateid: TEMPLATE }])], { skills: answer });+ const warnings = [];+ await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), (err) => {+ assert.equal(err.name, 'BuildHalt');+ assert.equal(err.code, 'CONNECTION_ERROR');+ assert.equal(err.cause, org.sdkErrors[0], "the SDK's own error is the halt's cause");+ assert.match(err.message, words);+ assert.equal(err.retry, 'never');+ return true;});- }+ assert.deepEqual(warnings, []);+ assert.deepEqual(org.writes(), [], 'no model was published and no skill was bound');+ assert.deepEqual(org.templateReads(), []);+ });}-test('the build confirms the absence of the template with the question the SDK asks, and asks it once for the whole build', async () => {- const { sdk } = makeSimpleMockSdk();- const reads = [];- sdk.configureRowSummary = async () => { throw Object.assign(new Error("Cannot configure the row summary of 'contoso_ticket': this org has no AI template"), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' }); };- sdk.queryRecords = async (entity, query) => { reads.push([entity, query]); return []; };- const r = await runSdkBuild(bothTables(), { sdk, apply: true, phases: ['ai-features'], warn: () => {} });- assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket', 'contoso_request']);- assert.deepEqual(reads, [['msdyn_aitemplate', { select: ['msdyn_aitemplateid'], filter: "msdyn_uniquename eq 'GptPowerPrompt'", top: 1 }]]);-});+// A failure of the SDK's own read of the template list. The build runs this attempt again, by itself, for a failure the SERVICE calls transient — a throttle (429), a service that is down or overloaded+// (503), a connection that was reset — and reads that from the errors along the halt's causes (lib/retry-policy.js, judgeFailure). The SDK's read is the one read of the list, and its error is the halt's+// own cause: a ConnectionError that carries the status, or the reset, so the chain says what the service said. The read is scripted to fail once and then to answer, so that a second attempt can finish.+const refusedWith = (status, message) => ({ status, headers: {}, body: { error: { message } } });+const connectionReset = () => Object.assign(new Error('Request failed: read ECONNRESET'), { code: 'ECONNRESET' });-test("every answer to the confirming read but an empty list leaves the SDK's own error to stop the build, and a missing template is never a transient halt", async () => {- // [what the read does, what it answers (or throws), the reason a failed read gives]- const answers = [- ['a first row with no id', () => [{}], null],- ['a first row that is not a row', () => [null], null],- ['a template', () => [{ msdyn_aitemplateid: TEMPLATE }], null],- ['no list', () => undefined, null],- ['a list that is not one', () => 'bad', null],- ['a read that fails', () => { throw new Error('Contoso template read failed'); }, 'Contoso template read failed'],- // Only what the SERVICE answered (a status, a reset) can make a halt transient: the words of a failure that has none are not read, so this is no more transient than the read above.- ['a read that fails in words that say to try again', () => { throw new Error('Please try again later.'); }, 'Please try again later.'],- ];- for (const [what, answer, failed] of answers) {- const { sdk } = makeSimpleMockSdk();- const refusal = Object.assign(new Error("Cannot configure the row summary of 'contoso_ticket': this org has no AI template 'GptPowerPrompt' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written."), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' });- sdk.configureRowSummary = async () => { throw refusal; };- sdk.queryRecords = async () => answer();+for (const [what, make, status] of [['a throttle', () => refusedWith(429, 'Contoso throttled'), 429], ['an unavailable service', () => refusedWith(503, 'Contoso unavailable'), 503], ['a reset connection', connectionReset, 0]]) {+ test(`${what} on the SDK's own read of the template list is a transient halt, which a second attempt can finish`, async (t) => {+ const org = await orgWithTemplateAnswers(t, [make(), listOf([])]);+ const options = (warnings) => ({ sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) });const warnings = [];- await assert.rejects(runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), (err) => {- assert.equal(err.name, 'BuildHalt', what);- assert.equal(err.code, 'ROW_SUMMARY_TEMPLATE_NOT_FOUND', what);- assert.equal(err.cause, refusal, `${what}: the SDK's error itself is the cause`);- assert.equal(err.retry, 'never', what);- assert.equal(isTransientHalt(err), false, what);- // A read that threw is kept under the SDK's error and named in the halt's text; one that answered, however wrongly, has failed at nothing, and the halt is the SDK's words alone.- assert.equal(refusal.cause && refusal.cause.message, failed || undefined, what);- assert.equal(err.message, `ai-features failed: ${refusal.message}${failed ? ` — the build then read the template list itself, to confirm that before skipping the row summaries, and that read failed (${failed}), so they were not skipped.` : ''}`, what);+ await assert.rejects(runSdkBuild(spec(), options(warnings)), (err) => {+ assert.equal(err.name, 'BuildHalt');+ assert.equal(isTransientHalt(err, { spec: spec() }), true, 'the build runs this attempt again');+ assert.equal(err.retry, 'service');+ assert.equal(err.cause, org.sdkErrors[0], "the SDK's own error is the halt's cause");+ assert.equal(err.cause.code, 'CONNECTION_ERROR');+ if (status) assert.equal(err.cause.statusCode, status);return true;});- assert.deepEqual(warnings, [], what);- }-});+ assert.deepEqual(warnings, [], 'nothing was skipped, so nothing says it was');+ assert.deepEqual(org.writes(), []);+ assert.deepEqual(org.reads, [], 'and the build read nothing of its own');+ // The attempt after it asks again, and this time the org answers: the list is empty, so the summary is skipped, as it is for any org without the template.+ const again = [];+ const r = await runSdkBuild(spec(), options(again));+ assert.equal(r.ok, true);+ assert.deepEqual(r.skipped.aiSummaries, ['contoso_ticket']);+ assert.equal(again.length, 1);+ assert.match(again[0], /no 'GptPowerPrompt' AI template/);+ assert.equal(org.templateReads().length, 2, 'one read for each attempt');+ });+}-test('an SDK error that cannot carry the failure of the confirming read still stops the build with the SDK\'s own words, and says nothing about a read it cannot attach', async () => {- const { sdk } = makeSimpleMockSdk();- const refusal = Object.freeze(Object.assign(new Error("Cannot configure the row summary of 'contoso_ticket': this org has no AI template 'GptPowerPrompt' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written."), { code: 'ROW_SUMMARY_TEMPLATE_NOT_FOUND' }));- sdk.configureRowSummary = async () => { throw refusal; };- sdk.queryRecords = async () => { throw Object.assign(new Error('HTTP 503 from https://contoso.crm.dynamics.com/api/data/v9.0/msdyn_aitemplates: Contoso unavailable'), { code: 'CONNECTION_ERROR', statusCode: 503 }); };- await assert.rejects(runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: () => {} }), (err) => {+// A refusal is not the service saying that a run again can help.+test("a refusal of the SDK's own read of the template list (403) is final: the build stops with the SDK's error and skips nothing", async (t) => {+ const org = await orgWithTemplateAnswers(t, [refusedWith(403, 'Contoso permission denied')]);+ const warnings = [];+ await assert.rejects(runSdkBuild(spec(), { sdk: org.sdk, apply: true, phases: ['ai-features'], warn: (w) => warnings.push(w) }), (err) => {assert.equal(err.name, 'BuildHalt');- assert.equal(err.cause, refusal, "the SDK's error itself is the cause");- assert.equal(refusal.cause, undefined, 'nothing could be attached to it');- assert.equal(err.retry, 'never', 'as before: the failure of the read is not on the chain');- assert.equal(err.message, `ai-features failed: ${refusal.message}`);+ assert.equal(err.cause, org.sdkErrors[0]);+ assert.equal(err.cause.statusCode, 403);+ assert.match(err.message, /Contoso permission denied/);+ assert.equal(err.retry, 'never');+ assert.equal(isTransientHalt(err, { spec: spec() }), false);return true;});+ assert.deepEqual(warnings, []);+ assert.deepEqual(org.writes(), []);});-test('only the exact template code starts the confirming read: a refusal of another kind is skipped or stops the build as it always did, with no read of the template list', async () => {+// The skip is the SDK's word for an empty list, and only that word: the code is matched exactly, in the error's own `code`.+test('only the exact template code skips the summaries for a missing template: a refusal of another kind is skipped or stops the build as it always did', async () => {for (const code of ['DuplicateRecordKey', 'ModelNotSupported']) {const { sdk, state } = summarySdk(code);const entities = [];@@ -549,6 +494,6 @@ test('only the exact template code starts the confirming read: a refusal of anotsdk.configureRowSummary = async () => { throw make(); };sdk.queryRecords = async (entity) => { entities.push(entity); return []; };await assert.rejects(runSdkBuild(spec(), { sdk, apply: true, phases: ['ai-features'], warn: () => {} }), (err) => err.name === 'BuildHalt', what);- assert.deepEqual(entities, [], `${what}: no read of the template list`);+ assert.deepEqual(entities, [], `${what}: the build stops, and reads nothing of its own`);}});diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.jsindex c84f67aff..69de77dfe 100644--- a/plugins/model-apps/scripts/tests/run-tests.test.js+++ b/plugins/model-apps/scripts/tests/run-tests.test.js@@ -269,6 +269,7 @@ const PCF_COPY_SYNC_PATHS = new Set(['scripts/validate-plugin-copies.js','plugins/pcf/scripts/lib/process-runner.js','plugins/pcf/scripts/lib/sdk-http-client.js',+ 'plugins/pcf/scripts/lib/output-redaction.js','plugins/pcf/scripts/lib/odata.js','plugins/pcf/scripts/lib/source-literals.js','plugins/pcf/scripts/lib/interaction-mode.js',diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.jsindex 213447f57..8ae5bf56f 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js@@ -4232,10 +4232,10 @@ test('deploy: an edited page whose update the service throttles is waited out an}});-// ── What the service asked crosses to the build, and the waits the build's own layers add are one budget ───────────────────────────────────────────────+// ── What the service asked crosses to the build, and the waits of the run's layers are one budget ─────────────────────────────────────────────────────// The backend waits out a throttled page write between its sends; when its six sends are not enough it hands the build what the last answer asked, as a moment before which nothing may be sent, and the build waits for THAT before-// it runs the pages phase again — not for its own shorter backoff. The waiting those two layers add is one budget of five minutes (lib/throttle-budget.js) — NOT all the waiting of a run: the HTTP client's own re-sends of a throttled read or-// publish keep their own schedule and are not drawn from it (pinned below). A wait that does not fit stops the run with a halt that says what the service asked and that a later run continues. These tests drive the real build, its retry loop,+// it runs the pages phase again — not for its own shorter backoff. The waiting those two layers do, and the HTTP client's own waits for a throttled read or publish (pinned at the end of this file), are one budget of five minutes+// (lib/throttle-budget.js). A wait that does not fit stops the run with a halt that says what the service asked and that a later run continues. These tests drive the real build, its retry loop,// the real backend and the real SDK, with each layer's waits recorded in one list.const waitsOf = (events) => events.filter((e) => e.ms !== undefined);const totalWait = (events) => waitsOf(events).reduce((sum, e) => sum + e.ms, 0);@@ -4373,10 +4373,9 @@ test('deploy: a throttle that never says how long keeps the waits it always had}});-// The budget bounds what the BUILD's own layers add — the page backend's waits between the sends of a page write, which is a `$batch` the HTTP client never re-sends, and the build's waits before it runs a phase again. It does not bound-// the production HTTP client's own re-sends of a throttled read or publish: those keep the schedule they always had (at most five re-sends, honouring a `Retry-After` of up to a minute), and charging them to the run would halt a build that is-// throttled for a while and succeeds today. This pins that decision, so a later change that starts charging the client has to make it on purpose.-test('deploy: the HTTP client\'s own waits for a throttled read are not drawn from the run\'s budget — five reads throttled for a minute are waited out by the client, five page writes by the backend, and the build succeeds', async () => {+// The HTTP client draws its waits for a throttled answer from the run's budget when it is given one (lib/sdk-http-client.js); a client that is given none — the pcf plugin's, which has no budget — waits as it always did: at most five re-sends of+// a throttled read or publish, each honouring a `Retry-After` of up to a minute. This pins that, with the same ten minutes of throttling the budgeted tests below cannot wait out.+test('deploy: a client that is given no budget waits as it always did — five reads throttled for a minute are waited out by the client, five page writes by the backend, and the build succeeds', async () => {const { createAzHttpClient } = require('../lib/sdk-http-client.js');const { makeThrottleBudget } = require('../lib/throttle-budget.js');const { appDir, spec } = onePageApp('Overview');@@ -4417,9 +4416,326 @@ test('deploy: the HTTP client\'s own waits for a throttled read are not drawn frassert.deepStrictEqual(events.filter((e) => e.who === 'client').map((e) => e.ms), [60000, 60000, 60000, 60000, 60000], 'the client waited out the five throttled reads on its own, a minute each');assert.deepStrictEqual(events.filter((e) => e.who === 'backend').map((e) => e.ms), [60000, 60000, 60000, 60000, 60000], 'the backend waited out the five throttled page writes');assert.deepStrictEqual(events.filter((e) => e.who === 'build'), [], 'and the build had nothing to wait for');- assert.strictEqual(budget.spentMs(), 300000, 'the budget holds the backend\'s waits and not the client\'s: ten minutes were waited in all, five of them inside it');+ assert.strictEqual(budget.spentMs(), 300000, 'the client was given no budget, so the budget holds the backend\'s waits alone: ten minutes were waited in all, five of them inside it');} finally {await genpage.dispose();fs.rmSync(appDir, { recursive: true, force: true });}});++// The transport under the production client: the answers of the fake page service as a transport hands them over, with the nth read throttled when `refuseRead(n)` answers.+function pageTransport(server, refuseRead = () => undefined) {+ const raw = server.http();+ let reads = 0;+ return async ({ url, method, headers, body }) => {+ if (method === 'GET') {+ reads += 1;+ const refused = refuseRead(reads);+ if (refused) return refused;+ }+ const answer = method === 'POST' && url.endsWith('/$batch') ? await raw.postRaw(url, body, { headers })+ : method === 'GET' ? await raw.get(url, { headers })+ : method === 'DELETE' ? await raw.delete(url, { headers })+ : method === 'PATCH' && Buffer.isBuffer(body) ? await raw.patchRaw(url, body, { headers })+ : await raw[method.toLowerCase()](url, typeof body === 'string' ? JSON.parse(body) : body, { headers });+ const text = typeof answer.body === 'string' || Buffer.isBuffer(answer.body) ? answer.body : JSON.stringify(answer.body === undefined ? null : answer.body);+ return { statusCode: answer.status, headers: answer.headers || {}, body: text };+ };+}+const throttledRead = (seconds) => ({ statusCode: 429, headers: { 'retry-after': String(seconds) }, body: '{"error":{"message":"throttled"}}' });+// A clock that every wait of the run moves, as a real wait does: the HTTP client places its waits on it.+function movingClock() {+ let at = Date.parse('2026-09-30T10:00:00Z');+ return { now: () => at, advance: (ms) => { at += ms; } };+}+// `driveBuild` builds for the page service's own environment, and a build keeps its local page records per environment: `pendingOf` and `receiptsOf` read those of BUILD_ENV, which a driven build never writes.+const pendingOfDriven = (spec, appDir) => readPendingCreations(path.join(appDir, '.maker-workspace'), appUniqueName(spec), PAGE_SERVICE);+const receiptsOfDriven = (spec, appDir) => readPageOwnership(path.join(appDir, '.maker-workspace'), appUniqueName(spec), PAGE_SERVICE).created;+// The production stack under the pages phase: the HTTP client, drawing its waits from the run's budget, over the fake page service on a clock its waits move, and the page backend on it. The requests `refuse` names are answered+// 429 with a `Retry-After` of `askSeconds`, as a transport answers them. `budget: false` is a run with none: a client and a backend that wait as they always did.+function budgetedPages(server, { refuse = () => false, askSeconds = 600, budget = true } = {}) {+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const clock = movingClock();+ const waits = [];+ const warnings = [];+ const throttle = makeThrottleBudget({ warn: (line) => warnings.push(line) });+ const transport = pageTransport(server);+ const sleep = async (ms) => { waits.push(ms); clock.advance(ms); };+ const httpClient = createAzHttpClient(PAGE_SERVICE, {+ getToken: () => 'TOK', random: () => 0, now: clock.now, sleep, ...(budget ? { throttle } : {}),+ request: async (request) => (refuse(request) ? throttledRead(askSeconds) : transport(request)),+ });+ const genpage = makeGenpageSdk(PAGE_SERVICE, { httpClient, ...(budget ? { throttle } : {}), random: () => 0, now: clock.now, sleep });+ return { genpage, throttle, clock, waits, warnings };+}++// With a budget the production client draws its waits for a throttled read or publish from it — with the backend's waits between the sends of a page write, and the build's own: one five minutes for the run.+test('deploy: the HTTP client\'s waits for a throttled read are drawn from the run\'s budget with the backend\'s — two reads and two page writes throttled for a minute are waited out inside it, and the build succeeds', async () => {+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const { appDir, spec } = onePageApp('Overview');+ fs.writeFileSync(path.join(appDir, 'p.tsx'), PAGE_SOURCE, 'utf8');+ const server = new FakeGenPageServer();+ const events = [];+ const clock = movingClock();+ const budget = makeThrottleBudget();+ const httpClient = createAzHttpClient(PAGE_SERVICE, {+ getToken: () => 'TOK', random: () => 0, throttle: budget, now: clock.now,+ sleep: async (ms) => { events.push({ who: 'client', ms }); clock.advance(ms); },+ request: pageTransport(server, (n) => (n <= 2 ? throttledRead(60) : undefined)),+ });+ server.failBatch = (n) => (n <= 2 ? { status: 429, headers: { 'retry-after': '60' } } : undefined);+ const genpage = makeGenpageSdk(PAGE_SERVICE, { httpClient, random: () => 0, sleep: async (ms) => { events.push({ who: 'backend', ms }); clock.advance(ms); } });+ try {+ const out = await driveBuild(spec, appDir, {+ genpage, runOpts: pagesWorkspace(appDir), opts: { retryDelayMs: undefined },+ deps: { throttle: budget, sleep: async (ms) => { events.push({ who: 'build', ms }); } },+ });+ assert.strictEqual(out.halt, null);+ assert.strictEqual(out.result.ok, true);+ assert.strictEqual(out.attempts, 1);+ assert.strictEqual(server.state.projects.size, 1, 'one page');+ assert.deepStrictEqual(events.filter((e) => e.who === 'client').map((e) => e.ms), [60000, 60000], 'the client waited out the two throttled reads');+ assert.deepStrictEqual(events.filter((e) => e.who === 'backend').map((e) => e.ms), [60000, 60000], 'the backend the two throttled page writes');+ assert.deepStrictEqual(events.filter((e) => e.who === 'build'), []);+ assert.strictEqual(budget.spentMs(), 240000, 'and all four are the budget\'s: four of the five minutes');+ } finally {+ await genpage.dispose();+ fs.rmSync(appDir, { recursive: true, force: true });+ }+});++test('deploy: ten minutes of throttling in all are no longer waited out — five reads throttled for a minute take the whole budget, and the page write that is throttled after them stops the build with the budget\'s halt', async () => {+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const { isTransientHalt } = require('../build-model-app.js');+ const { appDir, spec } = onePageApp('Overview');+ fs.writeFileSync(path.join(appDir, 'p.tsx'), PAGE_SOURCE, 'utf8');+ const server = new FakeGenPageServer();+ const events = [];+ const clock = movingClock();+ const budget = makeThrottleBudget();+ const httpClient = createAzHttpClient(PAGE_SERVICE, {+ getToken: () => 'TOK', random: () => 0, throttle: budget, now: clock.now,+ sleep: async (ms) => { events.push({ who: 'client', ms }); clock.advance(ms); },+ request: pageTransport(server, (n) => (n <= 5 ? throttledRead(60) : undefined)),+ });+ server.failBatch = (n) => (n <= 5 ? { status: 429, headers: { 'retry-after': '60' } } : undefined);+ const genpage = makeGenpageSdk(PAGE_SERVICE, { httpClient, random: () => 0, sleep: async (ms) => { events.push({ who: 'backend', ms }); clock.advance(ms); } });+ try {+ const out = await driveBuild(spec, appDir, {+ genpage, runOpts: pagesWorkspace(appDir), opts: { retryDelayMs: undefined },+ deps: { throttle: budget, sleep: async (ms) => { events.push({ who: 'build', ms }); } },+ });+ assert.ok(out.halt, 'the build stops: the service throttled for ten minutes, and a run waits five at most');+ assert.strictEqual(out.halt.code, 'throttle-budget-exhausted');+ assert.strictEqual(isTransientHalt(out.halt), true, 'a transient halt: a later run goes on from here');+ assert.match(out.halt.message, /the service asked to wait 60 s before the next send, which does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service \(300 s are spent\)\. Nothing more is sent now: run the same command again later, and it continues from here\./);+ assert.strictEqual(out.attempts, 1, 'and the run is not run again to be refused again');+ assert.deepStrictEqual(events.filter((e) => e.who === 'client').map((e) => e.ms), [60000, 60000, 60000, 60000, 60000], 'the client waited out the five throttled reads — five minutes');+ assert.deepStrictEqual(events.filter((e) => e.who !== 'client'), [], 'and nothing else was waited for');+ assert.strictEqual(budget.spentMs(), 300000);+ assert.strictEqual(server.batches.length, 1, 'the page write was sent once, and refused');+ assert.strictEqual(server.state.projects.size, 0, 'nothing was written');+ assert.strictEqual(pendingOfDriven(spec, appDir).size, 0, 'and no creation is left under way');+ } finally {+ await genpage.dispose();+ fs.rmSync(appDir, { recursive: true, force: true });+ }+});++// The pages phase makes its page backend itself, and the backend its own HTTP client: this is the production path, with the budget the build was given reaching the client through the engine and the backend, and nothing injected+// but the transport under the client (the module's `createAzHttpClient` is the one thing replaced, so that the client it makes talks to the fake page service on a clock the test holds).+test('deploy: the budget reaches the HTTP client the pages phase makes for itself — a read the service throttles for ten minutes is not waited for, nothing is written, and the build stops with the budget\'s halt, naming what the service asked', async (t) => {+ const clientModule = require('../lib/sdk-http-client.js');+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const { isTransientHalt } = require('../build-model-app.js');+ const { appDir, spec } = onePageApp('Overview');+ fs.writeFileSync(path.join(appDir, 'p.tsx'), PAGE_SOURCE, 'utf8');+ const server = new FakeGenPageServer();+ const events = [];+ const made = [];+ const create = clientModule.createAzHttpClient;+ t.mock.method(clientModule, 'createAzHttpClient', (env, deps) => {+ made.push(deps);+ return create(env, { ...deps, getToken: () => 'TOK', random: () => 0, sleep: async (ms) => { events.push({ who: 'client', ms }); }, request: pageTransport(server, () => throttledRead(600)) });+ });+ const budget = makeThrottleBudget();+ try {+ const out = await driveBuild(spec, appDir, {+ runOpts: pagesWorkspace(appDir), opts: { retryDelayMs: undefined },+ deps: { throttle: budget, sleep: async (ms) => { events.push({ who: 'build', ms }); } },+ });+ assert.strictEqual(made.length, 1, 'the pages phase made one backend, and the backend one client');+ assert.strictEqual(made[0].throttle, budget, 'with the very budget the build was given');+ assert.ok(out.halt, 'the build stops');+ assert.strictEqual(out.halt.code, 'throttle-budget-exhausted');+ assert.strictEqual(out.halt.phase, 'pages');+ assert.strictEqual(isTransientHalt(out.halt), true);+ assert.match(out.halt.message, /^pages stopped: the service asked to wait 600 s before the next send, which does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service \(0 s are spent\)\. Nothing more is sent now: run the same command again later, and it continues from here\.$/);+ assert.strictEqual(out.attempts, 1, 'the run is not run again to meet the same answer');+ assert.deepStrictEqual(events, [], 'nothing was waited for, by the client or by the build');+ assert.strictEqual(budget.spentMs(), 0);+ assert.strictEqual(budget.declined().count, 1, 'the client told the budget once');+ assert.strictEqual(server.batches.length, 0, 'and nothing was sent');+ assert.strictEqual(server.state.projects.size, 0);+ assert.strictEqual(pendingOfDriven(spec, appDir).size, 0);+ } finally {+ fs.rmSync(appDir, { recursive: true, force: true });+ }+});++// ── A read before a write that the run's budget refused ──────────────────────────────────────────────────────────────────────────────────────────+// The reads that come before a page write — an update's read of the page it is about to change, the read that proves a page a pending create left behind — are requests like any other: when the run's budget has no room for the wait a throttled+// read asks for, the HTTP client hands the 429 back as it came and tells the budget (lib/throttle-budget.js, `decline`). The SDK reports that 429 as a page that cannot be read, which the backend used to make final (`transient: false`), so the build+// stopped with `GENPAGE_UNREADABLE` — and, for a pending create, with a conflict that tells the maker to delete a record — instead of the budget's halt that says what the service asked. Nothing was written either way: the refusal is the throttle's.+const contentRead = ({ method, url }) => method === 'GET' && /\/filecontent\/\$value$/.test(new URL(url).pathname);++test('deploy: the read before an update that the budget has no room to wait for is the throttle\'s refusal and not an unreadable page — the build stops with the budget\'s halt, nothing is written, and the next run updates the page once', async () => {+ const { isTransientHalt } = require('../build-model-app.js');+ const { appDir, spec } = onePageApp('Overview');+ fs.writeFileSync(path.join(appDir, 'p.tsx'), PAGE_SOURCE, 'utf8');+ const server = new FakeGenPageServer();+ const seed = budgetedPages(server);+ let id;+ try {+ const seeded = await driveBuild(spec, appDir, { genpage: seed.genpage, runOpts: pagesWorkspace(appDir), deps: { throttle: seed.throttle } });+ assert.strictEqual(seeded.halt, null, 'the page is made');+ id = seeded.result.created.pages.p;+ } finally { await seed.genpage.dispose(); }+ fs.writeFileSync(path.join(appDir, 'p.tsx'), PAGE_SOURCE.replace('Page</div>', 'Edited</div>'), 'utf8');+ const state = () => ({ pages: server.state.projects.size, messages: server.messagesOf(id).length, batches: server.batches.length });+ const before = state();+ const refusing = budgetedPages(server, { refuse: contentRead });+ try {+ const out = await driveBuild(spec, appDir, { genpage: refusing.genpage, runOpts: pagesWorkspace(appDir), deps: { throttle: refusing.throttle } });+ assert.ok(out.halt, 'the build stops');+ assert.strictEqual(out.halt.code, 'throttle-budget-exhausted', 'with the budget\'s halt, and not "the page cannot be read"');+ assert.strictEqual(isTransientHalt(out.halt), true, 'a transient halt: a later run goes on from here');+ assert.match(out.halt.message, /^pages stopped: the service asked to wait 600 s before the next send, which does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service \(0 s are spent\)/);+ assert.strictEqual(out.attempts, 1, 'and the run is not run again to meet the same answer');+ assert.deepStrictEqual(refusing.waits, [], 'nothing was waited for');+ assert.ok(refusing.throttle.declined().count >= 1, 'the client told the budget');+ assert.deepStrictEqual(state(), before, 'nothing was written: no page, no turn, no change set');+ assert.strictEqual(pendingOfDriven(spec, appDir).size, 0);+ } finally { await refusing.genpage.dispose(); }+ const healthy = budgetedPages(server);+ try {+ const out = await driveBuild(spec, appDir, { genpage: healthy.genpage, runOpts: pagesWorkspace(appDir), deps: { throttle: healthy.throttle } });+ assert.strictEqual(out.halt, null);+ assert.deepStrictEqual(state(), { pages: before.pages, messages: before.messages + 2, batches: before.batches + 1 }, 'the next run updates the page once: one more turn, one more change set');+ assert.ok(server.rowText(id, 'src/pages/page.tsx').includes('Edited'));+ } finally {+ await healthy.genpage.dispose();+ fs.rmSync(appDir, { recursive: true, force: true });+ }+});++test('the backend: a read of a page that the budget refused to wait for says it is the throttle — HTTP 429, nothing changed, what the service asked — and the same read refused until the sends ran out is as final as it ever was', async () => {+ const { isTransientHalt } = require('../build-model-app.js');+ const ID = '9d3a77c1-0000-4000-8000-0000000000d1';+ const edit = { source: PAGE_SOURCE.replace('Page</div>', 'Edited</div>'), prompt: 'edit', agentMessage: 'done' };+ const attempt = async (options, call) => {+ const server = new FakeGenPageServer();+ server.seedPage(ID, { name: 'Overview', source: PAGE_SOURCE });+ const stack = budgetedPages(server, { refuse: contentRead, ...options });+ try { return { ...stack, server, error: await call(stack.genpage).then(() => null, (e) => e) }; } finally { await stack.genpage.dispose(); }+ };+ const update = (genpage) => genpage.update(ID, edit);+ const read = (genpage) => genpage.read(ID);+ // The budget has no room for the ten minutes the service asked.+ for (const [what, call, message] of [['update', update, /^could not read page \S+ before updating it \(HTTP 429 .*\) — nothing was changed$/], ['read', read, /^could not read page \S+: HTTP 429 /]]) {+ const refused = await attempt({}, call);+ const { error } = refused;+ assert.ok(error, what);+ assert.strictEqual(error.code, 'GENPAGE_UNREADABLE', what);+ assert.notStrictEqual(error.transient, false, `${what}: the service's load is not final`);+ assert.strictEqual(isTransientHalt(error), true, what);+ assert.strictEqual(error.statusCode, 429, what);+ assert.strictEqual(error.cause.code, 'CONNECTION_ERROR', `${what}: the SDK's own error is the cause`);+ assert.strictEqual(error.cause.statusCode, 429, what);+ assert.strictEqual(error.retryAfterMs, 600000, `${what}: what the service asked, whole`);+ assert.strictEqual(error.retryNotBefore, refused.clock.now() + 600000, `${what}: and the moment before which nothing may be sent`);+ assert.match(error.message, message, what);+ assert.deepStrictEqual(refused.waits, [], `${what}: nothing was waited for`);+ assert.strictEqual(refused.server.batches.length, 0, `${what}: nothing was written`);+ if (what === 'update') assert.deepStrictEqual([error.outcome, error.pageId], ['nothing', ID], 'an update says it changed nothing');+ }+ // The same refusal where the budget had room: every wait fit, the sends ran out, and the read failed as it always did — final, and no word of the budget.+ for (const [what, call] of [['update', update], ['read', read]]) {+ for (const [how, options] of [['with a budget that had room', { askSeconds: 1 }], ['with no budget', { askSeconds: 1, budget: false }]]) {+ const ran = await attempt(options, call);+ assert.ok(ran.error, `${what} ${how}`);+ assert.strictEqual(ran.error.code, 'GENPAGE_UNREADABLE', `${what} ${how}`);+ assert.strictEqual(ran.error.transient, false, `${what} ${how}: the sends ran out, which this has always been final`);+ assert.strictEqual(isTransientHalt(ran.error), false, `${what} ${how}`);+ assert.strictEqual(ran.error.retryAfterMs, undefined, `${what} ${how}`);+ assert.ok(ran.waits.length > 0, `${what} ${how}: the client waited, as the schedule has it`);+ assert.strictEqual(ran.throttle.declined().count, 0, `${what} ${how}: no wait was refused`);+ }+ }+});++test('deploy: a page under a pending id whose read the budget refused to wait for is not a conflict — the engine stops with a transient halt, the record stays and nothing is written', async () => {+ const { isTransientHalt } = require('../build-model-app.js');+ const { appDir, spec } = onePageApp('Overview');+ fs.writeFileSync(path.join(appDir, 'p.tsx'), PAGE_SOURCE, 'utf8');+ const workspaceDir = path.join(appDir, '.maker-workspace');+ const server = new FakeGenPageServer();+ const ID = '9d3a77c1-0000-4000-8000-0000000000d2';+ server.seedPage(ID, { name: 'Overview', source: PAGE_SOURCE });+ recordPagePending(workspaceDir, appUniqueName(spec), 'p', ID, 'Overview', BUILD_ENV, sha256(PAGE_SOURCE));+ try {+ await assert.rejects(buildPages(spec, appDir, budgetedPages(server, { refuse: contentRead }).genpage), (e) => {+ assert.strictEqual(e.code, 'pages-read-throttled', 'not "pages-identity-conflict", which tells the maker to delete a record');+ assert.strictEqual(e.phase, 'pages');+ assert.strictEqual(e.recoverable, true);+ assert.strictEqual(isTransientHalt(e), true, 'a run again may find the service ready');+ assert.match(e.message, new RegExp(`^could not read page ${ID}, which an earlier build started creating for "p", because the service throttled the read \\(.*HTTP 429.*\\) — nothing was changed`));+ return true;+ });+ assert.deepStrictEqual(server.writes(), [], 'nothing was written');+ assert.deepStrictEqual(receiptsOf(spec, appDir), [], 'no receipt was made out of the record');+ assert.strictEqual(pendingOf(spec, appDir).size, 1, 'and the record stays, for the run that can read the page');+ // A page that cannot be read for another reason stays the conflict it was: the reading of the 503 is the service's own words and no word of the budget.+ const unread = new FakeGenPageServer();+ unread.seedPage(ID, { name: 'Overview', source: PAGE_SOURCE });+ unread.failOn = rowReadsFail;+ await assert.rejects(buildPages(spec, appDir, realPageBackend(unread)), (e) => e.code === 'pages-identity-conflict');+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }+});++test('deploy: through the build, a page under a pending id whose read the budget refused to wait for stops the build with the budget\'s halt — and the next run reads the page, proves it holds what was sent and adopts it', async () => {+ const { isTransientHalt } = require('../build-model-app.js');+ const { appDir, spec } = onePageApp('Overview');+ fs.writeFileSync(path.join(appDir, 'p.tsx'), PAGE_SOURCE, 'utf8');+ const server = new FakeGenPageServer();+ const ID = '9d3a77c1-0000-4000-8000-0000000000d3';+ server.seedPage(ID, { name: 'Overview', source: PAGE_SOURCE });+ recordPagePending(path.join(appDir, '.maker-workspace'), appUniqueName(spec), 'p', ID, 'Overview', PAGE_SERVICE, sha256(PAGE_SOURCE));+ const refusing = budgetedPages(server, { refuse: contentRead });+ try {+ const out = await driveBuild(spec, appDir, { genpage: refusing.genpage, runOpts: pagesWorkspace(appDir), deps: { throttle: refusing.throttle } });+ assert.ok(out.halt, 'the build stops');+ assert.strictEqual(out.halt.code, 'throttle-budget-exhausted');+ assert.strictEqual(isTransientHalt(out.halt), true);+ assert.match(out.halt.message, /^pages stopped: the service asked to wait 600 s before the next send, which does not fit/);+ assert.strictEqual(out.attempts, 1);+ assert.deepStrictEqual(refusing.waits, []);+ assert.deepStrictEqual(server.writes(), [], 'nothing was written');+ assert.strictEqual(pendingOfDriven(spec, appDir).size, 1, 'the record of the create stays');+ } finally { await refusing.genpage.dispose(); }+ const healthy = budgetedPages(server);+ try {+ const out = await driveBuild(spec, appDir, { genpage: healthy.genpage, runOpts: pagesWorkspace(appDir), deps: { throttle: healthy.throttle } });+ assert.strictEqual(out.halt, null);+ assert.strictEqual(out.result.created.pages.p, ID, 'the page the earlier build started is adopted');+ assert.deepStrictEqual([...server.state.projects.keys()], [ID], 'one page');+ assert.deepStrictEqual(receiptsOfDriven(spec, appDir).map((r) => r.pageId), [ID]);+ assert.strictEqual(pendingOfDriven(spec, appDir).size, 0, 'and the record is consumed on that evidence');+ } finally {+ await healthy.genpage.dispose();+ fs.rmSync(appDir, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex ca6c66217..cceb80d20 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -113,7 +113,8 @@ function seedForm(id, fields) {bag: { a: [], c: [] } };}-// `existingTables`: { logical: { entitySetName, columns:[logical...], relationships:[schema...] } }+// `existingTables`: { logical: { entitySetName, columns:[logical...], relationships:[row...] } }, a relationship row being what the SDK's+// metadata projection lists for the table: { schemaName, type, relatedEntity, relatedAttribute } (a name alone does not identify one).const MEMBER_SOLUTION_ID = '5011c0de-0000-4000-8000-000000000001'; // a GUID: the membership read interpolates it unquotedfunction mockSdk(opts = {}) {const calls = [];@@ -294,7 +295,7 @@ function mockSdk(opts = {}) {createSolution: async (o) => { calls.push({ name: 'createSolution', args: [o] }); return { id: 'sol-1' }; },findTables: async (q, o) => { calls.push({ name: 'findTables', args: [q, o] }); const t = ex[String(q).toLowerCase()]; return t ? [{ logicalName: String(q).toLowerCase(), schemaName: q, displayName: q, entitySetName: t.entitySetName, isCustom: true }] : []; },findColumns: async (logical) => { calls.push({ name: 'findColumns', args: [logical] }); const t = ex[logical]; return ((t && t.columns) || []).map((c) => ({ logicalName: c, schemaName: c, displayName: c, attributeType: 'String', isCustom: true })); },- fetchEntityMetadata: async (logical) => { calls.push({ name: 'fetchEntityMetadata', args: [logical] }); const t = ex[logical]; return { logicalName: logical, displayName: logical, entitySetName: (t && t.entitySetName) || `${logical}s`, attributes: ((t && t.columns) || []).map((c) => ({ logicalName: c })), relationships: ((t && t.relationships) || []).map((s) => ({ schemaName: s, type: 'OneToMany' })) }; },+ fetchEntityMetadata: async (logical) => { calls.push({ name: 'fetchEntityMetadata', args: [logical] }); const t = ex[logical]; return { logicalName: logical, displayName: logical, entitySetName: (t && t.entitySetName) || `${logical}s`, attributes: ((t && t.columns) || []).map((c) => ({ logicalName: c })), relationships: (t && t.relationships) || [] }; },createTable: async (o) => { calls.push({ name: 'createTable', args: [o] }); if (opts.failTable === o.schemaName) throw new Error('boom'); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}` }; },updateTable: async (l, o) => { calls.push({ name: 'updateTable', args: [l, o] }); return {}; },createColumn: async (e, o) => { calls.push({ name: 'createColumn', args: [e, o] }); return { logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }; },@@ -671,7 +672,7 @@ test('idempotent: an existing table is reused — no createTable, and only missi});test('idempotent: an existing relationship is skipped', async () => {- const { sdk, calls } = mockSdk({ existingTables: { new_customer: { entitySetName: 'new_customers', columns: [], relationships: ['new_customer_new_ticket'] } } });+ const { sdk, calls } = mockSdk({ existingTables: { new_customer: { entitySetName: 'new_customers', columns: [], relationships: [{ schemaName: 'new_customer_new_ticket', type: 'OneToMany', relatedEntity: 'new_ticket', relatedAttribute: 'new_customerid' }] } } });await runSdkBuild(makeSpec(), { sdk, apply: true });assert.strictEqual(find(calls, 'createRelationship').length, 0, 'existing relationship not re-created');});@@ -1091,11 +1092,14 @@ test('app header: if the fetched header cannot be put back the build halts rathe// Both columns are localizable (https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule), and whether// a plain write of the base-language text keeps the translations beside it has not been measured against an environment. Until it has, a-// header that is not plain text — a localized one, held as one text per language — is never replaced by a-// scalar: the edit is left unapplied, with a warning, and nothing else about the push changes.+// header text that is not plain — a localized one, held as one text per language — is never replaced by a+// scalar: its own edit is left unapplied, with a warning, and nothing else about the push changes. The text is taken off the copy right before+// the push (`removeElement`), so the SDK — which writes every text the copy holds when its own comparison read of the header fails — has none of it to write.const localized = (english, french) => ({ '1033': english, '1036': french });+const headerRemovals = (calls) => appCalls(calls, 'removeElement', (c) => c.args[2] === '/name' || c.args[2] === '/description').map((c) => c.args[2]);+const beforeTheFirstPush = (calls, call) => calls.indexOf(call) < calls.indexOf(appCalls(calls, 'pushArtifact')[0]);-test('app header: a localized name and description are never replaced by a scalar — they are left as they are and the build says the edit was not applied', async () => {+test('app header: a localized name and description are never replaced by a scalar — they are taken off the copy before the push, and the build says the edit was not applied', async () => {const name = localized('Support Desk', 'Bureau d\u2019assistance');const description = localized('Tickets', 'Billets');const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppName: name, existingAppDescription: description });@@ -1103,16 +1107,17 @@ test('app header: a localized name and description are never replaced by a scalaconst result = await runSdkBuild(describedSpec(), { sdk, apply: true, phases: appShellPhases, warn: (m) => warnings.push(m) });assert.strictEqual(result.ok, true);assert.deepStrictEqual(headerEdits(calls), [], 'no write to the header text at all');+ assert.deepStrictEqual(headerRemovals(calls), ['/name', '/description'], 'both texts are taken off the copy');+ assert.ok(appCalls(calls, 'removeElement').every((c) => beforeTheFirstPush(calls, c)), 'before the push that would otherwise offer them to the SDK');const held = await sdk.getArtifact('app', appCalls(calls, 'pushArtifact')[0].args[1]);- assert.deepStrictEqual(held.name, name, 'the name is still the map — the spec\u2019s name is its English text: the unchanged-name, changed-description case');- assert.deepStrictEqual(held.description, description, 'the description is still the map');+ assert.deepStrictEqual([held.name, held.description], [undefined, undefined], 'neither is on the copy any more, and neither was ever replaced by a scalar');const notApplied = warnings.filter((w) => /was not applied/.test(w));assert.strictEqual(notApplied.length, 1, JSON.stringify(warnings));assert.match(notApplied[0], /^app "Support Desk": its description was not applied: it is localized \(2 languages: 1033, 1036\)/);assert.strictEqual(appCalls(calls, 'pushArtifact').length, 1, 'the sitemap push is as it always is');});-test('app header: a localized name the spec changes is not applied either — and neither is the description beside it', async () => {+test('app header: a localized name and a localized description the spec changes are each left as they are, and the build says so for each', async () => {const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppName: localized('Support Desk', 'Bureau d\u2019assistance'), existingAppDescription: localized('Tickets', 'Billets') });const warnings = [];await runSdkBuild(makeSpec({ app: { name: 'Help Desk', uniqueName: 'new_supportdesk', description: DESCRIBED } }), { sdk, apply: true, phases: appShellPhases, warn: (m) => warnings.push(m) });@@ -1120,83 +1125,78 @@ test('app header: a localized name the spec changes is not applied either — anassert.strictEqual(warnings.filter((w) => /was not applied/.test(w)).length, 2, JSON.stringify(warnings));assert.ok(warnings.some((w) => /^app "Help Desk": its name was not applied: it is localized/.test(w)));assert.ok(warnings.some((w) => /^app "Help Desk": its description was not applied: it is localized/.test(w)));+ assert.deepStrictEqual(headerRemovals(calls), ['/name', '/description']);});-// The SDK's header push writes the artifact's `name` AND `description` in ONE request, whichever of them an edit changed (pinned against the-// real bundle in app-header-text-real-bundle.test.js, which also shows what goes over the wire). So an edit of the plain one beside a-// localized sibling would send the localized one with it — a map in a String column, or a scalar over a text that carries translations.-// The header is therefore held whole: while either text is not plain, no edit of the header rides the push, and the build says which-// edits it left and why.+// The SDK's header push writes only the texts that changed, and neither compares nor writes a text removed from the copy (pinned against the real bundle in+// app-header-text-real-bundle.test.js, which also shows what goes over the wire). So a text that is not plain is taken off the copy and holds back its OWN edit+// only: the plain text beside it, and a routing description, are applied as usual and written alone.const NOT_APPLIED = /was not applied/;const notAppliedOf = (warnings) => warnings.filter((w) => NOT_APPLIED.test(w));-const WRITTEN_TOGETHER = /, and the app's name and description are written in one request, so changing its (name|description) would send the (name|description) too — a rebuild never sends a text that is not plain\. Change it in Power Apps\.$/;-test('app header: a plain-text name or description beside a localized one is NOT applied either — the SDK would send the localized one with it', async () => {+test('app header: a plain-text name beside a localized description IS applied, on its own — only the localized description\u2019s edit is left, and it is taken off the copy', async () => {const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppDescription: localized('Tickets', 'Billets') });const warnings = [];const result = await runSdkBuild(makeSpec({ app: { name: 'Help Desk', uniqueName: 'new_supportdesk', description: DESCRIBED } }), { sdk, apply: true, phases: appShellPhases, warn: (m) => warnings.push(m) });assert.strictEqual(result.ok, true);- assert.deepStrictEqual(headerEdits(calls), [], 'the name is plain text, but it would be sent beside the localized description: nothing is written');+ assert.deepStrictEqual(headerEdits(calls), [['/name', 'Help Desk']], 'the plain name is written; the localized description is not');const notApplied = notAppliedOf(warnings);- assert.strictEqual(notApplied.length, 2, JSON.stringify(warnings));- assert.ok(notApplied.some((w) => /^app "Help Desk": its description was not applied: it is localized \(2 languages: 1033, 1036\)/.test(w)), JSON.stringify(notApplied));- const blocked = notApplied.find((w) => /^app "Help Desk": its name was not applied: /.test(w));- assert.ok(blocked, JSON.stringify(notApplied));- assert.match(blocked, /^app "Help Desk": its name was not applied: the app's description is localized \(2 languages: 1033, 1036\)/);- assert.match(blocked, WRITTEN_TOGETHER);- assert.strictEqual(appCalls(calls, 'pushArtifact').length, 1, 'the sitemap push is made as it always is');+ assert.strictEqual(notApplied.length, 1, JSON.stringify(warnings));+ assert.match(notApplied[0], /^app "Help Desk": its description was not applied: it is localized \(2 languages: 1033, 1036\)/);+ assert.deepStrictEqual(headerRemovals(calls), ['/description']);+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 1, 'one push carries the name and the navigation');const held = await sdk.getArtifact('app', appCalls(calls, 'pushArtifact')[0].args[1]);- assert.deepStrictEqual([held.name, held.description], ['Support Desk', localized('Tickets', 'Billets')], 'the copy that push carries is the fetched header, untouched');+ assert.deepStrictEqual([held.name, held.description], ['Help Desk', undefined], 'the copy that push carries holds the new name and none of the localized description');});-test('app header: a localized name the spec leaves as it is, beside a description it changes — the description is not applied, and the name is not mentioned', async () => {+test('app header: a localized name the spec leaves as it is, beside a description it changes — the description is applied, and the name is not mentioned', async () => {const name = localized('Support Desk', 'Bureau d\u2019assistance');const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppName: name });const warnings = [];await runSdkBuild(describedSpec(), { sdk, apply: true, phases: appShellPhases, warn: (m) => warnings.push(m) });- assert.deepStrictEqual(headerEdits(calls), []);- const notApplied = notAppliedOf(warnings);- assert.strictEqual(notApplied.length, 1, JSON.stringify(warnings));- assert.match(notApplied[0], /^app "Support Desk": its description was not applied: the app's name is localized \(2 languages: 1033, 1036\)/);- assert.match(notApplied[0], WRITTEN_TOGETHER);- assert.deepStrictEqual((await sdk.getArtifact('app', appCalls(calls, 'pushArtifact')[0].args[1])).name, name);+ assert.deepStrictEqual(headerEdits(calls), [['/description', DESCRIBED]]);+ assert.deepStrictEqual(notAppliedOf(warnings), []);+ assert.deepStrictEqual(headerRemovals(calls), ['/name']);+ const held = await sdk.getArtifact('app', appCalls(calls, 'pushArtifact')[0].args[1]);+ assert.deepStrictEqual([held.name, held.description], [undefined, DESCRIBED]);});-test('app header: a header of ANY shape that is not plain text holds back the edit of the other one', async () => {+test('app header: a header text of ANY shape that is not plain holds back its own edit only — the other text is applied', async () => {const unreadable = [['an array', ['Support Desk']], ['a number', 42], ['null', null], ['a localized text', localized('Support Desk', 'Bureau d\u2019assistance')]];for (const [what, shape] of unreadable) {- // …in the name, beside a changed plain description+ // …in the name, beside a changed plain description: the description is written. The name's own edit is the spec's name, which an array, a number or a null does not hold — said once;+ // the localized text holds it (it is one of its entries), so it needs no word.const inName = mockSdk({ artifactsExist: true, existingAppName: shape });const nameWarnings = [];await runSdkBuild(describedSpec(), { sdk: inName.sdk, apply: true, phases: appShellPhases, warn: (m) => nameWarnings.push(m) });- assert.deepStrictEqual(headerEdits(inName.calls), [], `${what} in the name`);- const blockedDescription = notAppliedOf(nameWarnings).filter((w) => /^app "Support Desk": its description was not applied: the app's name (is localized|could not be read as plain text)/.test(w));- assert.strictEqual(blockedDescription.length, 1, `${what} in the name: ${JSON.stringify(nameWarnings)}`);- assert.match(blockedDescription[0], WRITTEN_TOGETHER);- // …and in the description, beside a changed plain name+ assert.deepStrictEqual(headerEdits(inName.calls), [['/description', DESCRIBED]], `${what} in the name`);+ assert.deepStrictEqual(headerRemovals(inName.calls), ['/name'], `${what} in the name`);+ const ownName = notAppliedOf(nameWarnings);+ assert.strictEqual(ownName.length, what === 'a localized text' ? 0 : 1, `${what} in the name: ${JSON.stringify(nameWarnings)}`);+ for (const w of ownName) assert.match(w, /^app "Support Desk": its name was not applied: the app's name could not be read as plain text \(it came back as /);+ // …and in the description, beside a changed plain name: the name is written, and the description's own edit is said once.const inDescription = mockSdk({ artifactsExist: true, existingAppDescription: shape });const descriptionWarnings = [];await runSdkBuild(makeSpec({ app: { name: 'Help Desk', uniqueName: 'new_supportdesk', description: 'Tickets' } }), { sdk: inDescription.sdk, apply: true, phases: appShellPhases, warn: (m) => descriptionWarnings.push(m) });- assert.deepStrictEqual(headerEdits(inDescription.calls), [], `${what} in the description`);- assert.strictEqual(notAppliedOf(descriptionWarnings).filter((w) => /^app "Help Desk": its name was not applied: the app's description (is localized|could not be read as plain text)/.test(w)).length, 1, `${what} in the description: ${JSON.stringify(descriptionWarnings)}`);+ assert.deepStrictEqual(headerEdits(inDescription.calls), [['/name', 'Help Desk']], `${what} in the description`);+ assert.deepStrictEqual(headerRemovals(inDescription.calls), ['/description'], `${what} in the description`);+ assert.strictEqual(notAppliedOf(descriptionWarnings).filter((w) => /^app "Help Desk": its description was not applied: (it is localized|the app's description could not be read as plain text)/.test(w)).length, 1, `${what} in the description: ${JSON.stringify(descriptionWarnings)}`);assert.strictEqual(appCalls(inDescription.calls, 'pushArtifact').length, 1, `${what}: the navigation is still pushed`);}});-test('app header: a routing description is NOT applied while the header holds a text that is not plain — warned, never halted, nothing sent for it', async () => {- // Written by the same request as the name and the description, so it would send the localized one too. Held back like the text- // edits: the navigation is the app step's own work and goes on, and the warning says what to do.+test('app header: a routing description is applied beside a text that is not plain — written alone, nothing warned, and the text taken off the copy', async () => {+ // The SDK writes the routing description by itself when only it changed, so the localized name is neither in the request nor a reason to hold the routing description back.const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppName: localized('Support Desk', 'Bureau d\u2019assistance') });const warnings = [];const result = await runSdkBuild(makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } }), { sdk, apply: true, phases: appShellPhases, warn: (m) => warnings.push(m) });- assert.strictEqual(result.ok, true, 'the build goes on');- assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0, 'the routing description is not added to the copy');- assert.strictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/aiDescription').length, 0);- assert.strictEqual(appCalls(calls, 'pushArtifact').length, 1, 'the sitemap push, carrying no header edit');- const notApplied = notAppliedOf(warnings);- assert.strictEqual(notApplied.length, 1, JSON.stringify(warnings));- assert.match(notApplied[0], /^app "Support Desk": its routing description \(app\.aiDescription\) was not applied: the app's name is localized \(2 languages: 1033, 1036\), and the app's name, description and routing description are written in one request, so changing it would send the name too — a rebuild never sends a text that is not plain\. Change it in Power Apps\.$/);- // …and a routing description the app already has, or none in the spec, is not worth a word.+ assert.strictEqual(result.ok, true);+ assert.deepStrictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').map((c) => c.args[3]), [{ aiDescription: ROUTING }], 'added at the artifact root, as for a plain header');+ assert.deepStrictEqual(headerEdits(calls), []);+ assert.deepStrictEqual(headerRemovals(calls), ['/name']);+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 1, 'one push carries the routing description and the navigation');+ assert.deepStrictEqual(notAppliedOf(warnings), []);+ // …and a routing description the app already has, or none in the spec, writes nothing, as for a plain header.const quiet = [];for (const [app, over] of [[{ name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING }, { existingAppAiDescription: ROUTING }], [{ name: 'Support Desk', description: 'Tickets' }, {}]]) {const m = mockSdk({ artifactsExist: true, existingAppName: localized('Support Desk', 'Bureau d\u2019assistance'), ...over });@@ -1206,26 +1206,39 @@ test('app header: a routing description is NOT applied while the header holds aassert.deepStrictEqual(notAppliedOf(quiet), []);});-test('app header: with the pages phase the finalizer holds the header back the same way, and an app-shell-only run with a routing description pushes nothing', async () => {+test('app header: with the pages phase the finalizer applies the header the same way, and an app-shell-only run pushes a routing description beside a text that is not plain', async () => {const held = { existingAppDescription: localized('Tickets', 'Billets') };// The finalizer is the sole existing-app writer when the pages phase runs.const withPages = mockSdk({ artifactsExist: true, ...held });const warnings = [];await runSdkBuild(describedSpec({ aiDescription: ROUTING }), { sdk: withPages.sdk, apply: true, phases: fullPhases, genpageCli: noPages, warn: (m) => warnings.push(m) });- assert.deepStrictEqual(headerEdits(withPages.calls), []);- assert.strictEqual(appCalls(withPages.calls, 'addElement', (c) => c.args[2] === '').length, 0, 'no routing description either');+ assert.deepStrictEqual(headerEdits(withPages.calls), [], 'the localized description is not replaced');+ assert.deepStrictEqual(appCalls(withPages.calls, 'addElement', (c) => c.args[2] === '').map((c) => c.args[3]), [{ aiDescription: ROUTING }], 'but the routing description is applied');+ assert.deepStrictEqual(headerRemovals(withPages.calls), ['/description']);assert.strictEqual(appCalls(withPages.calls, 'pushArtifact').length, 1, 'the finalizer\u2019s sitemap push, as ever');- assert.strictEqual(notAppliedOf(warnings).filter((w) => /its routing description/.test(w)).length, 1, JSON.stringify(warnings));- assert.strictEqual(notAppliedOf(warnings).filter((w) => /its name|its description/.test(w)).length, 1, JSON.stringify(warnings));- // Without the pages phase, a page subarea defers the sitemap write, so the routing description would be the ONLY reason to push the app: held back, there is none.+ assert.strictEqual(notAppliedOf(warnings).length, 1, JSON.stringify(warnings));+ assert.match(notAppliedOf(warnings)[0], /^app "Support Desk": its description was not applied: it is localized/);+ // Without the pages phase, a page subarea defers the sitemap write, so the routing description is the ONLY reason to push the app — and it is one, with the text taken off the copy.const spec = describedSpec({ aiDescription: ROUTING });spec.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });const alone = mockSdk({ artifactsExist: true, ...held });const aloneWarnings = [];await runSdkBuild(spec, { sdk: alone.sdk, apply: true, phases: appShellPhases, warn: (m) => aloneWarnings.push(m) });- assert.strictEqual(appCalls(alone.calls, 'pushArtifact').length, 0, 'nothing to push: the only edit was held back');+ assert.strictEqual(appCalls(alone.calls, 'pushArtifact').length, 1, 'the routing description rides a push of its own, as it does for a plain header');assert.deepStrictEqual(headerEdits(alone.calls), []);- assert.strictEqual(notAppliedOf(aloneWarnings).length, 2, JSON.stringify(aloneWarnings));+ assert.deepStrictEqual(headerRemovals(alone.calls), ['/description']);+ assert.strictEqual(notAppliedOf(aloneWarnings).length, 1, JSON.stringify(aloneWarnings));+});++test('app header: a text that is not plain is taken off the copy only when a push follows — a run that pushes nothing leaves the copy as the fetch read it', async () => {+ // The same shape, with a routing description the app already has: nothing is edited, so no push is made, and an edit left on the copy would be refused by the next run (refuseUnpushedAppCopy).+ const spec = describedSpec({ aiDescription: ROUTING });+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppDescription: localized('Tickets', 'Billets'), existingAppAiDescription: ROUTING });+ await runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases, warn: () => {} });+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 0, 'nothing to push');+ assert.deepStrictEqual(headerRemovals(calls), [], 'so nothing is taken off the copy');+ assert.deepStrictEqual(headerEdits(calls), []);});test('app header: a plain header is still edited whole — the guard changes nothing when no text is held', async () => {@@ -1755,7 +1768,7 @@ test('apply progress total includes existing-column reconciliation steps', asyncnew_customer: {entitySetName: 'new_customers',columns: ['new_name', 'new_tier', 'new_score'],- relationships: ['new_customer_new_ticket'],+ relationships: [{ schemaName: 'new_customer_new_ticket', type: 'OneToMany', relatedEntity: 'new_ticket', relatedAttribute: 'new_customerid' }],},new_ticket: {entitySetName: 'new_tickets',@@ -2721,6 +2734,28 @@ test('dashboards: chart + list tiles resolve the created view/visualization ids'assert.ok(find(calls, 'addSolutionComponent').some((c) => c.args[0].componentType === 60));});+// A tile's height is its rowspan, and the app draws a one-row tile as its title bar alone, so a tile the spec does not+// size is built 12 rows tall whatever its kind, and a size the spec states reaches the payload as written. The cells the+// real bundle writes are read in dashboard-roundtrip.test.js; this drives the dashboards phase itself.+test('dashboards: a tile the spec does not size is built 12 rows by 1 column, and an authored size is kept', async () => {+ const spec = makeSpec();+ spec.dashboards = [+ { name: 'Ops', tiles: [+ { type: 'chart', chart: 'By Priority', view: 'Active Tickets' },+ { type: 'list', view: 'Active Tickets', name: 'Recent' },+ { type: 'iframe', url: 'https://contoso.com/map', name: 'Map' },+ { type: 'list', view: 'Active Tickets', name: 'Wide', colspan: 2, rowspan: 6 },+ { type: 'list', view: 'Active Tickets', name: 'Strip', rowspan: 1 },+ ] },+ ];+ const { sdk, calls } = mockSdk();+ await runSdkBuild(spec, { sdk, apply: true });+ const sizes = find(calls, 'addElement')+ .filter((c) => c.args[0] === 'dashboard' && c.args[2] === '/components')+ .map((c) => [c.args[3].name, c.args[3].rowspan, c.args[3].colspan]);+ assert.deepStrictEqual(sizes, [['By Priority', 12, 1], ['Recent', 12, 1], ['Map', 12, 1], ['Wide', 6, 2], ['Strip', 1, 1]]);+});+test('app-shell: a live sitemap target absent from the gate approval halts before the app push', async () => {const spec = makeSpec();const existingSitemap = { areas: [{ groups: [{ subAreas: [@@ -2828,6 +2863,24 @@ test('dashboards: a pin that names a form, not a dashboard, halts instead of wirassert.ok(!find(calls, 'createArtifact').some((c) => c.args[0] === 'dashboard'));});+// The build never applies tile edits to a dashboard that exists — it reuses the dashboard as it is — so a dashboard an+// earlier version built keeps its one-row tiles when the default tile height changes. A rebuild adds no tile and pushes+// nothing, whether it finds the dashboard by name or by the id a download recorded.+test('dashboards: a rebuild does not resize the tiles of a dashboard that already exists', async () => {+ const touched = (calls) => ['addElement', 'updateElement', 'removeElement', 'pushArtifact']+ .flatMap((name) => find(calls, name))+ .filter((c) => c.args[0] === 'dashboard');+ const byName = makeSpec();+ byName.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ const named = mockSdk({ existingDashboards: ['Ops'] });+ await runSdkBuild(byName, { sdk: named.sdk, apply: true });+ assert.deepStrictEqual(touched(named.calls), [], 'a dashboard found by name is reused as it is');+ const pinned = mockSdk();+ answerPinned(pinned.sdk, { [PINNED_DASH]: { formid: PINNED_DASH, name: 'Command Center - Event operations', type: 0 } });+ await runSdkBuild(pinnedSpec(), { sdk: pinned.sdk, apply: true });+ assert.deepStrictEqual(touched(pinned.calls), [], 'a dashboard found by its pinned id is reused as it is');+});+// Names are neither unique nor compared exactly, so the lookup can return several dashboards. Reusing// the first one returned silently bound the app to an arbitrary one — possibly another app's. The app's// own is the one its solution holds; when that does not single one out the build halts, creating nothing.diff --git a/plugins/model-apps/scripts/tests/sdk-http-client-scrub.test.js b/plugins/model-apps/scripts/tests/sdk-http-client-scrub.test.jsindex ccc3dcff2..0b0a24a1c 100644--- a/plugins/model-apps/scripts/tests/sdk-http-client-scrub.test.js+++ b/plugins/model-apps/scripts/tests/sdk-http-client-scrub.test.js@@ -7,7 +7,7 @@ const test = require('node:test');const assert = require('node:assert/strict');const fs = require('node:fs');const path = require('node:path');-const { createAzHttpClient, scrub, scrubAnswer } = require('../lib/sdk-http-client.js');+const { createAzHttpClient, scrub, scrubAnswer, completeBatchStatus } = require('../lib/sdk-http-client.js');const ORIGIN = 'https://contoso.crm.dynamics.com';const API = `${ORIGIN}/api/data/v9.0`;@@ -146,6 +146,19 @@ test('a SUCCESS is never touched: its JSON, its raw text and its bytes are returassert.equal((await headed.client.get(`${API}/WhoAmI`)).headers['x-echo'], TOKEN);});+test('a change set the service refuses as a whole is a SUCCESS to the client — HTTP 200, the failed part inside — and is returned as it came, token and all: the strict readers count its bytes, and the token is taken out of what the process writes (lib/output-redaction.js)', async () => {+ const detail = JSON.stringify({ error: { code: '0x80040220', message: `Principal user rejected bearer ${TOKEN} for this write` } });+ const refused = ['--batchresponse_x', 'Content-Type: multipart/mixed; boundary=changesetresponse_x', '', '--changesetresponse_x', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', 'Content-ID: 1', '',+ 'HTTP/1.1 403 Forbidden', 'Content-Type: application/json', `Content-Length: ${Buffer.byteLength(detail)}`, '', detail, '--changesetresponse_x--', '--batchresponse_x--', ''].join('\r\n');+ const { client, sent } = clientOver([answer(200, refused)]);+ const res = await client.postRaw(`${API}/$batch`, 'x');+ assert.equal(sent.length, 1, 'it is sent once');+ assert.equal(res.status, 200);+ assert.equal(res.body, refused, 'the very text the service sent');+ assert.ok(res.body.includes(TOKEN), 'with the token in it');+ assert.equal(completeBatchStatus({ body: res.body }), 403, 'and the strict reader proves the refusal from it, as it does from the service\'s own');+});+test('an answer that is not a success is scrubbed in every mode the client reads in — raw text and bytes as well — and one that holds no token is returned as the same text and the same Buffer', async () => {const refusedBatch = answer(400, `{"error":{"message":"batch refused: ${TOKEN}"}}`);const raw = clientOver([refusedBatch]);diff --git a/plugins/model-apps/scripts/tests/sdk-http-client.test.js b/plugins/model-apps/scripts/tests/sdk-http-client.test.jsindex 4097579ae..7edcfa8b2 100644--- a/plugins/model-apps/scripts/tests/sdk-http-client.test.js+++ b/plugins/model-apps/scripts/tests/sdk-http-client.test.js@@ -1461,6 +1461,260 @@ test('retryAfterMs and batchRetryAfterMs cap what they read at RETRY_AFTER_CAP_Massert.strictEqual(batchRetryAfterMs({ body: part }, NOW, Infinity), 600000);});+// ── A run's throttle budget ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────+// The client's waits for a THROTTLED answer — HTTP 429, alone or as every operation of a `$batch` — are drawn from the budget a run allows itself for waiting out a throttled service (lib/throttle-budget.js) when the caller+// gives one (`deps.throttle`; the pcf plugin, which keeps a copy of this file, has none, and a client made without one waits exactly as it always did). A budgeted client waits what the service asked WHOLE — the cap of a minute is for+// the client's own bound, which the budget now is — and a wait that does not fit is not taken: the throttled answer comes back as it came, as when the sends run out, and the budget is told what the service asked. What is not+// throttling keeps its own schedule and is never drawn: a 5xx (a customization lock, a SQL deadlock, a gateway), a transport failure. Every wait here runs on a clock the wait moves, as a real one does.+const { makeThrottleBudget, refusedWait } = require('../lib/throttle-budget.js');+const ORG = 'https://org.crm.dynamics.com';+const READ = `${ORG}/api/data/v9.2/accounts`;+const CLOCK_START = Date.parse('2026-09-30T10:00:00Z');+// A budget, and the deps of a client that waits on a clock its waits move: what the waits were, and the lines the budget said.+function budgeted({ totalMs, spent = 0 } = {}) {+ let clock = CLOCK_START;+ const lines = [];+ const slept = [];+ const throttle = makeThrottleBudget({ ...(totalMs ? { totalMs } : {}), warn: (message) => lines.push(message) });+ if (spent) throttle.spend(spent);+ return { throttle, lines, slept, clock: () => clock, deps: { throttle, now: () => clock, random: () => 0, sleep: async (ms) => { slept.push(ms); clock += ms; } } };+}+const throttledAnswer = (retryAfter) => ({+ statusCode: 429,+ headers: retryAfter === undefined ? {} : { 'retry-after': String(retryAfter) },+ body: JSON.stringify({ error: { code: '0x80072322', message: 'Number of requests exceeded the limit of 6000 over time window of 300 seconds.' } }),+});+const taken = { statusCode: 200, headers: {}, body: '{"ok":true}' };+const clientOf = (transport, run, extra = {}) => createAzHttpClient(ORG, { getToken: () => 'TOK', request: transport.request, ...run.deps, ...extra });+const partRefused = (retryAfter) => ['HTTP/1.1 429 Too Many Requests' + (retryAfter ? `\r\nRetry-After: ${retryAfter}` : ''), '{}'];+// Lets the requests that are under way run to the point where they wait: each of them takes a few turns of the event loop to get its answer.+const settle = async () => { for (let i = 0; i < 20; i += 1) await new Promise((resolve) => setImmediate(resolve)); };++test('budgeted: a throttled read draws each wait from the budget — the schedule\'s, or the answer\'s Retry-After WHOLE even past the client\'s cap — and the long ones are said on the warn seam', async () => {+ // No Retry-After: the schedule (1 s, 2 s), which is quiet.+ const quiet = budgeted();+ const t1 = fakeTransport(() => (t1.calls.length <= 2 ? throttledAnswer() : taken));+ assert.strictEqual((await clientOf(t1, quiet).get(READ)).status, 200);+ assert.deepStrictEqual(quiet.slept, [1000, 2000]);+ assert.strictEqual(quiet.throttle.spentMs(), 3000, 'each wait is counted, and the budget holds exactly what was waited');+ assert.deepStrictEqual(quiet.lines, [], 'waits of up to five seconds are not worth a line');+ // A minute and a half: longer than the cap of a minute the client keeps for itself, and it is waited whole.+ const long = budgeted();+ const t2 = fakeTransport(() => (t2.calls.length <= 1 ? throttledAnswer(90) : taken));+ assert.strictEqual((await clientOf(t2, long).get(READ)).status, 200);+ assert.deepStrictEqual(long.slept, [90000], 'what the service asked, whole');+ assert.strictEqual(long.throttle.spentMs(), 90000);+ assert.deepStrictEqual(long.lines, ['the service throttled GET /api/data/v9.2/accounts (HTTP 429); waiting 90 s before sending it again (90 s of the 5 minutes a run allows itself for waiting out a throttled service are spent)']);+ // The date form of Retry-After is read against the clock of the client.+ const dated = budgeted();+ const t3 = fakeTransport(() => (t3.calls.length <= 1 ? { ...throttledAnswer(), headers: { 'retry-after': 'Wed, 30 Sep 2026 10:01:15 GMT' } } : taken));+ await clientOf(t3, dated).get(READ);+ assert.deepStrictEqual(dated.slept, [75000]);+ assert.strictEqual(dated.throttle.spentMs(), 75000);+ // The schedule is the floor: a short ask waits the schedule's wait, as ever.+ const short = budgeted();+ const t4 = fakeTransport(() => (t4.calls.length <= 1 ? throttledAnswer(1) : taken));+ await clientOf(t4, short).get(READ);+ assert.deepStrictEqual(short.slept, [1000]);+ const longer = budgeted();+ const t5 = fakeTransport(() => (t5.calls.length <= 3 ? throttledAnswer(1) : taken));+ await clientOf(t5, longer).get(READ);+ assert.deepStrictEqual(longer.slept, [1000, 2000, 4000], 'the schedule goes on growing under a short ask, and the budget holds all of it');+ assert.strictEqual(longer.throttle.spentMs(), 7000);+});++test('budgeted: a wait that does not fit is not taken — the throttled answer comes back as it came, nothing is sent again, and the budget is told what the service asked', async () => {+ const run = budgeted({ spent: 250000 });+ const t = fakeTransport(throttledAnswer(120));+ const res = await clientOf(t, run).get(READ);+ assert.strictEqual(t.calls.length, 1, 'the request was sent once, and not again');+ assert.deepStrictEqual(run.slept, [], 'and nothing was waited for');+ assert.strictEqual(res.status, 429, 'the answer is the 429 the service gave, which the SDK reports as what it is');+ assert.deepStrictEqual(res.body, JSON.parse(throttledAnswer().body), 'its body is as it came, parsed as any answer\'s is');+ assert.strictEqual(res.headers['retry-after'], '120', 'and its headers');+ assert.strictEqual(run.throttle.spentMs(), 250000, 'nothing is spent on a wait that was not taken');+ assert.deepStrictEqual(run.throttle.declined(), { count: 1, askedMs: 120000, waitMs: 120000 });+ assert.deepStrictEqual(run.lines, [refusedWait(run.throttle, { askedMs: 120000, waitMs: 120000 })], 'and the line says what the service asked and that the request was not sent again');+ assert.doesNotMatch(run.lines[0], /same command|again later|Nothing more is sent now/, 'and gives no advice on what to run: the client does not know what the caller has done before this request');+ // An ask longer than the whole budget stops the request at once, with nothing spent.+ const huge = budgeted();+ const th = fakeTransport(throttledAnswer(3600));+ assert.strictEqual((await clientOf(th, huge).get(READ)).status, 429);+ assert.strictEqual(th.calls.length, 1);+ assert.deepStrictEqual([huge.slept, huge.throttle.spentMs(), huge.throttle.declined().askedMs], [[], 0, 3600000]);+ // The same answer from a client with no budget is waited out on the schedule it always had: a minute at most per wait.+ const slept = [];+ const plain = fakeTransport(() => (plain.calls.length <= 1 ? throttledAnswer(3600) : taken));+ const unbudgeted = createAzHttpClient(ORG, { getToken: () => 'TOK', request: plain.request, random: () => 0, sleep: async (ms) => { slept.push(ms); } });+ assert.strictEqual((await unbudgeted.get(READ)).status, 200);+ assert.deepStrictEqual(slept, [RETRY_AFTER_CAP_MS]);+});++test('budgeted: the budget ends a throttled request where the schedule would have gone on — what fits is waited, the first wait that does not fit is not, and the sends that were left are not made', async () => {+ const run = budgeted({ totalMs: 20000 });+ const t = fakeTransport(throttledAnswer());+ const res = await clientOf(t, run).get(READ);+ assert.deepStrictEqual(run.slept, [1000, 2000, 4000, 8000], '1, 2, 4 and 8 s are 15 of the 20 s');+ assert.strictEqual(t.calls.length, 5, 'five sends; the sixth is not made, because the 8 s before it do not fit in the 5 that are left');+ assert.strictEqual(res.status, 429);+ assert.deepStrictEqual(run.throttle.declined(), { count: 1, askedMs: 0, waitMs: 8000 }, 'the service asked for nothing: the wait that did not fit is the schedule\'s');+ assert.strictEqual(run.lines.length, 2);+ assert.match(run.lines[0], /^the service throttled GET \/api\/data\/v9\.2\/accounts \(HTTP 429\); waiting 8 s before sending it again \(15 s of the 20 seconds a run allows itself/);+ assert.match(run.lines[1], /^the next wait before this request is sent again, 8 s, does not fit in what is left of the 20 seconds a run allows itself for waiting out a throttled service \(15 s are spent\), so it was not sent again\.$/);+ // When the schedule ends first it is the sends that ran out, as ever, and the budget is not told of anything.+ const roomy = budgeted();+ const t2 = fakeTransport(throttledAnswer());+ assert.strictEqual((await clientOf(t2, roomy).get(READ)).status, 429);+ assert.strictEqual(t2.calls.length, 6, 'six sends in all');+ assert.deepStrictEqual(roomy.slept, [1000, 2000, 4000, 8000, 8000]);+ assert.strictEqual(roomy.throttle.spentMs(), 23000);+ assert.strictEqual(roomy.throttle.declined().count, 0, 'the budget did not stop it');+});++test('budgeted: every wait of a throttled request is drawn — a record delete refused with 429, and a $batch of conditional deletes or of column creates refused in either shape, whole or by the Retry-After of one operation', async () => {+ const batchHeaders = { headers: { 'Content-Type': 'multipart/mixed;boundary=batch_b' } };+ const sends = [+ ['a record delete', (http) => http.delete(`${ORG}/api/data/v9.0/solutions(1)`), UNINSTALL_429, 204],+ ['conditional deletes, the whole request refused', (http) => postBatch(http, APP_DELETE), { statusCode: 429, headers: {}, body: '' }, 200],+ ['conditional deletes, every operation refused', (http) => postBatch(http, APP_DELETE), { statusCode: 200, headers: {}, body: batchAnswer(partRefused(), partRefused()) }, 200],+ ['column creates, the whole request refused', (http) => postBatch(http, COLUMNS), TABLE_LOCKED_429, 200],+ ['column creates, every operation refused', (http) => postBatch(http, COLUMNS), { statusCode: 429, headers: {}, body: batchAnswer(partRefused(), partRefused()) }, 200],+ ];+ for (const [what, send, refused, then] of sends) {+ const run = budgeted();+ const t = fakeTransport(() => (t.calls.length <= 2 ? refused : { statusCode: then, headers: {}, body: then === 204 ? '' : BATCH_RESPONSE }));+ const res = await send(clientOf(t, run));+ assert.strictEqual(res.status, then, what);+ assert.strictEqual(t.calls.length, 3, `${what}: sent again twice`);+ assert.deepStrictEqual(run.slept, [1000, 2000], `${what}: on the schedule`);+ assert.strictEqual(run.throttle.spentMs(), 3000, `${what}: and drawn from the budget`);+ }+ // The wait a refused operation asks for in its own headers is honoured whole, as the outer one is.+ for (const [kind, batch] of [['conditional deletes', APP_DELETE], ['column creates', COLUMNS]]) {+ const run = budgeted();+ const t = fakeTransport(() => (t.calls.length <= 1 ? { statusCode: 429, headers: { 'retry-after': '10' }, body: batchAnswer(partRefused('150')) } : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }));+ await postBatch(clientOf(t, run), batch);+ assert.deepStrictEqual(run.slept, [150000], `${kind}: the longer of the outer and the operation's, whole, past the cap of a minute`);+ assert.strictEqual(run.throttle.spentMs(), 150000);+ // And one that does not fit comes back as it came, with what it asked said.+ const full = budgeted({ spent: 200000 });+ const t2 = fakeTransport({ statusCode: 429, headers: {}, body: batchAnswer(partRefused('150')) });+ const res = await postBatch(clientOf(t2, full), batch);+ assert.strictEqual(t2.calls.length, 1, `${kind}: not sent again`);+ assert.strictEqual(res.status, 429);+ assert.strictEqual(res.body, batchAnswer(partRefused('150')), `${kind}: and the answer is the raw envelope, as it came`);+ assert.deepStrictEqual(full.throttle.declined(), { count: 1, askedMs: 150000, waitMs: 150000 });+ }+});++test('budgeted: what is not throttling keeps its own schedule and is never drawn — a 5xx whatever Retry-After it carries, a transport failure, a SQL deadlock victim — even when the budget has nothing left', async () => {+ const spentAll = () => budgeted({ spent: 300000 });+ // A 5xx waits as it did: the schedule, or the Retry-After it carries up to the cap of a minute, and the budget does not hear of it.+ for (const status of [500, 502, 503, 504]) {+ const run = spentAll();+ const t = fakeTransport(() => (t.calls.length <= 2 ? { statusCode: status, headers: { 'retry-after': '30' }, body: '' } : taken));+ assert.strictEqual((await clientOf(t, run).get(READ)).status, 200, String(status));+ assert.deepStrictEqual(run.slept, [30000, 30000], `${status}: the Retry-After it carried, capped as ever`);+ assert.deepStrictEqual([run.throttle.spentMs(), run.throttle.declined().count], [300000, 0], `${status}: nothing was drawn, and nothing declined`);+ const capped = spentAll();+ const t2 = fakeTransport(() => (t2.calls.length <= 1 ? { statusCode: status, headers: { 'retry-after': '600' }, body: '' } : taken));+ await clientOf(t2, capped).get(READ);+ assert.deepStrictEqual(capped.slept, [RETRY_AFTER_CAP_MS], `${status}: a long Retry-After is capped at a minute, because it is not a throttle's`);+ }+ // A transport failure (a reset) waits the schedule and sends again.+ const reset = spentAll();+ const t3 = fakeTransport(() => (t3.calls.length <= 2 ? { error: 'read ECONNRESET', code: 'ECONNRESET' } : taken));+ assert.strictEqual((await clientOf(t3, reset).get(READ)).status, 200);+ assert.deepStrictEqual(reset.slept, [1000, 2000]);+ assert.strictEqual(reset.throttle.spentMs(), 300000);+ // A record delete and a change set of conditional deletes that lost a SQL deadlock are sent again on the deadlock's own schedule.+ for (const [what, send, lost] of [['a record delete', (http) => http.delete(`${ORG}/api/data/v9.0/workflows(1)`), DEADLOCK_500], ['conditional deletes', (http) => postBatch(http, APP_DELETE), BATCH_DEADLOCK_500]]) {+ const run = spentAll();+ const t4 = fakeTransport(() => (t4.calls.length <= 3 ? lost : { statusCode: 204, headers: {}, body: '' }));+ await send(clientOf(t4, run));+ assert.strictEqual(t4.calls.length, 4, what);+ assert.deepStrictEqual(run.slept, [1000, 2000, 4000], `${what}: 1 s, 2 s and 4 s`);+ assert.deepStrictEqual([run.throttle.spentMs(), run.throttle.declined().count], [300000, 0], `${what}: none of it drawn`);+ }+});++test('budgeted: a request the caller sends once is sent once — a 429 is handed back with nothing waited for, nothing drawn and nothing declined', async () => {+ const run = budgeted();+ const t = fakeTransport(() => (t.calls.length <= 1 ? throttledAnswer(30) : taken));+ const res = await clientOf(t, run, { sendOnce: () => true }).get(READ);+ assert.strictEqual(res.status, 429);+ assert.strictEqual(t.calls.length, 1);+ assert.deepStrictEqual([run.slept, run.throttle.spentMs(), run.throttle.declined().count], [[], 0, 0]);+});++test('budgeted: a client given nothing that is a budget waits as it always did', async () => {+ for (const throttle of [undefined, null, {}, 'five minutes', { fits: true }]) {+ const slept = [];+ const t = fakeTransport(() => (t.calls.length <= 1 ? throttledAnswer(600) : taken));+ const http = createAzHttpClient(ORG, { getToken: () => 'TOK', request: t.request, random: () => 0, sleep: async (ms) => { slept.push(ms); }, throttle });+ assert.strictEqual((await http.get(READ)).status, 200, String(throttle));+ assert.deepStrictEqual(slept, [RETRY_AFTER_CAP_MS], `${JSON.stringify(throttle)}: the cap of a minute, as ever`);+ }+});++test('budgeted: requests that are throttled together wake together — their waits overlap, and the budget is charged for the time the run waited and not for the sum', async () => {+ let clock = CLOCK_START;+ const pending = [];+ const throttle = makeThrottleBudget({ totalMs: 100000 });+ // The first send of each read is refused with a minute to wait; the send that follows the wait is taken.+ const seen = new Set();+ const request = async (opts) => (seen.has(opts.url) ? taken : (seen.add(opts.url), throttledAnswer(60)));+ const http = createAzHttpClient(ORG, { getToken: () => 'TOK', request, throttle, now: () => clock, random: () => 0, sleep: (ms) => new Promise((resolve) => pending.push({ ms, resolve })) });+ const reads = [1, 2, 3, 4].map((n) => http.get(`${READ}${n}`));+ await settle();+ assert.deepStrictEqual(pending.map((p) => p.ms), [60000, 60000, 60000, 60000], 'all four are waiting a minute');+ assert.strictEqual(throttle.spentMs(), 60000, 'which is a minute of the run\'s waiting, and not four');+ clock += 60000;+ for (const p of pending.splice(0)) p.resolve();+ assert.deepStrictEqual((await Promise.all(reads)).map((r) => r.status), [200, 200, 200, 200]);+ assert.strictEqual(throttle.spentMs(), 60000);+ assert.strictEqual(throttle.declined().count, 0);+});++test('budgeted: requests throttled together are each judged by what they would add — the ones that end inside the wait under way fit, the one that runs past what is left does not', async () => {+ let clock = CLOCK_START;+ const pending = [];+ const throttle = makeThrottleBudget({ totalMs: 100000 });+ const asks = { a: 60, b: 90, c: 120 };+ const seen = new Set();+ const request = async (opts) => {+ const key = opts.url.slice(-1);+ if (seen.has(key)) return taken;+ seen.add(key);+ return throttledAnswer(asks[key]);+ };+ const http = createAzHttpClient(ORG, { getToken: () => 'TOK', request, throttle, now: () => clock, random: () => 0, sleep: (ms) => new Promise((resolve) => pending.push({ ms, resolve })) });+ const reads = ['a', 'b', 'c'].map((key) => http.get(`${READ}/${key}`));+ await settle();+ assert.deepStrictEqual(pending.map((p) => p.ms), [60000, 90000], 'a minute, and a minute and a half, which ends 30 s after the first');+ assert.strictEqual(throttle.spentMs(), 90000, '60 s, and the 30 s the second runs past the first');+ assert.deepStrictEqual(throttle.declined(), { count: 1, askedMs: 120000, waitMs: 120000 }, 'the third would run 30 s more past the second, and only 10 s are left');+ clock += 90000;+ for (const p of pending.splice(0)) p.resolve();+ assert.deepStrictEqual((await Promise.all(reads)).map((r) => r.status), [200, 200, 429], 'the third was handed back as it came');+});++test('budgeted: the answer a declined wait hands back is cleaned like any answer that is not a success — the token is out of its body and its headers', async () => {+ const TOKEN = `tok-${'x'.repeat(40)}`;+ const run = budgeted({ spent: 300000 });+ const answer = { statusCode: 429, headers: { 'retry-after': '30', 'x-echo': `Bearer ${TOKEN}` }, body: JSON.stringify({ error: { message: `rejected ${TOKEN}` } }) };+ const t = fakeTransport(answer);+ const res = await clientOf(t, run, { getToken: () => TOKEN }).get(READ);+ assert.strictEqual(t.calls.length, 1);+ assert.strictEqual(res.status, 429);+ assert.doesNotMatch(JSON.stringify(res), new RegExp(TOKEN));+ assert.strictEqual(res.body.error.message, 'rejected <token>');+ // A raw answer (a `$batch`, whose answer the SDK reads as text) is cleaned the same way.+ const raw = fakeTransport({ statusCode: 429, headers: {}, body: `${TOKEN} refused` });+ const refused = await postBatch(clientOf(raw, budgeted({ spent: 300000 }), { getToken: () => TOKEN }), COLUMNS);+ assert.strictEqual(refused.body, '<token> refused');+});+test('postRaw still refreshes the token once on 401 (rejected before processing, so it is safe)', async () => {const { request, calls } = fakeTransport(() =>calls.length <= 1 ? { statusCode: 401, headers: {}, body: '' } : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex f01087af2..6b630d585 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -2073,7 +2073,7 @@ test('teardown plans an ai-summaries step (before tables) for each candidate andassert.strictEqual(plan[aiIdx].phase, 'ai-summaries');assert.strictEqual(plan[aiIdx].target.entityLogicalName, 'new_memo');- // Run with a mock sdk that records removeRowSummary calls. The environment holds a row summary for the table: the step looks for the skill row before it removes one.+ // Run with a mock sdk that records removeRowSummary calls. The SDK looks the row summary up itself and answers { removed: true } for the one the environment holds.const removeCalls = [];const sdk = {resolveArtifact: async (kind, identity) => {@@ -2081,14 +2081,14 @@ test('teardown plans an ai-summaries step (before tables) for each candidate andif (kind === 'solution') return [{ id: 'sol-1', name: 'AiTest' }];return [];},- dataverse: { get: async (url) => (/^\/aiskillconfigs\?/.test(url) ? { status: 200, body: { value: [{ aiskillconfigid: 'skill-1' }] } } : { status: 200, body: { value: [] } }) },- removeRowSummary: async (args) => { removeCalls.push(args); },+ removeRowSummary: async (args) => { removeCalls.push(args); return { removed: true }; },deleteTable: async () => { const e = new Error('not found'); e.statusCode = 404; throw e; },deleteSolution: async () => {},};const res = await runTeardown(spec, { apply: true }, { sdk, emit: () => {} });assert.strictEqual(res.ok, true, JSON.stringify(res.errors));assert.ok(removeCalls.some((c) => c.entityLogicalName === 'new_memo'), 'removeRowSummary called for the candidate table');+ assert.deepStrictEqual(res.deleted.aiSummary, ['new_memo'], 'and its answer is a deletion');});test('planTeardown omits ai-summaries steps when the spec has no `ai` block at all', () => {diff --git a/plugins/model-apps/scripts/tests/skill-posttool-validation.test.js b/plugins/model-apps/scripts/tests/skill-posttool-validation.test.jsindex 85a72dd8f..64bb8ab23 100644--- a/plugins/model-apps/scripts/tests/skill-posttool-validation.test.js+++ b/plugins/model-apps/scripts/tests/skill-posttool-validation.test.js@@ -40,6 +40,10 @@ function stagePlugin() {path.join(PLUGIN_ROOT, "scripts", "lib", "utf8-stream.js"),path.join(root, "scripts", "lib", "utf8-stream.js"));+ fs.copyFileSync(+ path.join(PLUGIN_ROOT, "scripts", "lib", "output-redaction.js"),+ path.join(root, "scripts", "lib", "output-redaction.js")+ );// The staged hook must be the real source, not a rewritten stand-in.assert.equal(fs.readFileSync(path.join(root, "hooks", "run-skill-posttool-validation.js"), "utf8"),diff --git a/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.js b/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.jsindex ae551b62a..4bac8ad4b 100644--- a/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/solution-settings-real-bundle.test.js@@ -14,6 +14,7 @@ const plainPrivateFile = require('./helpers/plain-private-file.js');plainPrivateFile.install();const ss = require('../solution-settings.js');const { createCloud, LOCK_REFUSAL, CONCURRENCY_REFUSAL, ORG, DATAVERSE_TOKEN } = require('./helpers/fake-power-platform.js');+const { LOGS, jobRow, jobAnswer, REFUSAL_STATUS } = require('./helpers/import-job-logs.js');const { runScript } = require('./helpers/run-with-fakes.js');const { VALUES, spellingsOfValue } = require('./helpers/value-spellings.js');const { WORK_FOLDER, RECORDED_WORK_FOLDER, PLAIN_WORK_FOLDER, entriesOf, pluginFolderOf, assertMadeByTheMaker, refusingWorkFolders } = require('./helpers/solution-settings-work-folder.js');@@ -662,8 +663,9 @@ test('REAL BUNDLE: a 429 of another kind, and the lock\'s words under another co{ status: 429, code: '0x80071154', message: 'The current Import operation failed due to another concurrent operation running at the same time. Please try again later.' },{ ...LOCK_REFUSAL, code: '0x80048d19' },{ ...LOCK_REFUSAL, status: 503 },- // SolutionConcurrencyFailure: its documented text says the installation or removal FAILED, so it is not taken to say that nothing started — with the lock's words or without them.- { ...CONCURRENCY_REFUSAL },+ // SolutionConcurrencyFailure: its documented text says the installation or removal FAILED, so the code does not say that nothing started unless the platform's words do — "Cannot start …" — and its job+ // then proves it (below). Under another status, or with the documented text alone, it is sent once.+ { ...CONCURRENCY_REFUSAL, status: 503 },{ ...CONCURRENCY_REFUSAL, message: 'The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later.' },];for (const refusal of throttled) {@@ -680,6 +682,171 @@ test('REAL BUNDLE: a 429 of another kind, and the lock\'s words under another co}});+// --- an import refused with SolutionConcurrencyFailure (0x80071151) ----------------------------------------------------------------------------------------------+// What the platform was measured to answer an import that meets another import or a publish: HTTP 429, 0x80071151, and "Cannot start …" words (CONCURRENCY_REFUSAL). The code alone does not say that nothing+// started, so the refused send's own job — read once, at once — decides: it does not exist (404), or it is finished and its log says the import failed with that error before it processed the solution or any component.+const PROOF_READ = '?$select=importjobid,completedon,data';+const SENT_AGAIN_404 = (sends, waits) => `ImportSolution was sent ${sends} times. Each send before the last was refused before it started (HTTP 429, code 0x80071151: another operation held the environment's customization lock) and the job it named did not exist (importjobs(<id>) answered 404). The run waited ${waits} before sending again.`;+// How many requests the platform had seen when each wait began: a wait that follows the read of the job has the read before it.+const withWaitsAfterRequests = (http, cloud, waits) => ({ ...http, sleep: async (ms) => { waits.push([ms, cloud.requests.length]); } });+const NOT_PROVEN = (reason, id = JOB) => `ImportSolution was not sent again: the platform refused it (HTTP 429, code 0x80071151: another operation held the environment's customization lock), but ${reason}, so it is not proven that the refused send applied nothing of the package. Look up import job ${id} (importjobs(${id}) in the Web API, or the solution history in Maker) and run the import again only when that shows nothing was imported and the other operation has finished.`;+// What a refusal with 0x80071151 adds to the failure when the sends ran out on it: the job of the LAST send was not looked at, so nothing shows that the send applied nothing — the failure says what to look up first,+// by the rule that decided the sends before it, and never "run the import again" without it (the same words as in solution-settings.test.js).+const NOT_LOOKED_AT = (id) => `The last send was refused too (code 0x80071151), but this run sends the import 5 times at most and did not look at its import job, so it is not proven that it applied nothing of the package. Look up import job ${id} (importjobs(${id}) in the Web API, or the solution history in Maker) and run the import again only when that job does not exist (a 404), or is finished and its log says the import failed with that error before it processed the solution or any component, and the other operation has finished. Anything else means that the import may be running or may have applied the package: do not run it again.`;+const RUN_AGAIN = 'run the import again when the other operation has finished';++test('REAL BUNDLE: an import refused with 0x80071151 whose job does not exist is sent again — staged once, the job read AT ONCE (before the wait), the second send the same package — and one import is accepted', async () => {+ const { cloud, http } = world({ importRefusals: [CONCURRENCY_REFUSAL] });+ const waits = [];+ const f = files();+ const result = await ss.runImport(importRequest(f), { http: withWaitsAfterRequests(http, cloud, waits), pac: never, importJobId: JOB });+ assert.strictEqual(cloud.state.imports.length, 1, 'the platform took one import');+ assert.strictEqual(cloud.state.refusedImports.length, 1, 'and refused one');+ const [accepted] = cloud.state.imports;+ const [refused] = cloud.state.refusedImports;+ assert.strictEqual(refused.ImportJobId, JOB);+ assert.notStrictEqual(accepted.ImportJobId, JOB);+ assert.deepStrictEqual({ ...accepted, ImportJobId: JOB }, refused, 'the same package and the same ComponentParameters: only the job id differs');+ assert.deepStrictEqual(result, {+ source: 'sdk',+ importJobId: accepted.ImportJobId,+ applied: { environmentVariables: ['new_Secret'], connectionReferences: ['new_Dataverse'] },+ importAttempts: 2,+ importRefusals: [{ importJobId: JOB, status: 429, code: '0x80071151', waitedMs: 10000, proof: 'job-absent' }],+ });+ assert.deepStrictEqual(wireOf(cloud), [+ 'POST StageSolution',+ 'DELETE stagesolutionuploads(33333333-3333-4333-8333-333333333333)',+ 'POST ImportSolution',+ `GET importjobs(${JOB})${PROOF_READ}`,+ 'POST ImportSolution',+ ]);+ assert.deepStrictEqual(waits, [[10000, 4]], 'the wait came after the read of the job — the fourth request — and no read followed it');+ assert.deepStrictEqual(cloud.state.jobReads, [JOB]);+ assert.strictEqual(cloud.state.staged.length, 1);+ assert.ok(cloud.requests.every((r) => r.authorization === `Bearer ${cloud.tokens.dataverse}`), 'every request — the read of the job too — carried the Dataverse token');+ assert.ok(!JSON.stringify(result).includes(SECRET) && !JSON.stringify(result).includes(CONNECTION_ID), 'the output names entries, never their values');+});++test('REAL BUNDLE: an import refused with 0x80071151 whose job EXISTS — finished, its log saying the import failed with that error before it processed anything — is sent again, and the output says the log proved it', async () => {+ const { cloud, http } = world({ importRefusals: [CONCURRENCY_REFUSAL], jobLogAnswer: jobAnswer(jobRow(LOGS.refused({ tables: 6 }), { id: JOB })) });+ const waits = [];+ const f = files();+ const result = await ss.runImport(importRequest(f), { http: withWaitsAfterRequests(http, cloud, waits), pac: never, importJobId: JOB });+ assert.strictEqual(cloud.state.imports.length, 1);+ assert.deepStrictEqual(result.importRefusals, [{ importJobId: JOB, status: 429, code: '0x80071151', waitedMs: 10000, proof: 'job-refused-before-any-component' }]);+ assert.strictEqual(result.importAttempts, 2);+ assert.deepStrictEqual(wireOf(cloud).slice(2), ['POST ImportSolution', `GET importjobs(${JOB})${PROOF_READ}`, 'POST ImportSolution']);+ assert.deepStrictEqual(waits, [[10000, 4]]);+});++test('REAL BUNDLE: five refusals with 0x80071151 in a row end the run — each of the first four read at once and waited out, the fifth the SDK\'s own failure with the count — and no import was taken', async () => {+ const { cloud, http } = world({ importRefusals: Array.from({ length: 5 }, () => CONCURRENCY_REFUSAL) });+ const waits = [];+ const f = files();+ await assert.rejects(ss.runImport(importRequest(f), { http: withWaitsAfterRequests(http, cloud, waits), pac: never, importJobId: JOB }), (err) => {+ const ids = cloud.state.refusedImports.map((body) => body.ImportJobId);+ assert.strictEqual(new Set(ids).size, 5);+ assert.strictEqual(err.message, `HTTP 429 from ${ORG}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${SENT_AGAIN_404(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(ids[4])}`);+ assert.deepStrictEqual([err.code, err.statusCode, err.importJobId, err.importAttempts], ['CONNECTION_ERROR', 429, ids[4], 5]);+ assert.deepStrictEqual(err.importRefusals.map((r) => [r.importJobId, r.waitedMs, r.proof]), ids.slice(0, 4).map((id, i) => [id, [10000, 20000, 40000, 60000][i], 'job-absent']));+ return true;+ });+ assert.strictEqual(cloud.state.imports.length, 0, 'the platform took no import');+ assert.deepStrictEqual(waits.map(([ms]) => ms), [10000, 20000, 40000, 60000]);+ // Four reads at once, one after each of the first four refusals — each wait follows its read — then the one read of the last job's log that every failed import makes (`$select=data`).+ assert.deepStrictEqual(cloud.requests.filter((r) => r.path.includes('/importjobs(')).map((r) => r.search), [...Array(4).fill(PROOF_READ), '?$select=data']);+ assert.deepStrictEqual(waits.map(([, seen]) => seen), [4, 6, 8, 10], 'a wait after each of the four reads of the job: the Stage, the delete of the staging copy, then a send and its read for each');+ assert.strictEqual(cloud.requests.filter((r) => r.path.endsWith('/StageSolution')).length, 1, 'staged once, for five sends');+});++// The read of an import job answers `answer` once `sends` ImportSolution requests have reached the platform — the read of the LAST send's job, the one the failure makes — and is the platform's own (a 404) before that.+const jobAnsweringAfterSends = (sends, answer) => {+ let seen = 0;+ return (entry) => {+ if (entry.method === 'POST' && entry.path.endsWith('/ImportSolution')) seen += 1;+ return entry.method === 'GET' && entry.path.includes('/importjobs(') && seen >= sends ? answer : undefined;+ };+};++test('REAL BUNDLE: the fifth refusal with 0x80071151 is followed by no advice to run the import again, whatever the job of that send is — it was not looked at, so the failure says what to look up first — and no sixth import is sent', async () => {+ for (const [what, last] of [+ ['a job that is still running', jobAnswer(jobRow(LOGS.running(), { completed: false }))],+ ['a job that applied the package', jobAnswer(jobRow(LOGS.succeeded()))],+ ['a read that is refused', json(403, { error: { message: 'principal user is missing prvReadImportJob privilege' } })],+ ['a read that fails', json(503, { error: { message: 'service unavailable' } })],+ ['a read that gets no answer', { error: 'Request timed out' }],+ ['a job that does not exist', undefined],+ ]) {+ const { cloud, http } = world({ importRefusals: Array.from({ length: 6 }, () => CONCURRENCY_REFUSAL) }, last ? { override: jobAnsweringAfterSends(5, last) } : {});+ const waits = [];+ const f = files();+ await assert.rejects(ss.runImport(importRequest(f), { http: withWaits(http, waits), pac: never, importJobId: JOB }), (err) => {+ const ids = cloud.state.refusedImports.map((body) => body.ImportJobId);+ assert.strictEqual(new Set(ids).size, 5, what);+ assert.strictEqual(err.message, `HTTP 429 from ${ORG}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${SENT_AGAIN_404(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(ids[4])}`, what);+ assert.ok(!err.message.includes(RUN_AGAIN), `${what}: the advice that nothing has proven safe is not given`);+ assert.deepStrictEqual([err.code, err.statusCode, err.importJobId, err.importAttempts], ['CONNECTION_ERROR', 429, ids[4], 5], what);+ return true;+ }, what);+ assert.deepStrictEqual([cloud.state.refusedImports.length, cloud.state.imports.length, waits], [5, 0, [10000, 20000, 40000, 60000]], `${what}: five sends, no sixth, nothing taken`);+ assert.deepStrictEqual(cloud.requests.filter((r) => r.path.includes('/importjobs(')).map((r) => r.search), [...Array(4).fill(PROOF_READ), '?$select=data'], `${what}: four proofs, then the failure's usual read of the last job — never a fifth proof`);+ }+});++test('REAL BUNDLE: a timer that resumes after the five minutes ends the retry before the send, for a refusal with 0x80071151 proven by a 404 or by the log — the job read at once, the wait, and no second import', async () => {+ for (const [what, jobLogAnswer, logged] of [+ ['a 404', undefined, ''],+ ['the log of an import refused at the lock', jobAnswer(jobRow(LOGS.refused({ tables: 6 }), { id: JOB })), ` The import job's log (importjobs(${JOB})) says: its status is ${REFUSAL_STATUS}`],+ ]) {+ const { cloud, http } = world({ importRefusals: [CONCURRENCY_REFUSAL, CONCURRENCY_REFUSAL], ...(jobLogAnswer ? { jobLogAnswer } : {}) });+ const time = clocked(http, { lateMs: 350000 });+ const f = files();+ await assert.rejects(ss.runImport(importRequest(f), { http: time.http, pac: never, importJobId: JOB }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ORG}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message}${logged} ${OUT_OF_TIME('360 s')}`, what);+ assert.deepStrictEqual([err.code, err.statusCode, err.importJobId, 'importAttempts' in err], ['CONNECTION_ERROR', 429, JOB, false], what);+ return true;+ }, what);+ assert.deepStrictEqual([cloud.state.refusedImports.length, cloud.state.imports.length, time.waits], [1, 0, [10000]], `${what}: one send, nothing taken, the one wait`);+ assert.deepStrictEqual(wireOf(cloud).slice(-2), [`GET importjobs(${JOB})${PROOF_READ}`, `GET importjobs(${JOB})?$select=data`], `${what}: the proof at once, then the failure's usual read — and no send after the wait`);+ }+});++test('REAL BUNDLE: a refusal with 0x80071151 whose job does not prove that nothing was applied is NOT sent again — one send, the job read once at once, no wait — and the failure says why and what to do', async () => {+ for (const [what, jobLogAnswer, reason] of [+ ['the import is still running', jobAnswer(jobRow(LOGS.running(), { completed: false })), 'its import job is not finished (completedon is empty)'],+ ['the import failed after it began', jobAnswer(jobRow(LOGS.failedAfterStart())), 'the log of its import job says the import failed with error 0x80048033, not with 0x80071151'],+ ['the solution manifest was processed', jobAnswer(jobRow(LOGS.refused({ manifest: 'true' }))), 'the log of its import job shows that the import began to apply the package (its solution manifest is processed)'],+ ['the read is refused', json(403, { error: { message: 'principal user is missing prvReadImportJob privilege' } }), 'the read of its import job answered HTTP 403, which is neither the job nor a 404'],+ ]) {+ const { cloud, http } = world({ importRefusals: [CONCURRENCY_REFUSAL], jobLogAnswer });+ const waits = [];+ const f = files();+ await assert.rejects(ss.runImport(importRequest(f), { http: withWaits(http, waits), pac: never, importJobId: JOB }), (err) => {+ assert.ok(err.message.startsWith(`HTTP 429 from ${ORG}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message}`), what);+ assert.ok(err.message.endsWith(NOT_PROVEN(reason)), `${what}: ${err.message}`);+ assert.deepStrictEqual([err.code, err.statusCode, err.importJobId, 'importAttempts' in err, 'importRefusals' in err, 'fallback' in err], ['CONNECTION_ERROR', 429, JOB, false, false, false], what);+ return true;+ }, what);+ assert.deepStrictEqual([cloud.state.refusedImports.length, cloud.state.imports.length, waits.length], [1, 0, 0], `${what}: one send, nothing taken, nothing waited for`);+ assert.deepStrictEqual(cloud.requests.filter((r) => r.path.includes('/importjobs(')).map((r) => r.search), [PROOF_READ, '?$select=data'], `${what}: the read that decides, then the failure's usual read of the log`);+ }+});++test('REAL BUNDLE: a refusal with 0x80071151 whose message does not begin "Cannot start" is sent once, with no read of the job but the failure\'s usual one — the code alone is not proof that nothing started', async () => {+ const documented = { ...CONCURRENCY_REFUSAL, message: 'The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later.' };+ const { cloud, http } = world({ importRefusals: [documented] });+ const waits = [];+ const f = files();+ await assert.rejects(ss.runImport(importRequest(f), { http: withWaits(http, waits), pac: never, importJobId: JOB }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ORG}/api/data/v9.0/ImportSolution: ${documented.message}`);+ assert.deepStrictEqual(['importAttempts' in err, 'importRefusals' in err], [false, false]);+ return true;+ });+ assert.deepStrictEqual([cloud.state.refusedImports.length, waits.length], [1, 0]);+ assert.deepStrictEqual(cloud.requests.filter((r) => r.path.includes('/importjobs(')).map((r) => r.search), ['?$select=data']);+});+test('REAL BUNDLE: a send that follows a refusal and is answered by a gateway is the failure — one more send is not made — and the job to look up is the one that send carried', async () => {// The platform refuses the first send, takes the second (it is recorded) and a gateway answers 504 for it: the second send's outcome is unknown.const { cloud, http } = world({ importRefusals: [LOCK_REFUSAL], importAnswer: json(504, { error: { code: '0x80048d19', message: 'gateway timeout' } }) });@@ -707,14 +874,16 @@ test('REAL BUNDLE: a refusal that quotes the settings file reaches no messageassert.strictEqual(cloud.state.refusedImports.length, 5);});-// A clock that only the waits move, so that what the run spends is measured as it is when the waits are real: `now` is what the client reads, and a wait moves it by its length.+// A clock that only the waits move, so that what the run spends is measured as it is when the waits are real: `now` is what the client reads, and a wait moves it by its length — and by `lateMs` more, for a timer+// that resumes later than it was asked to (a delayed timer, a laptop that was suspended).const CLOCK_ORIGIN = Date.UTC(2026, 9, 14, 12, 0, 0);-function clocked(http) {+function clocked(http, { lateMs = 0 } = {}) {const clock = { elapsed: 0 };const waits = [];- return { clock, waits, http: { ...http, now: () => CLOCK_ORIGIN + clock.elapsed, sleep: async (ms) => { waits.push(ms); clock.elapsed += ms; } } };+ return { clock, waits, http: { ...http, now: () => CLOCK_ORIGIN + clock.elapsed, sleep: async (ms) => { waits.push(ms); clock.elapsed += ms + lateMs; } } };}const NOT_SENT_AGAIN = (wait, spent) => `ImportSolution was not sent again: the next wait, ${wait}, does not fit in what is left of the 5 minutes this run spends in all on sending it again (${spent} are spent). Run the import again when the other operation has finished.`;+const OUT_OF_TIME = (spent) => `ImportSolution was not sent again: the 5 minutes this run spends in all on sending it again were used up (${spent}) before the next send. Run the import again when the other operation has finished.`;test('REAL BUNDLE: a Retry-After longer than a minute — in seconds, and as a date — is waited out WHOLE before the second send; the platform is never sent the import again early', async () => {for (const [form, header] of [['delay-seconds', '180'], ['HTTP-date', new Date(CLOCK_ORIGIN + 180000).toUTCString()]]) {@@ -1150,6 +1319,61 @@ test('PROCESS: a refusal whose job exists is not sent again — exit 1, the lineassert.deepStrictEqual(run.state.waits, [10000], 'the proof is read after the wait: this is the one wait that came to nothing');});+test('PROCESS: an import refused with 0x80071151 is sent again when its job proves nothing was applied — exit 0, one line with each refusal and its proof — and is not when it does not — exit 1, the sentence that says why on stdout and on stderr', () => {+ const sent = importInProcess({ platform: { instantWaits: true }, solution: { importRefusals: [CONCURRENCY_REFUSAL], jobLogAnswer: jobAnswer(jobRow(LOGS.refused())) } });+ assert.strictEqual(sent.status, 0, sent.stderr);+ const [accepted] = sent.state.imports;+ const [refusedId] = sent.state.refusedImports.map((body) => body.ImportJobId);+ assert.strictEqual(importPosts(sent), 2);+ assert.deepStrictEqual(JSON.parse(sent.lines[0]), {+ ok: true,+ source: 'sdk',+ importJobId: accepted.ImportJobId,+ applied: { environmentVariables: ['new_Secret'], connectionReferences: [] },+ importAttempts: 2,+ importRefusals: [{ importJobId: refusedId, status: 429, code: '0x80071151', waitedMs: 10000, proof: 'job-refused-before-any-component' }],+ });+ assert.deepStrictEqual(sent.state.waits, [10000]);+ assert.strictEqual(sent.stderr, '');+ noSecrets(sent);+ assertPrintsNone(sent, [SECRET, CONNECTION_ID]);++ const stopped = importInProcess({ platform: { instantWaits: true }, solution: { importRefusals: [CONCURRENCY_REFUSAL], jobLogAnswer: jobAnswer(jobRow(LOGS.running(), { completed: false })) } });+ assert.strictEqual(stopped.status, 1);+ assert.strictEqual(importPosts(stopped), 1);+ const jobId = stopped.state.refusedImports[0].ImportJobId;+ const out = JSON.parse(stopped.lines[0]);+ assert.deepStrictEqual(out, {+ ok: false,+ error: `HTTP 429 from ${ORG}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${NOT_PROVEN('its import job is not finished (completedon is empty)', jobId)}`,+ code: 'CONNECTION_ERROR',+ status: 429,+ importJobId: jobId,+ });+ assert.strictEqual(stopped.stderr.trim(), out.error, 'stderr says the same');+ assert.deepStrictEqual(stopped.state.waits, [], 'nothing was waited for');+ noSecrets(stopped);+});++test('PROCESS: five refusals with 0x80071151 in a row end the run — exit 1, one ok:false line whose last sentence says what to look up before the import is run again, the same words on stderr — and nothing is imported', () => {+ const run = importInProcess({ platform: { instantWaits: true }, solution: { importRefusals: Array.from({ length: 5 }, () => CONCURRENCY_REFUSAL) } });+ assert.strictEqual(run.status, 1);+ const out = JSON.parse(run.lines[0]);+ const ids = run.state.refusedImports.map((body) => body.ImportJobId);+ assert.strictEqual(ids.length, 5);+ assert.deepStrictEqual([out.ok, out.code, out.status, out.importJobId, out.importAttempts], [false, 'CONNECTION_ERROR', 429, ids[4], 5]);+ assert.deepStrictEqual(out.importRefusals.map((r) => [r.importJobId, r.waitedMs, r.proof]), ids.slice(0, 4).map((id, i) => [id, [10000, 20000, 40000, 60000][i], 'job-absent']));+ assert.strictEqual(out.error, `HTTP 429 from ${ORG}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${SENT_AGAIN_404(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(ids[4])}`);+ assert.ok(!out.error.includes(RUN_AGAIN), 'the advice that nothing has proven safe is not given');+ assert.strictEqual(run.stderr.trim(), out.error, 'stderr says the same');+ assert.deepStrictEqual(run.state.waits, [10000, 20000, 40000, 60000]);+ assert.strictEqual(importPosts(run), 5);+ assert.strictEqual(run.state.imports.length, 0);+ assert.deepStrictEqual(run.requests.filter((r) => r.path.includes('/importjobs(')).map((r) => r.search), [...Array(4).fill(PROOF_READ), '?$select=data']);+ assert.ok(!('fallback' in out), 'pac was not asked');+ noSecrets(run);+});+// --- nothing a settings file holds comes back out ------------------------------------------------------------------------------------------------const LONG_SECRET = 'synthetic-sensitive-value-CDR';diff --git a/plugins/model-apps/scripts/tests/solution-settings.test.js b/plugins/model-apps/scripts/tests/solution-settings.test.jsindex 13295be1a..4f69fe47e 100644--- a/plugins/model-apps/scripts/tests/solution-settings.test.js+++ b/plugins/model-apps/scripts/tests/solution-settings.test.js@@ -2083,20 +2083,23 @@ function platformFor({ sends, job = NO_SUCH_JOB }) {};return { http, requests, waits, events, imports: () => requests.filter(isImportSend), jobReads: () => requests.filter(isJobRead) };}-// The long-action client over such a platform; `told` is what the client says of each refusal it sends again, `stopped` what it says of a retry it ends for want of time, and `observing: false` is a caller-// that gave it no listener.+// The long-action client over such a platform; `told` is what the client says of each refusal it sends again, `stopped` what it says of a retry it ends for want of time, `unproven` what it says of a refusal+// it does not send again because the job does not prove that nothing was applied, and `observing: false` is a caller that gave it no listener.function refusedImport({ sends, job, observing = true, http = {} }) {const platform = platformFor({ sends, job });const told = [];const stopped = [];- const listeners = { onImportRefused: (event) => told.push(event), onImportRetryStopped: (event) => stopped.push(event) };+ const unproven = [];+ const exhausted = [];+ const listeners = { onImportRefused: (event) => told.push(event), onImportRetryStopped: (event) => stopped.push(event), onImportRetryUnproven: (event) => unproven.push(event), onImportRetryExhausted: (event) => exhausted.push(event) };const client = ss.solutionHttpClient(ENV, { ...platform.http, ...http }, observing ? listeners : {});- return { ...platform, http: { ...platform.http, ...http }, client, told, stopped, post: () => client.post(`${ENV}/api/data/v9.0/ImportSolution`, importBody()) };+ return { ...platform, http: { ...platform.http, ...http }, client, told, stopped, unproven, exhausted, post: () => client.post(`${ENV}/api/data/v9.0/ImportSolution`, importBody()) };}// The same, over a clock that only the waits move: `now` is what the client reads, a wait moves it by its length, and a read of the job moves it by `readMs` — so what the client spends is measured, as-// it is when the waits are real. `sentAt` is when each send reached the platform, in milliseconds from the first.+// it is when the waits are real. `sentAt` is when each send reached the platform, in milliseconds from the first. `lateMs` is how much later than asked each timer resumes (a timer that was delayed, a laptop+// that was suspended: the wait the client asked for is the least a real wait takes) and `job` is what every read of the job answers.const CLOCK_ORIGIN = Date.UTC(2026, 9, 14, 12, 0, 0);-function clockedImport({ sends, readMs = 0, observing = true }) {+function clockedImport({ sends, readMs = 0, observing = true, lateMs = 0, job = NO_SUCH_JOB }) {const clock = { elapsed: 0, sentAt: [] };const answers = sends.map((answer) => (options) => {clock.sentAt.push(clock.elapsed);@@ -2105,9 +2108,9 @@ function clockedImport({ sends, readMs = 0, observing = true }) {const waits = [];const world = refusedImport({sends: answers,- job: () => { clock.elapsed += readMs; return NO_SUCH_JOB; },+ job: () => { clock.elapsed += readMs; return job; },observing,- http: { now: () => CLOCK_ORIGIN + clock.elapsed, sleep: async (ms) => { waits.push(ms); clock.elapsed += ms; world.events.push(`wait ${ms}`); } },+ http: { now: () => CLOCK_ORIGIN + clock.elapsed, sleep: async (ms) => { waits.push(ms); clock.elapsed += ms + lateMs; world.events.push(`wait ${ms}`); } },});return { ...world, clock, waits };}@@ -2149,34 +2152,516 @@ test('the codes that make a refusal to start are exactly the five customization-}});-// SolutionConcurrencyFailure is documented as "The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later." — an operation-// that FAILED, which is not the platform saying it refused to start one. Answers that begin "Cannot start the requested operation …" and end with that sentence have been seen carrying this code, but the-// documented text is what the list of codes follows: this code is not one this client sends again for, and the answer is the first and the last send, as every answer to an import was before the resend existed.+// SolutionConcurrencyFailure (0x80071151) is documented as "The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later." — an+// operation that FAILED, which does not say that nothing started, so the code alone does not make an import one to send again. What the platform was MEASURED to answer an import that meets another import or a+// publish is this code with a message that begins "Cannot start another [Import] because there is a previous [Import] running" ("Cannot start the requested operation [Import] because there is another [Publish]+// running" for a publish), and for that answer the import's own job decides, read once and at once (the tests below). An answer with this code whose message does not begin "Cannot start" is the first and the+// last send, as every answer to an import was before the resend existed.const { CONCURRENCY_REFUSAL } = require('./helpers/fake-power-platform.js');-test('SolutionConcurrencyFailure (0x80071151) is NOT a refusal to start — whatever words come with it, in either case of its hex digits, the import is sent ONCE: no job read, no wait, nothing told, the answer back as it came', async () => {- const documented = 'The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later.';+const { LOGS, jobRow, jobAnswer, CAPTURED_STATES, REFUSAL_STATUS } = require('./helpers/import-job-logs.js');+const concurrencyAnswer = (options = {}) => lockAnswer({ code: CONCURRENCY_REFUSAL.code, message: CONCURRENCY_REFUSAL.message, ...options });+// The read of a refused send's job asks for the three columns the rule looks at, and no other: `progress` is the same for a running import and a refused one, and `solutionid` is set for a solution never made.+const PROOF_READ = '?$select=importjobid,completedon,data';+const DOCUMENTED_CONCURRENCY_TEXT = 'The solution installation or removal failed due to the installation or removal of another solution at the same time. Please try again later.';++test('SolutionConcurrencyFailure (0x80071151) is a refusal to start only when its message says so — "Cannot start …" — and every other answer with the code is sent ONCE: no job read, no wait, nothing told, the answer back as it came', async () => {+ const plain = (value) => ({ statusCode: 429, headers: {}, body: typeof value === 'string' ? value : JSON.stringify(value) });const cases = [- ['its documented text', documented],- ['the two-part message that begins "Cannot start the requested operation"', CONCURRENCY_REFUSAL.message],- ['the lock\'s own words', LOCK_REFUSAL.message],+ ['its documented text', lockAnswer({ code: '0x80071151', message: DOCUMENTED_CONCURRENCY_TEXT, headers: { 'retry-after': '5' } })],+ ['a message that says "Cannot start" further in', lockAnswer({ code: '0x80071151', message: `The import failed. Cannot start another one: ${DOCUMENTED_CONCURRENCY_TEXT}` })],+ ['a message that begins "Could not start"', lockAnswer({ code: '0x80071151', message: 'Could not start the requested operation [Import] because there is another [Publish] running at this moment.' })],+ ['a message in another language', lockAnswer({ code: '0x80071151', message: 'No se puede iniciar otro [Import] porque hay un [Import] anterior en ejecución.' })],+ ['an empty message', lockAnswer({ code: '0x80071151', message: '' })],+ ['a message that is null', plain({ error: { code: '0x80071151', message: null } })],+ ['a message that is not text', plain({ error: { code: '0x80071151', message: ['Cannot start another [Import]'] } })],+ ['no message at all', plain({ error: { code: '0x80071151' } })],+ ['a body that is not JSON', plain('Cannot start another [Import] because there is a previous [Import] running')],+ ['the words and the code outside "error"', plain({ code: '0x80071151', message: REFUSAL_STATUS })],+ ['the code spelled as a decimal', plain({ error: { code: -2147020463, message: REFUSAL_STATUS } })],+ ['the code in a text around it', lockAnswer({ code: 'error 0x80071151', message: REFUSAL_STATUS })],];- for (const [what, message] of cases) {+ for (const status of [400, 401, 403, 404, 408, 409, 412, 500, 502, 503, 504]) cases.push([`the code and the words under HTTP ${status}`, lockAnswer({ code: '0x80071151', message: REFUSAL_STATUS, statusCode: status })]);+ for (const [what, answer] of cases) {+ const world = refusedImport({ sends: [answer, ok()] });+ const res = await world.post();+ assert.strictEqual(res.status, answer.statusCode, `${what}: the answer comes back as it came`);+ assert.strictEqual(world.imports().length, 1, `${what}: one send`);+ assert.deepStrictEqual([world.jobReads().length, world.waits.length, world.told.length, world.unproven.length, world.stopped.length], [0, 0, 0, 0, 0], `${what}: no job read, no wait, nothing told`);+ }+});++test('concurrencyRefusalOf and lockRefusalOf are two matchers that never answer the same refusal — 0x80071151 needs HTTP 429 and a message that begins "Cannot start", the lock codes need HTTP 429 and the code alone, each in either case of its hex digits', () => {+ const answer = (code, message, statusCode = 429) => lockAnswer({ code, message, statusCode });+ assert.deepStrictEqual(ss.concurrencyRefusalOf(answer('0x80071151', REFUSAL_STATUS)), { status: 429, code: '0x80071151' });+ assert.deepStrictEqual(ss.concurrencyRefusalOf(answer('0X80071151', ' Cannot start the requested operation')), { status: 429, code: '0x80071151' }, 'white space before the words, the other case of the code');+ assert.strictEqual(ss.concurrencyRefusalOf(answer('0x80071151', DOCUMENTED_CONCURRENCY_TEXT)), null);+ assert.strictEqual(ss.lockRefusalOf(answer('0x80071151', REFUSAL_STATUS)), null, 'the lock matcher is the five codes only');+ for (const code of ss.LOCK_REFUSAL_CODES) {+ assert.strictEqual(ss.concurrencyRefusalOf(answer(code, LOCK_REFUSAL.message)), null, code);+ assert.deepStrictEqual(ss.lockRefusalOf(answer(code, LOCK_REFUSAL.message)), { status: 429, code }, code);+ }+ for (const res of [null, undefined, {}, { error: 'Request timed out' }, { statusCode: 429 }, { statusCode: 429, body: '' }, { statusCode: 429, body: 'null' }, { statusCode: 429, body: '[]' }, { statusCode: 429, body: '{"error":"Cannot start"}' }]) {+ assert.strictEqual(ss.concurrencyRefusalOf(res), null, JSON.stringify(res));+ assert.strictEqual(ss.lockRefusalOf(res), null, JSON.stringify(res));+ }+ // A body the transport already parsed is read too.+ assert.deepStrictEqual(ss.concurrencyRefusalOf({ statusCode: 429, body: { error: { code: '0x80071151', message: 'Cannot start another [Import]' } } }), { status: 429, code: '0x80071151' });+});++test('an import refused with 0x80071151 ("Cannot start …") whose job does not exist is sent again under a NEW job id — the job is read ONCE and AT ONCE, before the wait, and the 404 is the proof', async () => {+ for (const [what, message] of [+ ['an import that met another import', REFUSAL_STATUS],+ ['the two-part message of an import that met a publish', CONCURRENCY_REFUSAL.message],+ ['the lock\'s own words', LOCK_REFUSAL.message],+ ]) {for (const spelled of ['0x80071151', '0X80071151']) {- const world = refusedImport({ sends: [lockAnswer({ code: spelled, message, headers: { 'retry-after': '5' } }), ok()] });+ const world = refusedImport({ sends: [concurrencyAnswer({ code: spelled, message }), ok()] });const res = await world.post();- assert.deepStrictEqual([res.status, res.body.error.code, res.body.error.message], [429, spelled, message], `${what}: the answer comes back as it came`);- assert.strictEqual(world.imports().length, 1, `${what}: one send`);- assert.deepStrictEqual([world.jobReads().length, world.waits.length, world.told.length], [0, 0, 0], `${what}: no job read, no wait, nothing told`);+ assert.strictEqual(res.status, 200, `${what}: the second send's answer is the one the SDK reads`);+ assert.strictEqual(world.imports().length, 2, `${what}: the refused send, and one more`);+ const [refusedId, newId] = world.imports().map(jobIdOf);+ assert.strictEqual(refusedId, JOB);+ assert.match(newId, GUID);+ assert.notStrictEqual(newId, JOB, 'a new job id — the refused one is never used again');+ assert.strictEqual(world.imports()[1].body, world.imports()[0].body.replace(JOB, newId), 'the same request in every other byte');+ // In this order: the send, the ONE read of the refused send's job — at once — the wait, and the send again. The row of a refused send is final when the answer is in hand, so nothing is read again after the wait.+ assert.deepStrictEqual(world.events, [`send ${JOB}`, `read importjobs(${JOB})`, 'wait 10000', `send ${newId}`], what);+ assert.deepStrictEqual(world.jobReads().map((r) => [r.method, new URL(r.url).search, new URL(r.url).origin]), [['GET', PROOF_READ, ENV]], what);+ assert.deepStrictEqual(world.told, [{ importJobId: JOB, status: 429, code: '0x80071151', waitedMs: 10000, nextImportJobId: newId, proof: 'job-absent' }], `${what}: told as the reference spells it, with how it was proven`);+ assert.deepStrictEqual([world.stopped, world.unproven], [[], []], what);}}});-test('import: a refusal with 0x80071151 is reported exactly as an import refused for any other reason always was — the SDK\'s code and the status, the job that was sent, no count, no list — and pac is not asked', async () => {+test('an import refused with 0x80071151 whose job EXISTS is sent again when the job is finished and its log says the import failed with that error before it processed the solution manifest or any component — the log is the proof', async () => {+ for (const state of CAPTURED_STATES.filter((captured) => captured.group === 'refused-final')) {+ const world = refusedImport({ sends: [concurrencyAnswer(), ok()], job: jobAnswer(jobRow(state.data())) });+ const res = await world.post();+ assert.strictEqual(res.status, 200, state.name);+ assert.strictEqual(world.imports().length, 2, state.name);+ const newId = jobIdOf(world.imports()[1]);+ assert.deepStrictEqual(world.events, [`send ${JOB}`, `read importjobs(${JOB})`, 'wait 10000', `send ${newId}`], state.name);+ assert.deepStrictEqual(world.jobReads().map((r) => new URL(r.url).search), [PROOF_READ], state.name);+ assert.deepStrictEqual(world.told, [{ importJobId: JOB, status: 429, code: '0x80071151', waitedMs: 10000, nextImportJobId: newId, proof: 'job-refused-before-any-component' }], state.name);+ assert.deepStrictEqual([world.stopped, world.unproven], [[], []], state.name);+ }+});++test('a refusal with 0x80071151 whose job does NOT prove that nothing was applied is sent ONCE — one read at once, no wait, no second send — and the client says why it did not send again', async () => {+ const answer = (statusCode, body = {}) => ({ statusCode, headers: {}, body: JSON.stringify(body) });+ const cases = [+ // [what, the answer to the read of the job, why it is not proof]+ ['an import that is still running (completedon is empty)', jobAnswer(jobRow(LOGS.running(), { completed: false })), 'unfinished'],+ ['a refusal\'s row that is complete before its log is (completedon is set, the root has no verdict)', jobAnswer(jobRow(LOGS.unfinishedRoot())), 'not-a-failure'],+ ['an import that applied the package', jobAnswer(jobRow(LOGS.succeeded())), 'not-a-failure'],+ ['an import that failed AFTER it began (error 0x80048033, the manifest processed)', jobAnswer(jobRow(LOGS.failedAfterStart())), 'other-error'],+ ['the refusal\'s own log with the solution manifest processed', jobAnswer(jobRow(LOGS.refused({ manifest: 'true' }))), 'manifest-processed'],+ ['the refusal\'s own log with a component processed', jobAnswer(jobRow(LOGS.refused({ components: 'true' }))), 'component-processed'],+ ['a log that is not an XML document', jobAnswer(jobRow('<importexportxml succeeded="failure"')), 'log-unreadable'],+ ['a row with no log', jobAnswer(jobRow(null)), 'no-log'],+ ['an answer that is not a row', answer(200, 'plain'), 'no-log'],+ ['an empty 200', { statusCode: 200, headers: {}, body: '' }, 'no-log'],+ ['a 204', answer(204, ''), 'unreadable'],+ ['a 400', answer(400), 'unreadable'], ['a 401', answer(401), 'unreadable'], ['a 403', answer(403), 'unreadable'], ['a 408', answer(408), 'unreadable'], ['a 412', answer(412), 'unreadable'],+ ['a 429', answer(429), 'unreadable'], ['a 500', answer(500), 'unreadable'], ['a 502', answer(502), 'unreadable'], ['a 503', answer(503), 'unreadable'], ['a 504', answer(504), 'unreadable'],+ ['no answer', { error: 'Request timed out' }, 'no-answer'],+ ['an answer cut off', { error: 'Connection closed before the response completed', incompleteResponse: true, statusCode: 200 }, 'no-answer'],+ ['a transport that throws', () => { throw new Error('socket hang up'); }, 'no-answer'],+ ];+ for (const [what, job, why] of cases) {+ const world = refusedImport({ sends: [concurrencyAnswer(), ok()], job });+ const res = await world.post();+ assert.deepStrictEqual([res.status, res.body.error.code], [429, '0x80071151'], `${what}: the refusal comes back as it came`);+ assert.deepStrictEqual([world.imports().length, world.jobReads().length, world.waits.length, world.told.length, world.stopped.length], [1, 1, 0, 0, 0], `${what}: one send, one read, no wait, nothing sent again`);+ assert.deepStrictEqual(world.unproven.map((event) => [event.importJobId, event.status, event.code, event.why]), [[JOB, 429, '0x80071151', why]], what);+ assert.strictEqual(typeof world.unproven[0].reason, 'string', `${what}: and in words`);+ }+ // A read that cannot even have a token is no proof either.+ let tokens = 0;+ const tokenless = refusedImport({ sends: [concurrencyAnswer(), ok()], http: { getToken: () => { tokens += 1; return tokens === 1 ? 'dataverse-token' : null; } } });+ assert.strictEqual((await tokenless.post()).status, 429);+ assert.deepStrictEqual([tokenless.imports().length, tokenless.unproven.map((event) => event.why)], [1, ['no-answer']]);+});++test('the lock codes are read AFTER the wait, by the 404 alone, as before — and 0x80071151 is read AT ONCE, by the row — and a run that meets both proves each by its own rule', async () => {+ // The lock code first: wait, read (`$select=importjobid`), send. Then 0x80071151: read (the three columns), wait, send. Then the platform takes it.+ const world = refusedImport({ sends: [lockAnswer(), concurrencyAnswer(), ok()] });+ const res = await world.post();+ assert.strictEqual(res.status, 200);+ const [first, second, third] = world.imports().map(jobIdOf);+ assert.deepStrictEqual(world.events, [+ `send ${first}`, 'wait 10000', `read importjobs(${first})`,+ `send ${second}`, `read importjobs(${second})`, 'wait 20000',+ `send ${third}`,+ ]);+ assert.deepStrictEqual(world.jobReads().map((r) => new URL(r.url).search), ['?$select=importjobid', PROOF_READ]);+ assert.deepStrictEqual(world.told.map((event) => [event.code, 'proof' in event ? event.proof : '(none)']), [['0x8004F064', '(none)'], ['0x80071151', 'job-absent']], 'a lock code\'s refusal is told as it always was');+});++test('an import refused with 0x80071151 is sent FIVE times at most, on the lock codes\' schedule: each of the first four refusals is read at once and waited out (10, 20, 40, 60 s), the fifth is the failure — no read, no wait', async () => {+ const world = refusedImport({ sends: Array.from({ length: 6 }, () => concurrencyAnswer()) }); // a sixth would be answered, too: it must never be asked+ const res = await world.post();+ assert.deepStrictEqual([res.status, res.body.error.code], [429, '0x80071151']);+ assert.strictEqual(world.imports().length, 5);+ assert.strictEqual(world.jobReads().length, 4, 'one read for each of the first four refusals');+ assert.deepStrictEqual(world.waits, [10000, 20000, 40000, 60000]);+ const ids = world.imports().map(jobIdOf);+ assert.strictEqual(new Set(ids).size, 5, 'every send carried a job id of its own');+ assert.deepStrictEqual(world.events, [+ `send ${ids[0]}`, `read importjobs(${ids[0]})`, 'wait 10000',+ `send ${ids[1]}`, `read importjobs(${ids[1]})`, 'wait 20000',+ `send ${ids[2]}`, `read importjobs(${ids[2]})`, 'wait 40000',+ `send ${ids[3]}`, `read importjobs(${ids[3]})`, 'wait 60000',+ `send ${ids[4]}`,+ ]);+ assert.deepStrictEqual(world.told.map((event) => [event.importJobId, event.nextImportJobId, event.waitedMs, event.proof]), ids.slice(0, 4).map((id, i) => [id, ids[i + 1], [10000, 20000, 40000, 60000][i], 'job-absent']));+ assert.deepStrictEqual([world.stopped, world.unproven], [[], []], 'a refusal after the fifth send is the sends running out, not the time and not a job that proves nothing');+ assert.deepStrictEqual(world.exhausted, [{ importJobId: ids[4], status: 429, code: '0x80071151' }], 'the listener is told which refusal the sends ran out on — the job it carried, which was not looked at');+});++// A refusal with 0x80071151 that asks, with Retry-After, to wait `seconds`.+const askingConcurrency = (seconds) => () => concurrencyAnswer({ headers: { 'retry-after': String(seconds) } });++test('a Retry-After on a refusal with 0x80071151 is waited WHOLE, as for the lock codes — and one that does not fit the five minutes ends the retry AFTER the one read, which comes first for this refusal, with no wait and no send', async () => {+ const waited = clockedImport({ sends: [askingConcurrency(45), ok()] });+ assert.strictEqual((await waited.post()).status, 200);+ assert.deepStrictEqual(waited.waits, [45000]);+ assert.deepStrictEqual(waited.events.slice(0, 3), [`send ${JOB}`, `read importjobs(${JOB})`, 'wait 45000']);+ const world = clockedImport({ sends: [askingConcurrency(600), ok()] });+ const res = await world.post();+ assert.strictEqual(res.status, 429);+ assert.deepStrictEqual([world.imports().length, world.jobReads().length, world.waits.length, world.told.length], [1, 1, 0, 0], 'one send, the one read, nothing waited for');+ assert.deepStrictEqual(world.stopped, [{ importJobId: JOB, waitMs: 600000, spentMs: 0 }]);+ assert.deepStrictEqual(world.unproven, []);+});++test('the one read of the job counts in the five minutes: a refusal whose wait no longer fits once the read is done ends the retry with the platform\'s own refusal — the wait is never shortened to fit', async () => {+ // Each read takes 100 s. Send one is refused at 0 s, its read ends at 100 s, the platform asks for 120 s: 220 s are inside the five minutes, so the run waits and sends again at 220 s.+ // That send is refused too and its read ends at 320 s, which leaves nothing for a wait of 120 s — nor for the 20 s the schedule would give.+ const world = clockedImport({ sends: [askingConcurrency(120), askingConcurrency(120), ok()], readMs: 100000 });+ const res = await world.post();+ assert.strictEqual(res.status, 429);+ assert.deepStrictEqual(world.waits, [120000]);+ assert.deepStrictEqual(world.clock.sentAt, [0, 220000], 'a second send was made; a third was not');+ assert.strictEqual(world.jobReads().length, 2);+ assert.strictEqual(world.told.length, 1);+ assert.deepStrictEqual(world.stopped, [{ importJobId: world.imports().map(jobIdOf)[1], waitMs: 120000, spentMs: 320000 }]);+});++// The five minutes are asked for AFTER a wait as well as before it. What the client asks the timer for is the least a wait takes: a timer that is delayed, a busy machine, a laptop that is suspended resumes it+// later, so a wait that fitted when it began can end after the five minutes — and a send made then is a send the budget does not allow. `lateMs` is how much later than asked each timer resumes.+const LATE_PROOFS = [+ ['its job does not exist (a 404)', NO_SUCH_JOB],+ ['its job is finished and its log says the import was refused at the lock', jobAnswer(jobRow(LOGS.refused()))],+];++test('a wait that ends AFTER the five minutes — a timer that resumed late — ends the retry before the send, for a refusal with 0x80071151 proven by a 404 or by the log: nothing is sent, nothing is told as sent again, and the listener hears what was spent — to the millisecond', async () => {+ // 100 s late ends at 110 s and 290 s late at exactly 300 s: both are inside the five minutes and send. One millisecond more is past them, and does not.+ for (const [lateMs, expectedSends] of [[100000, 2], [290000, 2], [290001, 1]]) {+ const world = clockedImport({ sends: [() => concurrencyAnswer(), ok()], lateMs });+ await world.post();+ assert.strictEqual(world.imports().length, expectedSends, `a timer ${lateMs} ms late`);+ assert.deepStrictEqual(world.stopped, expectedSends === 1 ? [{ importJobId: JOB, waitMs: null, spentMs: 300001 }] : [], `a timer ${lateMs} ms late`);+ }+ for (const [what, job] of LATE_PROOFS) {+ // The first refusal: the wait is 10 s, which fits, and the timer resumes at 360 s.+ const first = clockedImport({ sends: [() => concurrencyAnswer(), ok()], lateMs: 350000, job });+ const res = await first.post();+ assert.strictEqual(res.status, 429, `${what}: the refusal comes back as it came`);+ assert.strictEqual(res.body.error.code, '0x80071151', what);+ assert.deepStrictEqual(first.events, [`send ${JOB}`, `read importjobs(${JOB})`, 'wait 10000'], `${what}: the read at once, the wait, and no send after it`);+ assert.deepStrictEqual([first.imports().length, first.clock.sentAt, first.told, first.unproven], [1, [0], [], []], what);+ assert.deepStrictEqual(first.stopped, [{ importJobId: JOB, waitMs: null, spentMs: 360000 }], `${what}: what was spent is what the clock says, and not what the wait asked for`);+ // A later refusal: the first wait is late but inside the five minutes (10 s asked, 150 s taken), the second (20 s asked, 160 s taken) ends at 310 s.+ const later = clockedImport({ sends: [() => concurrencyAnswer(), () => concurrencyAnswer(), ok()], lateMs: 140000, job });+ assert.strictEqual((await later.post()).status, 429, what);+ const [firstId, secondId] = later.imports().map(jobIdOf);+ assert.strictEqual(later.imports().length, 2, `${what}: a second send was made, a third was not`);+ assert.deepStrictEqual(later.clock.sentAt, [0, 150000], what);+ assert.deepStrictEqual(later.events, [`send ${firstId}`, `read importjobs(${firstId})`, 'wait 10000', `send ${secondId}`, `read importjobs(${secondId})`, 'wait 20000'], what);+ assert.strictEqual(later.told.length, 1, `${what}: the first refusal was sent again, the second was not`);+ assert.deepStrictEqual(later.stopped, [{ importJobId: secondId, waitMs: null, spentMs: 310000 }], what);+ }+});++test('the same late timer ends the retry for a lock code — after the read that follows its wait, as ever — and a timer that is late but ends inside the five minutes, or exactly at them, sends as it always did', async () => {+ const lock = clockedImport({ sends: [() => lockAnswer(), ok()], lateMs: 350000 });+ assert.strictEqual((await lock.post()).status, 429);+ assert.deepStrictEqual(lock.events, [`send ${JOB}`, 'wait 10000', `read importjobs(${JOB})`], 'the proof of a lock code is read after the wait');+ assert.deepStrictEqual([lock.imports().length, lock.told], [1, []]);+ assert.deepStrictEqual(lock.stopped, [{ importJobId: JOB, waitMs: null, spentMs: 360000 }]);+ // 100 s late ends at 110 s and 290 s late at exactly 300 s: both send. One millisecond more is past the five minutes, and does not.+ for (const [lateMs, expectedSends] of [[100000, 2], [290000, 2], [290001, 1]]) {+ const world = clockedImport({ sends: [() => lockAnswer(), ok()], lateMs });+ await world.post();+ assert.strictEqual(world.imports().length, expectedSends, `a timer ${lateMs} ms late`);+ assert.deepStrictEqual(world.events.slice(0, 3), [`send ${JOB}`, 'wait 10000', `read importjobs(${JOB})`], `a timer ${lateMs} ms late: the read after the wait, as ever`);+ assert.deepStrictEqual(world.stopped, expectedSends === 1 ? [{ importJobId: JOB, waitMs: null, spentMs: 300001 }] : [], `a timer ${lateMs} ms late`);+ }+});++test('a client with no listener never reads the job or waits for a refusal with 0x80071151 either: the retry belongs to the caller that asked for it', async () => {+ const world = refusedImport({ sends: [concurrencyAnswer(), ok()], observing: false });+ assert.strictEqual((await world.post()).status, 429);+ assert.deepStrictEqual([world.imports().length, world.jobReads().length, world.waits.length], [1, 0, 0]);+});++test('a refusal with 0x80071151 is ImportSolution\'s alone: a refused ExportSolution or StageSolution is sent once, job or no job', async () => {+ for (const [action, body] of [['ExportSolution', { SolutionName: 'x' }], ['StageSolution', { CustomizationFile: 'x' }]]) {+ const world = refusedImport({ sends: [concurrencyAnswer(), ok()] });+ const res = await world.client.post(`${ENV}/api/data/v9.0/${action}`, body);+ assert.strictEqual(res.status, 429, action);+ assert.deepStrictEqual([world.requests.length, world.waits.length], [1, 0], `${action}: one request, no job read, no wait`);+ }+});++test('import: a refusal with 0x80071151 that is sent again is reported — each refusal with how its job proved it — and a run that met only 404s says what it always said, with the code it was refused with', async () => {const { request } = importFiles();- const platform = platformFor({ sends: [lockAnswer({ code: CONCURRENCY_REFUSAL.code, message: CONCURRENCY_REFUSAL.message }), ok()] });+ const platform = platformFor({ sends: [concurrencyAnswer(), concurrencyAnswer(), ok()] });+ const result = await ss.runImport(request, { http: platform.http, sdkFirst: importingOver(), importJobId: JOB });+ const ids = platform.imports().map(jobIdOf);+ assert.deepStrictEqual(result, {+ source: 'sdk',+ importJobId: ids[2],+ applied: APPLIED,+ importAttempts: 3,+ importRefusals: [+ { importJobId: JOB, status: 429, code: '0x80071151', waitedMs: 10000, proof: 'job-absent' },+ { importJobId: ids[1], status: 429, code: '0x80071151', waitedMs: 20000, proof: 'job-absent' },+ ],+ });+ // The failure of a run that was refused at every send: the platform's own refusal, the count, and — for the last send, whose job was not looked at — what to look up before the import is run again.+ const refusedAlways = platformFor({ sends: Array.from({ length: 5 }, () => concurrencyAnswer()) });+ await assert.rejects(ss.runImport(importFiles().request, { http: refusedAlways.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${RESENT_AS('0x80071151')(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(refusedAlways.imports().map(jobIdOf)[4])}`);+ return true;+ });+});++// The sentences of a run that was refused with 0x80071151, by how the jobs of its refused sends proved it: all by their absence (the sentence of the lock codes), all by their logs, or some of each.+const RESENT_AS = (code) => (sends, waits) => `ImportSolution was sent ${sends} times. Each send before the last was refused before it started (HTTP 429, code ${code}: another operation held the environment's customization lock) and the job it named did not exist (importjobs(<id>) answered 404). The run waited ${waits} before sending again.`;+const RESENT_BY_LOG = (sends, waits, shown = 'importjobs(<id>) held the log of an import that failed with that error before it processed the solution or any component') => `ImportSolution was sent ${sends} times. Each send before the last was refused at the environment's customization lock (HTTP 429, code 0x80071151: another operation held it) before any of the package was applied, and its import job showed it: ${shown}. The run waited ${waits} before sending again.`;+const RESENT_BY_LOG_OR_404 = (sends, waits) => RESENT_BY_LOG(sends, waits, 'importjobs(<id>) answered 404, or held the log of an import that failed with that error before it processed the solution or any component');+// A job's answer that depends on which send's job is read: `proofs[i]` is the answer for the i-th job read.+const jobsAnsweringInOrder = (...answers) => { const left = [...answers]; return () => left.shift() || NO_SUCH_JOB; };++test('import: a refusal proven by the job\'s LOG is reported with the sentence that says how — and one proven by a 404 beside it says both', async () => {+ const refused = jobAnswer(jobRow(LOGS.refused()));+ const { request } = importFiles();+ const byLog = platformFor({ sends: [concurrencyAnswer(), ok()], job: refused });+ const result = await ss.runImport(request, { http: byLog.http, sdkFirst: importingOver(), importJobId: JOB });+ assert.deepStrictEqual(result.importRefusals, [{ importJobId: JOB, status: 429, code: '0x80071151', waitedMs: 10000, proof: 'job-refused-before-any-component' }]);+ assert.strictEqual(result.importAttempts, 2);+ // All five sends refused, each proven by its log: the platform's refusal, the count, and how each was proven.+ const allLogs = platformFor({ sends: Array.from({ length: 5 }, () => concurrencyAnswer()), job: refused });+ await assert.rejects(ss.runImport(importFiles().request, { http: allLogs.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${RESENT_BY_LOG(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(allLogs.imports().map(jobIdOf)[4])}`);+ assert.deepStrictEqual(err.importRefusals.map((refusal) => refusal.proof), Array(4).fill('job-refused-before-any-component'));+ return true;+ });+ // Some by a 404 (the first refusal is the commoner kind: no job at all), some by the log; the third is a job that is still running, which is no proof.+ const running = jobAnswer(jobRow(LOGS.running(), { completed: false }));+ const mixed = platformFor({ sends: [concurrencyAnswer(), concurrencyAnswer(), concurrencyAnswer()], job: jobsAnsweringInOrder(NO_SUCH_JOB, refused, running) });+ await assert.rejects(ss.runImport(importFiles().request, { http: mixed.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.statusCode, 429);+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${RESENT_BY_LOG_OR_404(3, '10 s, 20 s')} ${NOT_PROVEN(WHY.unfinished, mixed.imports().map(jobIdOf)[2])}`);+ return true;+ });+});++// What a refusal that is not sent again adds to its failure, word for word: why the job is no proof (`reason`), and what to do.+const NOT_PROVEN = (reason, id = JOB) => `ImportSolution was not sent again: the platform refused it (HTTP 429, code 0x80071151: another operation held the environment's customization lock), but ${reason}, so it is not proven that the refused send applied nothing of the package. Look up import job ${id} (importjobs(${id}) in the Web API, or the solution history in Maker) and run the import again only when that shows nothing was imported and the other operation has finished.`;+// What a refusal with 0x80071151 adds to the failure when it is the LAST send's — the sends ran out on it. Its job was not looked at (the four reads are for the refusals that can still be sent again, and their proofs+// are of four other jobs), so nothing shows that the send applied nothing: the failure says what to look up first, by the rule that decided the sends before it, and never "run the import again" without it.+const NOT_LOOKED_AT = (id = JOB) => `The last send was refused too (code 0x80071151), but this run sends the import 5 times at most and did not look at its import job, so it is not proven that it applied nothing of the package. Look up import job ${id} (importjobs(${id}) in the Web API, or the solution history in Maker) and run the import again only when that job does not exist (a 404), or is finished and its log says the import failed with that error before it processed the solution or any component, and the other operation has finished. Anything else means that the import may be running or may have applied the package: do not run it again.`;+// What the advice said before, and still says for a lock code: the documented text of those codes says the operation could not be started.+const RUN_AGAIN = 'It sends at most 5 times: run the import again when the other operation has finished.';+const WHY = {+ unfinished: 'its import job is not finished (completedon is empty)',+ noLog: 'its import job has no log to read',+ unreadable: 'the log of its import job is not an XML document this script can read',+ notFailure: 'the log of its import job does not say that the import failed',+ otherError: 'the log of its import job says the import failed with error 0x80048033, not with 0x80071151',+ manifestProcessed: 'the log of its import job shows that the import began to apply the package (its solution manifest is processed)',+ componentProcessed: 'the log of its import job shows that the import began to apply components of the package',+ http: (status) => `the read of its import job answered HTTP ${status}, which is neither the job nor a 404`,+ noAnswer: 'the read of its import job got no answer',+};++test('import: a refusal whose job does not prove that nothing was applied is the platform\'s own failure with a sentence that says why and what to do — one send, no count, no list — and pac is not asked', async () => {+ const cases = [+ [jobAnswer(jobRow(LOGS.running(), { completed: false })), WHY.unfinished],+ [jobAnswer(jobRow(LOGS.succeeded())), WHY.notFailure],+ [jobAnswer(jobRow(LOGS.unfinishedRoot())), WHY.notFailure],+ [jobAnswer(jobRow(LOGS.failedAfterStart())), WHY.otherError],+ [jobAnswer(jobRow(LOGS.refused({ manifest: 'true' }))), WHY.manifestProcessed],+ [jobAnswer(jobRow(LOGS.refused({ components: 'true' }))), WHY.componentProcessed],+ [jobAnswer(jobRow('<importexportxml>')), WHY.unreadable],+ [jobAnswer(jobRow(null)), WHY.noLog],+ [{ statusCode: 503, headers: {}, body: '{}' }, WHY.http(503)],+ [{ statusCode: 403, headers: {}, body: JSON.stringify({ error: { message: 'principal user is missing prvReadImportJob privilege' } }) }, WHY.http(403)],+ [{ error: 'Request timed out' }, WHY.noAnswer],+ ];+ for (const [job, reason] of cases) {+ const { request } = importFiles();+ const platform = platformFor({ sends: [concurrencyAnswer(), ok()], job });+ const { pac, calls } = fakePac(() => ({ status: 0, stdout: '', stderr: '' }));+ await assert.rejects(ss.runImport(request, { http: platform.http, sdkFirst: importingOver(), importJobId: JOB, pac, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${NOT_PROVEN(reason)}`);+ assert.deepStrictEqual(ss.describeFailure(err), { ok: false, error: err.message, code: 'CONNECTION_ERROR', status: 429, importJobId: JOB });+ return true;+ }, reason);+ assert.deepStrictEqual([platform.imports().length, platform.jobReads().length, platform.waits.length, calls.length], [1, 1, 0, 0], `${reason}: one send, one read, no wait, pac not asked`);+ }+});++test('import: a refusal that is not proven after one that was sent again keeps the count — both sentences, and the job to look up is the LAST send\'s', async () => {+ const { request } = importFiles();+ const platform = platformFor({ sends: [concurrencyAnswer(), concurrencyAnswer(), ok()], job: jobsAnsweringInOrder(NO_SUCH_JOB, jobAnswer(jobRow(LOGS.failedAfterStart()))) });+ await assert.rejects(ss.runImport(request, { http: platform.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ const [, second] = platform.imports().map(jobIdOf);+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${RESENT_AS('0x80071151')(2, '10 s')} ${NOT_PROVEN(WHY.otherError, second)}`);+ assert.deepStrictEqual([err.importJobId, err.importAttempts], [second, 2]);+ assert.deepStrictEqual(err.importRefusals, [{ importJobId: JOB, status: 429, code: '0x80071151', waitedMs: 10000, proof: 'job-absent' }]);+ assert.deepStrictEqual(ss.describeFailure(err), { ok: false, error: err.message, code: 'CONNECTION_ERROR', status: 429, importJobId: second, importAttempts: 2, importRefusals: err.importRefusals });+ return true;+ });+ assert.strictEqual(platform.imports().length, 2);+});++// A job whose read answers 404 for each of the first four refused sends — each is proven, so each is waited out and sent again — and `last` for every read after them: the failure's own read of the LAST send's job.+const lastJobAnswering = (last, proofs = 4) => {+ let reads = 0;+ return () => { reads += 1; return reads <= proofs ? NO_SUCH_JOB : last; };+};++test('import: when the sends run out on a refusal with 0x80071151 the failure never says "run the import again" outright, whatever the job of that last send is — it was not looked at, so the failure says what to look up first', async () => {+ const answer = (statusCode, body = {}) => ({ statusCode, headers: {}, body: JSON.stringify(body) });+ const cases = [+ ['a job that is still running', jobAnswer(jobRow(LOGS.running(), { completed: false }))],+ ['a job that applied the package', jobAnswer(jobRow(LOGS.succeeded()))],+ ['a job that does not exist', NO_SUCH_JOB],+ ['a read that is refused (403)', answer(403, { error: { message: 'principal user is missing prvReadImportJob privilege' } })],+ ['a read that fails (503)', answer(503)],+ ['a read that gets no answer', { error: 'Request timed out' }],+ ];+ for (const [what, last] of cases) {+ const platform = platformFor({ sends: Array.from({ length: 6 }, () => concurrencyAnswer()), job: lastJobAnswering(last) }); // a sixth would be answered, too: it must never be asked+ const { pac, calls } = fakePac(() => ({ status: 0, stdout: '', stderr: '' }));+ await assert.rejects(ss.runImport(importFiles().request, { http: platform.http, sdkFirst: importingOver(), importJobId: JOB, pac }), (err) => {+ const ids = platform.imports().map(jobIdOf);+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${RESENT_AS('0x80071151')(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(ids[4])}`, what);+ assert.ok(!err.message.includes(RUN_AGAIN), `${what}: the advice that nothing has proven safe is not given`);+ assert.deepStrictEqual([err.code, err.statusCode, err.importJobId, err.importAttempts], ['CONNECTION_ERROR', 429, ids[4], 5], what);+ assert.deepStrictEqual(ss.describeFailure(err), { ok: false, error: err.message, code: 'CONNECTION_ERROR', status: 429, importJobId: ids[4], importAttempts: 5, importRefusals: err.importRefusals }, what);+ return true;+ }, what);+ assert.strictEqual(platform.imports().length, 5, `${what}: five sends, and no sixth`);+ assert.deepStrictEqual(platform.jobReads().map((r) => new URL(r.url).search), [...Array(4).fill(PROOF_READ), '?$select=data'], `${what}: the four proofs, then the one read of the last job's log that every failed import makes — never a fifth proof`);+ assert.deepStrictEqual(platform.waits, [10000, 20000, 40000, 60000], what);+ assert.strictEqual(calls.length, 0, `${what}: pac is not asked`);+ }+});++test('import: the log of the last send\'s job is still quoted when it says why the import failed — and the advice is still to look that job up first, since the quotation is not the rule that proves it', async () => {+ for (const [what, last, quoted] of [+ ['an import that failed after it began', jobAnswer(jobRow(LOGS.failedAfterStart())), 'its status is The import failed.'],+ ['an import refused at the lock, which is the shape the rule accepts', jobAnswer(jobRow(LOGS.refused())), `its status is ${REFUSAL_STATUS}`],+ ]) {+ const platform = platformFor({ sends: Array.from({ length: 5 }, () => concurrencyAnswer()), job: lastJobAnswering(last) });+ await assert.rejects(ss.runImport(importFiles().request, { http: platform.http, sdkFirst: importingOver(), importJobId: JOB }), (err) => {+ const ids = platform.imports().map(jobIdOf);+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} The import job's log (importjobs(${ids[4]})) says: ${quoted} ${RESENT_AS('0x80071151')(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(ids[4])}`, what);+ return true;+ }, what);+ }+});++test('import: the sentence about the last send is the one for the KIND of refusal it was — a lock code says what it always said, 0x80071151 says what to look up — whichever kind the sends before it were', async () => {+ const lockLast = platformFor({ sends: [...Array.from({ length: 4 }, () => concurrencyAnswer()), lockAnswer()] });+ await assert.rejects(ss.runImport(importFiles().request, { http: lockLast.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${LOCK_REFUSAL.message} ${RESENT_AS('0x80071151')(5, '10 s, 20 s, 40 s, 60 s')} ${RUN_AGAIN}`);+ return true;+ });+ const concurrencyLast = platformFor({ sends: [...Array.from({ length: 4 }, () => lockAnswer()), concurrencyAnswer()] });+ await assert.rejects(ss.runImport(importFiles().request, { http: concurrencyLast.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message} ${RESENT(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(concurrencyLast.imports().map(jobIdOf)[4])}`);+ return true;+ });+});++test('import: when the sends run out on an answer that is not a refusal to start — a 429 of another kind, or 0x80071151 with other words — the failure is the platform\'s own, judged like a first send: what the sends before it were, and no advice to run the import again', async () => {+ const others = [+ ['a service protection limit', '0x80072322', 'Number of requests exceeded the limit of 6000 over time window of 300 seconds.'],+ ['0x80071151 with its documented words alone', '0x80071151', DOCUMENTED_CONCURRENCY_TEXT],+ ['an operation that failed because of another, which had started', '0x80071154', 'The current Import operation failed due to another concurrent operation running at the same time. Please try again later.'],+ ];+ for (const [what, code, message] of others) {+ const platform = platformFor({ sends: [...Array.from({ length: 4 }, () => lockAnswer()), lockAnswer({ code, message })] });+ await assert.rejects(ss.runImport(importFiles().request, { http: platform.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${message} ${RESENT(5, '10 s, 20 s, 40 s, 60 s')}`, what);+ assert.deepStrictEqual([err.statusCode, err.importAttempts], [429, 5], what);+ return true;+ }, what);+ assert.deepStrictEqual([platform.imports().length, platform.jobReads().length], [5, 4], `${what}: five sends, the four proofs and no more`);+ }+});++test('the client tells the listener which refusal the sends ran out on — once, with the job it carried, its status and its code, for either kind of refusal — and of no earlier refusal and no other answer', async () => {+ const told = async (sends, extra = {}) => {+ const world = refusedImport({ sends, ...extra });+ await world.post();+ return world;+ };+ for (const [code, refusal] of [['0x8004F064', () => lockAnswer()], ['0x80071151', () => concurrencyAnswer()]]) {+ const world = await told(Array.from({ length: 6 }, () => refusal()));+ const ids = world.imports().map(jobIdOf);+ assert.deepStrictEqual(world.exhausted, [{ importJobId: ids[4], status: 429, code }], code);+ assert.strictEqual(world.jobReads().length, 4, `${code}: the job of the last send is not read`);+ assert.deepStrictEqual(world.told.map((event) => event.importJobId), ids.slice(0, 4), `${code}: the four before it were sent again, and are told as that`);+ }+ // The last send's own kind decides, not the kind of the others.+ const mixed = await told([...Array.from({ length: 4 }, () => concurrencyAnswer()), lockAnswer(), ok()]);+ assert.deepStrictEqual(mixed.exhausted.map((event) => event.code), ['0x8004F064']);+ // Not told: a refusal that is sent again, an answer that is not a refusal to start, a send the platform takes, a retry the time ended, and a refusal whose job proves nothing.+ const gateway = { statusCode: 504, headers: {}, body: JSON.stringify({ error: { code: '0x80048d19', message: 'gateway timeout' } }) };+ const quiet = [+ ['a refusal that is sent again and taken', await told([lockAnswer(), concurrencyAnswer(), ok()])],+ ['a gateway on the fifth send', await told([...Array.from({ length: 4 }, () => lockAnswer()), gateway, ok()])],+ ['a service protection limit on the fifth send', await told([...Array.from({ length: 4 }, () => lockAnswer()), lockAnswer({ code: '0x80072322', message: 'Number of requests exceeded the limit.' }), ok()])],+ ['0x80071151 with its documented words alone on the fifth send', await told([...Array.from({ length: 4 }, () => lockAnswer()), lockAnswer({ code: '0x80071151', message: DOCUMENTED_CONCURRENCY_TEXT }), ok()])],+ ['a refusal whose job proves nothing', await told([concurrencyAnswer(), ok()], { job: jobAnswer(jobRow(LOGS.running(), { completed: false })) })],+ ['a retry that the time ended', await told([askingConcurrency(600), ok()])],+ ];+ for (const [what, world] of quiet) assert.deepStrictEqual(world.exhausted, [], what);+ // A client that was given no listener for it is not harmed by the refusal the sends ran out on.+ const silent = ss.solutionHttpClient(ENV, platformFor({ sends: Array.from({ length: 6 }, () => lockAnswer()) }).http, { onImportRefused: () => {} });+ assert.strictEqual((await silent.post(`${ENV}/api/data/v9.0/ImportSolution`, importBody())).status, 429);+});++test('import: nothing the settings file holds is in a sentence a refusal with 0x80071151 adds — the platform\'s words that quote it are withheld, and the run\'s own sentences, which hold no value, are shown whole', async () => {+ const quoting = concurrencyAnswer({ message: `${REFUSAL_STATUS} (value ${SECRET}, connection ${CONNECTION_ID}, plain ${PLAIN})` });+ const quoted = importFiles(filled());+ const unproven = platformFor({ sends: [quoting, ok()], job: jobAnswer(jobRow(LOGS.running(), { completed: false })) });+ await assert.rejects(ss.runImport(quoted.request, { http: unproven.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${WITHHELD('message')} ${NOT_PROVEN(WHY.unfinished)}`);+ const printed = JSON.stringify(ss.describeFailure(err));+ for (const value of [SECRET, CONNECTION_ID, PLAIN]) assert.ok(!printed.includes(value), value);+ return true;+ });+ const exhausted = platformFor({ sends: Array.from({ length: 5 }, () => quoting) });+ await assert.rejects(ss.runImport(importFiles(filled()).request, { http: exhausted.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${WITHHELD('message')} ${RESENT_AS('0x80071151')(5, '10 s, 20 s, 40 s, 60 s')} ${NOT_LOOKED_AT(exhausted.imports().map(jobIdOf)[4])}`);+ return true;+ });+});++test('import: a refusal with 0x80071151 whose message does not begin "Cannot start" is reported exactly as an import refused for any other reason always was — the SDK\'s code and the status, the job that was sent, no count, no list — and pac is not asked', async () => {+ const { request } = importFiles();+ const platform = platformFor({ sends: [lockAnswer({ code: CONCURRENCY_REFUSAL.code, message: DOCUMENTED_CONCURRENCY_TEXT }), ok()] });const { pac, calls } = fakePac(() => ({ status: 0, stdout: '', stderr: '' }));await assert.rejects(ss.runImport(request, { http: platform.http, sdkFirst: importingOver(), importJobId: JOB, pac, readJobLog: async () => null }), (err) => {- assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${CONCURRENCY_REFUSAL.message}`);+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${DOCUMENTED_CONCURRENCY_TEXT}`);assert.deepStrictEqual(ss.describeFailure(err), { ok: false, error: err.message, code: 'CONNECTION_ERROR', status: 429, importJobId: JOB });return true;});@@ -2503,6 +2988,23 @@ test('import: a retry whose budget the proof read used up says so — the refusa});});+test('import: a retry whose wait overran the five minutes says so — the refusal, the sends there were, and the time that was spent — for a refusal with 0x80071151 as for a lock code', async () => {+ for (const [what, refusal, message, resent] of [+ ['0x80071151', concurrencyAnswer, CONCURRENCY_REFUSAL.message, RESENT_AS('0x80071151')],+ ['a lock code', lockAnswer, LOCK_REFUSAL.message, RESENT],+ ]) {+ // Every timer resumes 140 s late: the first wait ends at 150 s, the second, which was asked for 20 s, at 310 s.+ const world = clockedImport({ sends: Array.from({ length: 5 }, () => () => refusal()), lateMs: 140000 });+ await assert.rejects(ss.runImport(importFiles().request, { http: world.http, sdkFirst: importingOver(), importJobId: JOB, readJobLog: async () => null }), (err) => {+ const ids = world.imports().map(jobIdOf);+ assert.strictEqual(ids.length, 2, what);+ assert.strictEqual(err.message, `HTTP 429 from ${ENV}/api/data/v9.0/ImportSolution: ${message} ${resent(2, '10 s')} ${OUT_OF_TIME('310 s')}`, what);+ assert.deepStrictEqual([err.importJobId, err.importAttempts], [ids[1], 2], what);+ return true;+ }, what);+ }+});+test('import: when the sends run out the failure is not described as one that ran out of time, and a retry that ended for time is not described as one whose sends ran out', async () => {const { request } = importFiles();const sends = clockedImport({ sends: Array.from({ length: 5 }, () => () => lockAnswer()) });diff --git a/plugins/model-apps/scripts/tests/spec-lint-app-access.test.js b/plugins/model-apps/scripts/tests/spec-lint-app-access.test.jsnew file mode 100644index 000000000..846fd4be1--- /dev/null+++ b/plugins/model-apps/scripts/tests/spec-lint-app-access.test.js@@ -0,0 +1,165 @@+'use strict';+// The lint's access advice, for an app that is EXTENDED rather than built: a maker downloads an app that already has usable security roles+// and adds a table, leaving `personas[]` out on purpose (a persona's role is converged to the privileges the spec declares, so it is not+// how to add one table to somebody else's role) and planning the additive grants with `roleGrants[]`.+//+// Two things were wrong. "no personas[]" told that maker the app "opens only for system administrators" — a claim about the DEPLOYED app that a+// spec which authors no role cannot make — and the only way to silence it was to redefine the existing roles. And nothing said what is+// true of that spec: the new table is held by no role this spec grants, so users of the app's roles cannot use it until a grant is made.+//+// The checks are offline, so what they can know is what the spec carries: a download writes the app's unique name and the ids of its pages and+// dashboards, and a spec for a new app writes none of them. Nothing in a spec PROVES the app is new, so the advice for a spec with no such mark+// is worded as a condition.+const { test } = require('node:test');+const assert = require('node:assert/strict');+const { lintAppSpec } = require('../lib/spec-lint.js');+const { lintSpec } = require('../lint-app-spec.js');+const { extensionSpec, newAppSpec, grant, persona } = require('./helpers/app-access-specs.js');++// Every way the plugin has put "this app is administrator-only" into a sentence.+const ADMIN_ONLY = /only for (system )?admin|opens only|administrator-only|admin-only|only administrators/i;++const noRoles = (r) => r.warnings.find((w) => /^no personas\[\]/.test(w));+const noAccess = (r) => r.warnings.filter((w) => /no access declared/.test(w));++test('an extension of an existing app that leaves personas[] empty is not told its app is administrator-only', () => {+ const r = lintAppSpec(extensionSpec());+ const w = noRoles(r);+ assert.ok(w, `still says the jobs are not recorded: ${JSON.stringify(r.warnings)}`);+ assert.doesNotMatch(w, ADMIN_ONLY, 'a spec that authors no role cannot say who can open the deployed app');+ assert.match(w, /authors no security role/, 'what IS true of the spec');+});++test('the advice for an extension says the app already exists and its roles are left as they are, and points at roleGrants[]', () => {+ const w = noRoles(lintAppSpec(extensionSpec()));+ assert.match(w, /already exists/);+ assert.match(w, /leaves the roles/);+ assert.match(w, /roleGrants\[\]/, 'the way to give an existing role a new table');+ assert.match(w, /app\.uniqueName/, 'names what the spec carries that says so');+});++test('a spec that carries nothing of a deployed app words the answer as a condition, never as a fact', () => {+ const r = lintAppSpec(newAppSpec());+ const w = noRoles(r);+ assert.ok(w, JSON.stringify(r.warnings));+ assert.match(w, /\bIf the app is new\b/, 'conditional');+ assert.match(w, /System Administrator role only/, 'what a new app is associated with');+ assert.match(w, /already exists, it keeps the roles it has/, 'and what an existing one keeps');+ assert.doesNotMatch(w, ADMIN_ONLY);+});++test('each mark a download writes is read as a mark of an existing app', () => {+ for (const [what, edit] of [+ ['app.uniqueName', (s) => { s.app.uniqueName = 'contoso_support'; }],+ ['pages[].pageId', (s) => { s.pages = [{ key: 'home', name: 'Home', pageId: '11111111-2222-3333-4444-555555555555', source: { kind: 'tsx', codeFile: 'home.tsx' } }]; }],+ ['dashboards[].dashboardId', (s) => { s.dashboards = [{ name: 'Overview', dashboardId: '11111111-2222-3333-4444-555555555555', tiles: [] }]; }],+ ]) {+ const s = newAppSpec();+ edit(s);+ const w = noRoles(lintAppSpec(s));+ assert.match(w, /already exists/, what);+ assert.match(w, new RegExp(what.replace(/[[\]]/g, '\\$&')), `${what} is named`);+ }+});++test('a new table that no persona and no roleGrants[] entry grants a privilege on is flagged', () => {+ const r = lintAppSpec(extensionSpec());+ const flagged = noAccess(r);+ assert.equal(flagged.length, 1, JSON.stringify(r.warnings));+ assert.match(flagged[0], /contoso_baseline/);+ assert.match(flagged[0], /roleGrants\[\]/, 'says how to give an existing role the table');+ assert.match(flagged[0], /cannot use it until a grant is made/);+ assert.doesNotMatch(flagged[0], /contoso_project/, 'a table the app already holds is not introduced by this spec');+ assert.equal(r.ok, true, 'advice, never an error');+ assert.deepEqual(r.errors, []);+});++test('a roleGrants[] entry that covers the new table satisfies the check, and the neutral note about the roles stays', () => {+ const s = extensionSpec();+ s.roleGrants = [grant('Contoso PM - Project Manager', 'contoso_baseline', ['create', 'read', 'write'])];+ const r = lintAppSpec(s);+ assert.deepEqual(noAccess(r), [], JSON.stringify(r.warnings));+ assert.ok(noRoles(r), 'the spec still records no jobs');+ assert.doesNotMatch(noRoles(r), ADMIN_ONLY);+});++test('a grant given by role id covers the table the same way', () => {+ const s = extensionSpec();+ s.roleGrants = [grant('33333333-3333-3333-3333-333333333333', 'contoso_baseline')];+ assert.deepEqual(noAccess(lintAppSpec(s)), []);+});++test('a persona privilege — on a job or in additionalPrivileges — covers the table too', () => {+ const onJob = newAppSpec();+ onJob.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'], scope: 'user' }])];+ assert.deepEqual(noAccess(lintAppSpec(onJob)), []);++ const additional = newAppSpec();+ additional.personas = [persona('Agent', [{ entity: 'account', access: ['read'] }], { additionalPrivileges: [{ entity: 'contoso_ticket', access: ['read'] }] })];+ assert.deepEqual(noAccess(lintAppSpec(additional)), []);+});++test('personas that exist but leave a new table without a privilege still get that table flagged', () => {+ const s = newAppSpec({ tables: ['contoso_ticket', 'contoso_note'] });+ s.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read'] }])];+ const flagged = noAccess(lintAppSpec(s));+ assert.equal(flagged.length, 1);+ assert.match(flagged[0], /contoso_note/);+ assert.doesNotMatch(flagged[0], /contoso_ticket/);+});++test('one warning names every uncovered new table and none that is covered', () => {+ const s = extensionSpec({ newTables: ['contoso_baseline', 'contoso_risk', 'contoso_issue'] });+ s.roleGrants = [grant('Contoso PM - Viewer', 'contoso_risk')];+ const flagged = noAccess(lintAppSpec(s));+ assert.equal(flagged.length, 1, 'one warning for the spec, not one per table');+ assert.match(flagged[0], /contoso_baseline/);+ assert.match(flagged[0], /contoso_issue/);+ assert.doesNotMatch(flagged[0], /contoso_risk/);+});++test('the table is matched by its logical name in any letter case, and a grant of no access covers nothing', () => {+ const upper = extensionSpec();+ upper.entities[1].schemaName = 'Contoso_Baseline';+ upper.roleGrants = [grant('Contoso PM - Viewer', 'CONTOSO_BASELINE')];+ assert.deepEqual(noAccess(lintAppSpec(upper)), []);++ const empty = extensionSpec();+ empty.roleGrants = [{ role: 'Contoso PM - Viewer', privileges: [{ entity: 'contoso_baseline', access: [] }] }];+ assert.equal(noAccess(lintAppSpec(empty)).length, 1, 'an empty access[] grants nothing');+});++test('a table the app already holds is never flagged, whatever grants the spec has', () => {+ const s = extensionSpec({ newTables: [] });+ assert.deepEqual(noAccess(lintAppSpec(s)), []);+});++test('a spec whose personas cover every table gets none of the access advice — nothing it already passed now warns', () => {+ const s = newAppSpec();+ s.pages = [{ key: 'overview', name: 'Overview', source: { kind: 'intent' } }];+ s.personas = [persona('Agent', [{ entity: 'contoso_ticket', access: ['read', 'write'], scope: 'user' }])];+ const r = lintAppSpec(s);+ assert.deepEqual(noAccess(r), []);+ assert.equal(noRoles(r), undefined);+ assert.ok(!r.warnings.some((w) => ADMIN_ONLY.test(w)));+});++test('half-typed grants and tables do not stop the lint', () => {+ for (const edit of [+ (s) => { s.roleGrants = {}; },+ (s) => { s.roleGrants = [null, 'x', { role: 'R' }, { role: 'R', privileges: 'x' }, { role: 'R', privileges: [null, { entity: 5 }] }]; },+ (s) => { s.entities.push(null, 'x', { displayName: 'no schema name' }); },+ (s) => { s.personas = [{ persona: 'P', jobs: [{ name: 'j', privileges: [null, { entity: 'contoso_baseline' }] }], additionalPrivileges: 'x' }]; },+ ]) {+ const s = extensionSpec();+ edit(s);+ assert.doesNotThrow(() => lintAppSpec(s), JSON.stringify(s));+ }+});++test('lint-app-spec reports the same advice, tagged lint: and without failing the run', () => {+ const r = lintSpec(extensionSpec());+ assert.equal(r.ok, true, JSON.stringify(r.errors));+ assert.ok(r.warnings.some((w) => /^lint: no personas\[\]/.test(w) && !ADMIN_ONLY.test(w)), JSON.stringify(r.warnings));+ assert.ok(r.warnings.some((w) => /^lint: .*contoso_baseline.*no access declared/.test(w)), JSON.stringify(r.warnings));+});diff --git a/plugins/model-apps/scripts/tests/strict-xml.test.js b/plugins/model-apps/scripts/tests/strict-xml.test.jsindex 18f77b75e..b8a47a010 100644--- a/plugins/model-apps/scripts/tests/strict-xml.test.js+++ b/plugins/model-apps/scripts/tests/strict-xml.test.js@@ -295,3 +295,67 @@ test('readXmlElements: it never reads past a refusal, so a hostile document cannfor (const xml of [`<a>${'<'.repeat(200000)}`, `<a>${'&'.repeat(200000)}`, `<a ${'b="1" '.repeat(1000)}>`, `<${'a'.repeat(200000)} `, `<a b="${'&'.repeat(100000)}`, '<a>'.repeat(10000)]) readXmlElements(xml, all);assert.ok(Date.now() - started < 3000, `${Date.now() - started} ms`);});++// An element a caller asks for says its `path`, the names of its ancestors, so a document that is nested deep and is asked for at every level costs the SQUARE of its depth in memory:+// a few kilobytes of `<a><a><a>…` are enough to exhaust the heap of the process that reads them. A caller that reads a document it does not trust says how deep it may be.+test('readXmlElements { maxDepth }: a document nested deeper than the caller allows is refused at the element that goes over — at, or one level below, the bound', () => {+ const nest = (depth, inner = '') => `${'<a>'.repeat(depth)}${inner}${'</a>'.repeat(depth)}`;+ const bounded = (xml, maxDepth) => readXmlElements(xml, all, { maxDepth });+ assert.strictEqual(bounded(nest(3), 3).ok, true, 'three levels, three allowed');+ const over = bounded(nest(4), 3);+ assert.strictEqual(over.ok, false);+ assert.deepStrictEqual(Object.keys(over).sort(), ['detail', 'ok'], 'a document that is not read answers no element at all');+ assert.match(over.detail, /^elements nested more than 3 levels deep, at line 1, column 10$/, 'it says where: the fourth <a> starts after nine characters');+ // An empty-element tag is a level of its own, as is the root.+ assert.strictEqual(bounded(nest(2, '<b/>'), 3).ok, true);+ assert.strictEqual(bounded(nest(3, '<b/>'), 3).ok, false);+ assert.strictEqual(bounded('<a/>', 1).ok, true);+ assert.strictEqual(bounded('<a><b/></a>', 1).ok, false);+ // Siblings are not nesting: a document as wide as you like is read.+ assert.strictEqual(bounded(`<r>${'<a><b/></a>'.repeat(5000)}</r>`, 3).elements.length, 10001);+ // The path of an element is as long as its depth, so the bound is also the bound of what the answer holds.+ const deepest = bounded(nest(5, '<z/>'), 6).elements.at(-1);+ assert.strictEqual(deepest.path.split('/').length, 5);+ // A document of thousands of levels asked for at every one is refused at the bound, not read: the answer would be gigabytes of paths.+ const started = Date.now();+ const hostile = bounded(nest(6000), 32);+ assert.strictEqual(hostile.ok, false);+ assert.match(hostile.detail, /nested more than 32 levels deep/);+ assert.ok(Date.now() - started < 3000, `${Date.now() - started} ms`);+ // Without the option nothing changes: a nesting of any depth is read, as before.+ assert.strictEqual(readXmlElements(nest(300), () => false).ok, true);+ assert.strictEqual(readXmlElements(nest(300), () => false, {}).ok, true);+ assert.strictEqual(readXmlElements(nest(300), () => false, { maxDepth: undefined }).ok, true);+ // The bound is a whole number of at least one — anything else is a mistake of the caller, which must not read as "no bound".+ for (const wrong of [0, -1, 1.5, NaN, Infinity, '3', null, {}]) assert.throws(() => readXmlElements('<a/>', all, { maxDepth: wrong }), TypeError, String(wrong));+});++// What a spreadsheet's rows and cells hold is elements. A caller that reads such a document by the elements it names must not lose what is written between them — a sentence in a+// row, a comment, a CDATA section — because the text it skipped may be what the document meant.+test('readXmlElements { elementOnly }: an element the caller says holds elements and white space only refuses text, a CDATA section, a comment or an instruction directly inside it', () => {+ const holdsElements = (name) => name === 'Table' || name === 'Row';+ const read = (xml) => readXmlElements(xml, all, { elementOnly: holdsElements });+ const readOk = (xml) => { const r = read(xml); assert.strictEqual(r.ok, true, `${JSON.stringify(xml)}: ${r.detail}`); return r.elements; };+ assert.deepStrictEqual(readOk('<Table>\r\n <Row> <Cell>x y</Cell>\t</Row>\n<Row/></Table>').map((e) => e.name), ['Table', 'Row', 'Cell', 'Row'], 'elements and white space: what such an element is made of');+ for (const [what, xml, detail] of [+ ['text before its elements', '<Table>t<Row/></Table>', /^text inside <Table>, which holds elements only, at line 1, column 8$/],+ ['text after them', '<Table><Row/>t</Table>', /^text inside <Table>, which holds elements only, at line 1, column 14$/],+ ['text in an element', '<Table><Row>text</Row></Table>', /text inside <Row>/],+ ['a reference to a space', '<Table><Row> </Row></Table>', /text inside <Row>/],+ ['a CDATA section', '<Table><Row><![CDATA[ ]]></Row></Table>', /a CDATA section inside <Row>, which holds elements only/],+ ['a comment', '<Table><!-- c --><Row/></Table>', /a comment inside <Table>, which holds elements only/],+ ['an instruction', '<Table><Row><?p x?></Row></Table>', /a processing instruction inside <Row>, which holds elements only/],+ ]) {+ const r = read(xml);+ assert.strictEqual(r.ok, false, what);+ assert.deepStrictEqual(Object.keys(r).sort(), ['detail', 'ok'], `${what}: no element is answered`);+ assert.match(r.detail, detail, what);+ }+ // Only the elements the caller names: the text of any other is its own, and so are the prolog and the epilog.+ assert.deepStrictEqual(readOk('<!-- c --><?p x?><Table><Cell>t<!-- c --><![CDATA[x]]><?p x?>&</Cell></Table><!-- c -->').map((e) => e.name), ['Table', 'Cell']);+ // Without the option nothing changes: text, comments, CDATA sections and instructions are read wherever they are.+ assert.strictEqual(readXmlElements('<Table>t<!-- c --><![CDATA[x]]><?p x?><Row>t</Row></Table>', all).ok, true);+ assert.strictEqual(readXmlElements('<Table>t</Table>', all, { elementOnly: undefined }).ok, true);+ // It is a function of the name, or nothing.+ for (const wrong of [true, 'Table', ['Table'], {}, null]) assert.throws(() => readXmlElements('<a/>', all, { elementOnly: wrong }), TypeError, String(wrong));+});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 472948913..8c0632ace 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@@ -40,9 +40,13 @@ const tableId = (schema) => `${hex(hash(`table.${schema}`), 8)}-0000-4000-8000-$const duplicateAttribute = (name, table) => ({ status: 400, headers: {}, body: { error: { code: '0x80060304', message: `Attribute ${name} already exists for entity ${table}.` } } });// Columns every table gets from the platform, whatever the request says.const SYSTEM_COLUMNS = ['createdon', 'modifiedon', 'ownerid', 'statecode', 'statuscode'];-// The most bytes an alternate key may hold. A text column takes 2 bytes a character, so a name column of 450 characters is the longest-// that can be in a key alone — and the 850 characters some environments make of a new name column are far too long.-const KEY_BYTES_LIMIT = 900;+// The most bytes an alternate key may hold on the environment measured: the platform's own answer to a key that is too large names the+// limit (HTTP 400, code 0x80060895, "Index size exceeded the size limit of 1700 bytes. The key is too large. Try removing some columns or+// making the strings in string columns shorter."). A text column takes 2 bytes a character, so the 850 characters that are the most a name+// column may have are 1,700 bytes by themselves: that column alone fits, and no other column fits beside it. Microsoft Learn documents 900+// bytes; an environment that enforces that is the stub's `keyBytesLimit: 900`.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys+const KEY_BYTES_LIMIT = 1700;// A table or a column in a metadata path is named by its logical name — the alternate key, `LogicalName='new_ticket'` — or by its// MetadataId, the primary key. A table's MetadataId stops answering when the table is deleted, whatever is made under its name afterwards.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/retrieve-metadata-name-metadataid@@ -134,6 +138,7 @@ function fakeDataverse({tableReadBack = null, // (table) => response | undefined; overrides the read the SDK makes of a table it just createdlookupLag = 0, // how many reads of a new table BY NAME answer 404 before it shows (the metadata-read lag)keepsAskedLength = false, // the environment that keeps the length asked of a plain text primary column in a one-attribute create+ plainPrimaryLength = 850, // what an environment that ignores the length asked makes of a plain text primary column: the one measured makes the most there is, 850keepsAskedRequired = false, // the environment that keeps the required level asked of a plain text primary column (the one measured stores it None whatever is sent)levelRead = null, // (n) => response | undefined; overrides the typed read of one column's RequiredLevel (the SDK's check of a primary column's level)columnListRead = null, // (n) => response | undefined; overrides the read of all of a table's columns with their RequiredLevel (the build's read of what an existing table holds)@@ -141,6 +146,8 @@ function fakeDataverse({identityRead = null, // (n) => response | undefined; overrides the read of which table answers to a name (its MetadataId and primary name column)updateFails = null, // (body) => response | falsy, for the PUT of a typed column; a falsy answer lets it throughkeyFails = null, // (body, table) => response | falsy, for the request that creates an alternate key; a falsy answer lets it through+ keyBytesLimit = KEY_BYTES_LIMIT, // the most bytes a key may hold on this environment (the one measured answers 1,700; Learn documents 900)+ createdOnColumn = false, // list `createdon` among a new table's columns, as the DateTime the platform gives every table, so a key can name itextraCompanions = null, // (body) => names the platform makes beside a column that nothing in the build lists} = {}) {const log = [];@@ -279,7 +286,7 @@ function fakeDataverse({// What the platform makes of the primary name column's length in a create that carries only that column (measured on two// environments): one keeps the length asked, the other makes a plain text column 850 whatever length was asked and keeps// the length asked of an auto-numbered one.- primaryLength: !body.Attributes[0].AutoNumberFormat && !keepsAskedLength ? 850 : body.Attributes[0].MaxLength,+ primaryLength: !body.Attributes[0].AutoNumberFormat && !keepsAskedLength ? plainPrimaryLength : body.Attributes[0].MaxLength,};const collision = firstTaken(table, body.Attributes);if (collision) return refuse(p, duplicateAttribute(collision, logical));@@ -290,6 +297,8 @@ function fakeDataverse({const primary = clone(body.Attributes[0]);if (!primary.AutoNumberFormat && !keepsAskedRequired) primary.RequiredLevel = { ...primary.RequiredLevel, Value: 'None' };addColumn(table, primary);+ // `createdon` is one of the columns the platform gives every table (SYSTEM_COLUMNS), a DateTime: a key may name it, though no spec declares it.+ if (createdOnColumn) table.columns.set('createdon', { body: { '@odata.type': 'Microsoft.Dynamics.CRM.DateTimeAttributeMetadata', SchemaName: 'createdon' }, row: columnRow(table, { SchemaName: 'createdon' }) });if (createCommitsThenFails) return refuse(p, createCommitsThenFails(body));return created(`EntityDefinitions(${table.id})`);}@@ -302,8 +311,9 @@ function fakeDataverse({return created(`EntityDefinitions(LogicalName='${m[1]}')/Attributes(${attributeId(t.logical, body.SchemaName)})`);}// The request that creates an alternate key. The platform validates a key when it is created: its columns must exist, and the- // key's total size must stay within what an index holds — 900 bytes, 2 for each character of a text column. This stub refuses a- // key that is too large with a message of its own: the rule is the platform's, the wording is not.+ // key's total size must stay within what an index holds — 2 bytes for each character of a text column (see KEY_BYTES_LIMIT). The+ // answers are the platform's own, as measured: a key that is too large is HTTP 400 with code 0x80060895, a key made twice is HTTP 400+ // with code 0x80060893.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keysif ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Keys$/.exec(p))) {const t = tables.get(m[1]);@@ -311,7 +321,7 @@ function fakeDataverse({const failure = keyFails && keyFails(body, t);if (failure) return refuse(p, failure);const name = String(body.SchemaName).toLowerCase();- if (t.keys.has(name)) return refuse(p, reply(400, { error: { message: `A key with the same name already exists on ${t.logical}.` } }));+ if (t.keys.has(name)) return refuse(p, reply(400, { error: { code: '0x80060893', message: `An entity key with the name ${body.SchemaName} already exists on entity ${t.logical}.` } }));let bytes = 0;for (const attribute of body.KeyAttributes) {const column = t.columns.get(attribute);@@ -319,7 +329,7 @@ function fakeDataverse({const isText = /StringAttributeMetadata$/.test(String(column.body['@odata.type']));bytes += isText ? 2 * (attribute === t.primaryName ? t.primaryLength : (column.body.MaxLength || 100)) : 8;}- if (bytes > KEY_BYTES_LIMIT) return refuse(p, reply(400, { error: { message: `The key ${body.SchemaName} is ${bytes} bytes long; a key may hold at most ${KEY_BYTES_LIMIT}.` } }));+ if (bytes > keyBytesLimit) return refuse(p, reply(400, { error: { code: '0x80060895', message: `Index size exceeded the size limit of ${keyBytesLimit} bytes. The key is too large. Try removing some columns or making the strings in string columns shorter.` } }));const id = attributeId(t.logical, `key.${body.SchemaName}`);t.keys.set(name, { body: clone(body), id });return created(`EntityDefinitions(LogicalName='${m[1]}')/Keys(${id})`);@@ -572,6 +582,7 @@ test('each column\'s body in the change set equals the body the per-column pathassert.strictEqual(byName.get('new_title').MaxLength, 200);assert.strictEqual(byName.get('new_email').FormatName.Value, 'Email', 'a Text column\'s format');assert.strictEqual(byName.get('new_email').MaxLength, 120);+ assert.strictEqual(byName.get('new_notes').MaxLength, 4000, 'a Memo column\'s maxLength');assert.strictEqual(byName.get('new_count').RequiredLevel.Value, 'Recommended');assert.strictEqual(byName.get('new_minutes').Format, 'Duration', 'an Integer column\'s display format');assert.strictEqual(byName.get('new_big').AttributeType, 'BigInt', 'a BigInt column');@@ -788,7 +799,7 @@ test('only an answer that leaves the outcome unknown is followed by a read of th// The plugin's own HTTP client over the same stub — what a real build sends: its `postRaw` (the verbatim body a change set needs; the// SDK's DataverseClient.supportsAtomicBatch is true exactly when the client has it), its headers and its retry policy. `slept` records// the waits between attempts (without waiting); the jitter is off, so they are the schedule itself.-function throughAzHttpClient(dv) {+function throughAzHttpClient(dv, clientOptions = {}) {const { createAzHttpClient } = require('../lib/sdk-http-client.js');const sent = [];const slept = [];@@ -802,7 +813,7 @@ function throughAzHttpClient(dv) {else throw new Error(`unexpected ${method} ${url}`);return { statusCode: res.status, headers: res.headers || {}, body: typeof res.body === 'string' ? res.body : (res.body === null || res.body === undefined ? '' : JSON.stringify(res.body)) };};- const httpClient = createAzHttpClient(ORG, { getToken: () => 'test-token', request, sleep: async (ms) => { slept.push(ms); }, random: () => 0 });+ const httpClient = createAzHttpClient(ORG, { getToken: () => 'test-token', request, sleep: async (ms) => { slept.push(ms); }, random: () => 0, ...clientOptions });return { httpClient, sent, slept };}@@ -883,6 +894,247 @@ test('a table still locked after the HTTP client has spent its attempts: the chaassert.deepStrictEqual(events, baseline.events);});+// ── A change set the run's throttle budget has no room to wait for ────────────────────────────────────────────────────────────────────────────+// With a run's budget (lib/throttle-budget.js) the HTTP client does not send the change set again when the wait the service asks for does not fit what is left: it hands the 429 back as it came and tells the budget. The service has asked the+// run to hold back, so the columns are NOT then created one by one — each would be one more request to a service that said to wait — and the phase halts with the budget's halt before any request of a column's own. What the halted phase still owes+// (the length of the name column of the table this run created) is settled as it is for any halt. A refusal the budget did not make — the client's sends ran out while the budget had room — is the fallback it always was.+test('a change set the budget has no room to wait for (HTTP 429, Retry-After ten minutes) stops the phase before any column request — no column is created one by one — and the length the halted phase owes is still set', async () => {+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const { isTransientHalt } = require('../build-model-app.js');+ const dv = fakeDataverse({ batchFails: () => ({ status: 429, headers: { 'retry-after': '600' }, body: TABLE_LOCKED_BODY }) });+ const throttle = makeThrottleBudget();+ const { httpClient, sent, slept } = throughAzHttpClient(dv, { throttle });+ const sdk = await realSdk(httpClient);+ const events = [];+ const warnings = [];+ const spec = oneTable([textColumn('new_a'), { schemaName: 'new_b', type: 'Integer' }], asksFor(120));+ await assert.rejects(+ provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99, throttle }), spec, apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) }),+ (error) => {+ assert.ok(error instanceof BuildHalt);+ assert.strictEqual(error.code, 'throttle-budget-exhausted');+ assert.strictEqual(error.phase, 'data-model');+ assert.strictEqual(error.recoverable, true);+ assert.strictEqual(isTransientHalt(error), true, 'a later run goes on from here');+ assert.match(error.message, /^data-model stopped: the service asked to wait 600 s before the next send, which does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service \(0 s are spent\)\./);+ return true;+ },+ );+ assert.strictEqual(sent.filter((s) => /\/\$batch$/.test(s.url)).length, 1, 'the change set was sent once');+ assert.deepStrictEqual(slept, [], 'and nothing was waited for');+ assert.deepStrictEqual(sent.filter((s) => /\/Attributes$/.test(s.url) && s.method === 'POST'), [], 'no column was created by a request of its own');+ assert.deepStrictEqual(['new_a', 'new_b'].filter((name) => dv.tables.get('new_ticket').columns.has(name)), [], 'and neither column exists');+ assert.deepStrictEqual(warnings.filter((w) => /one by one/.test(w)), [], 'no fallback is announced');+ assert.strictEqual(throttle.declined().count, 1, 'the client told the budget once');+ assert.strictEqual(dv.tables.get('new_ticket').primaryLength, 120, 'the table this run created has the name length the spec asks for: a halted phase still settles it');+ assert.deepStrictEqual(lengthEvents({ events }).map((e) => [e.status, e.label]), [['ok', 'primary column length new_ticket.new_name -> 120']]);+});++test('a change set the budget had room to wait for and the client\'s sends ran out on is not the budget\'s refusal — the columns are created one by one, as before, with the table-was-throttled warning', async () => {+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const dv = fakeDataverse({ batchFails: () => ({ status: 429, headers: { 'retry-after': '1' }, body: TABLE_LOCKED_BODY }) });+ const throttle = makeThrottleBudget();+ const { httpClient, sent, slept } = throughAzHttpClient(dv, { throttle });+ const sdk = await realSdk(httpClient);+ const events = [];+ const warnings = [];+ const spec = oneTable([textColumn('new_a'), textColumn('new_b')]);+ const result = await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99, throttle }), spec, apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) });+ assert.strictEqual(sent.filter((s) => /\/\$batch$/.test(s.url)).length, 6, 'six attempts in all');+ assert.deepStrictEqual(slept, [1000, 2000, 4000, 8000, 8000], 'each wait fit what was left');+ assert.strictEqual(throttle.declined().count, 0, 'so the budget refused nothing');+ assert.strictEqual(sent.filter((s) => /\/Attributes$/.test(s.url) && s.method === 'POST').length, 2, 'and each column was created by its own request');+ assert.deepStrictEqual(warnings, [`table new_ticket was throttled (${LOCKED_REASON}), so its 2 ordinary column(s) are created one by one instead of in one request`]);+ const baseline = await provisionOver(spec, { inlineColumns: false });+ assert.deepStrictEqual(result, baseline.result);+ assert.deepStrictEqual(events, baseline.events);+});++test('through the build, a change set the budget has no room to wait for halts the build once with the budget\'s halt — it is not run again, waits for nothing and creates no column one by one', async () => {+ const { buildModelApp, isTransientHalt } = require('../build-model-app.js');+ const { runSdkBuild } = require('../lib/sdk-build.js');+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const dv = fakeDataverse({ batchFails: () => ({ status: 429, headers: { 'retry-after': '600' }, body: TABLE_LOCKED_BODY }) });+ const warnings = [];+ const waits = [];+ const throttle = makeThrottleBudget({ warn: (line) => warnings.push(line) });+ const { httpClient, sent, slept } = throughAzHttpClient(dv, { throttle });+ const sdk = await realSdk(httpClient);+ const spec = { schemaVersion: 2, ...oneTable([textColumn('new_a'), textColumn('new_b')]), app: { name: 'Budget app' } };+ let attempts = 0;+ const error = await buildModelApp(spec, { apply: true, env: ORG, preResolvedLanguageCode: 1033 }, {+ sdk, provisionSdk: sdk, throttle, log: () => {}, warn: (m) => warnings.push(m), provisionedLanguages: async () => [1033], sleep: async (ms) => { waits.push(ms); },+ discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),+ runBuild: (s, o) => { attempts += 1; return runSdkBuild(s, { ...o, phases: ['data-model'] }); },+ }).then(() => null, (e) => e);+ assert.ok(error, 'the build did not report a success: the service asked it to wait ten minutes');+ assert.strictEqual(error.code, 'throttle-budget-exhausted');+ assert.strictEqual(isTransientHalt(error), true);+ assert.match(error.message, /^data-model stopped: the service asked to wait 600 s before the next send, which does not fit/);+ assert.strictEqual(attempts, 1, 'the phase was not run again to meet the same answer');+ assert.deepStrictEqual([...waits, ...slept], [], 'nothing was waited for, by the client or by the build');+ assert.deepStrictEqual(sent.filter((s) => /\/Attributes$/.test(s.url) && s.method === 'POST'), [], 'no column was created by a request of its own');+ assert.deepStrictEqual(warnings.filter((w) => /one by one/.test(w)), []);+});++// ── What the build owes when the budget refuses a wait ────────────────────────────────────────────────────────────────────────────────────────+// A table this run creates is owed the length the spec asks of its name column, and only this run can pay it: a run in a new process finds the table and leaves its name column as it is (a rebuild must not shorten a column that may hold data),+// and a key over that column is refused for its size while the column keeps the 850 characters some environments make of a new one. So the budget's refusal of one table's length update — the service throttled it for longer than the run has room+// to wait — must not stop the update of the next table's, and a length step that never began must not count as a length that was set. The step guard (makeRunner) stops the steps of the phase after a refusal; the length a table owes is not one of them.+const NOTE_KEY = { schemaName: 'new_note_namekey', displayName: 'Name key', columns: ['new_notename'] };+// Two tables that each ask for a length (120 and 180); the second has an alternate key over its name column, which waits for that length.+function twoOwedLengths({ key = false } = {}) {+ const spec = oneTable([], asksFor(120));+ spec.entities.push({ schemaName: 'new_note', displayName: 'Note', primaryAttribute: { schemaName: 'new_notename', displayName: 'Name', maxLength: 180 }, columns: [], ...(key ? { alternateKeys: [NOTE_KEY] } : {}) });+ return spec;+}+// The first update of a length — the one that asks 120 — is throttled for ten minutes, which the budget has no room for; every other request is healthy.+function firstLengthThrottled() {+ let refused = false;+ return (body) => {+ if (refused || body.MaxLength !== 120) return null;+ refused = true;+ return { status: 429, headers: { 'retry-after': '600' }, body: { error: { message: 'throttled first length update' } } };+ };+}+// One run of the data-model phase as a process makes it: its own SDK over the transport, its own budget, its own record of what is owed. `runnerOf` stands between the engine and its runner.+async function budgetedRun(dv, spec, { owedLengths = new Map(), runnerOf = (runner) => runner } = {}) {+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const warnings = [];+ const events = [];+ const throttle = makeThrottleBudget({ warn: () => {} });+ const { httpClient, sent, slept } = throughAzHttpClient(dv, { throttle });+ const sdk = await realSdk(httpClient);+ const runner = runnerOf(makeRunner({ emit: (e) => events.push(e), total: 99, throttle }));+ const error = await provisionDataModel({+ sdk, provision: sdk, runner, spec, apply: true, owedLengths, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m),+ }).then(() => null, (err) => err);+ return { error, events, warnings, throttle, sent, slept, owedLengths, sdk };+}+const primaryLengths = (dv) => Object.fromEntries([...dv.tables].map(([name, table]) => [name, table.primaryLength]));+const keysOf = (dv) => Object.fromEntries([...dv.tables].map(([name, table]) => [name, [...table.keys.keys()]]));+const lengthRequests = (dv) => dv.log.filter((r) => r.method === 'PUT').map((r) => r.body.MaxLength);++test('the budget refuses the first of two owed name lengths: the second is still set, the key over it waits for the next run, and that run finishes — a length the build owes is not dropped', async () => {+ const { isTransientHalt } = require('../build-model-app.js');+ const dv = fakeDataverse({ updateFails: firstLengthThrottled() });+ const spec = twoOwedLengths({ key: true });+ const first = await budgetedRun(dv, spec);+ assert.strictEqual(first.throttle.declined().count, 1, 'one update was refused for want of room');+ assert.deepStrictEqual(first.slept, [], 'and nothing was waited for');+ assert.ok(first.error instanceof BuildHalt, 'the phase stops at the key, a step of the phase');+ assert.strictEqual(first.error.code, 'throttle-budget-exhausted');+ assert.strictEqual(isTransientHalt(first.error), true, 'a later run goes on from here');+ assert.deepStrictEqual(lengthRequests(dv), [120, 180], 'both tables were asked to set their length');+ assert.deepStrictEqual(primaryLengths(dv), { new_ticket: 850, new_note: 180 }, 'the table whose update was refused keeps the length the platform gave it; the other was set');+ assert.deepStrictEqual(lengthEvents(first).map((e) => [e.status, e.label]), [['error', 'primary column length new_ticket.new_name -> 120'], ['ok', 'primary column length new_note.new_notename -> 180']]);+ assert.deepStrictEqual([...first.owedLengths.keys()], ['new_ticket'], 'what is still owed is the length whose update was refused: the one that was set is paid');+ assert.strictEqual(first.owedLengths.get('new_ticket').tried, true, 'and its step has run and said what became of it');+ assert.deepStrictEqual(keysOf(dv), { new_ticket: [], new_note: [] }, 'the key is a step of the phase, and no step of the phase starts after a refusal');+ // The next run is a new process: it finds both tables, owes nothing, and the key goes over a name column of 180 characters.+ const refusedBefore = dv.refusals.length;+ const next = await budgetedRun(dv, spec);+ assert.strictEqual(next.error, null, 'the next run finishes');+ assert.deepStrictEqual(keysOf(dv), { new_ticket: [], new_note: ['new_note_namekey'] });+ assert.strictEqual(dv.refusals.length, refusedBefore, 'and the platform refuses nothing');+ assert.deepStrictEqual(primaryLengths(dv), { new_ticket: 850, new_note: 180 }, 'a run that finds a table leaves its name column as it is');+});++test('the budget refuses the first of two owed name lengths and no key waits: the second table is set all the same, narrated as any length step is, and only the refused one stays owed', async () => {+ const dv = fakeDataverse({ updateFails: firstLengthThrottled() });+ const run = await budgetedRun(dv, twoOwedLengths());+ assert.strictEqual(run.throttle.declined().count, 1, 'one update was refused for want of room');+ assert.strictEqual(run.error, null, 'the refused update is best-effort, as any failed length step is: the phase goes on');+ assert.deepStrictEqual(primaryLengths(dv), { new_ticket: 850, new_note: 180 });+ assert.deepStrictEqual(lengthEvents(run).map((e) => [e.status, e.label]), [['error', 'primary column length new_ticket.new_name -> 120'], ['ok', 'primary column length new_note.new_notename -> 180']]);+ assert.strictEqual(run.warnings.length, 1, 'one warning, for the table whose update was refused');+ assert.match(run.warnings[0], /^could not set the length of the primary name column new_ticket\.new_name to 120 /);+ assert.deepStrictEqual([...run.owedLengths.keys()], ['new_ticket']);+});++// What an attempt that failed leaves behind (`owedLengths`) is paid by the attempt that follows it, and a refusal of the budget in that attempt does not change that.+test('a debt an earlier attempt left is still paid by a run in which the budget refuses the first of two owed lengths — the second table\'s carried debt is not dropped', async () => {+ let attempt = 1;+ const throttled = firstLengthThrottled();+ const dv = fakeDataverse({ updateFails: (body) => (attempt === 1 ? refusal() : throttled(body)) });+ const spec = twoOwedLengths();+ const owed = new Map();+ // The first attempt creates both tables and cannot set either length: the platform refuses each update, so both are owed, and tried.+ const first = await budgetedRun(dv, spec, { owedLengths: owed });+ assert.strictEqual(first.error, null);+ assert.deepStrictEqual([...owed.keys()].sort(), ['new_note', 'new_ticket']);+ assert.deepStrictEqual(primaryLengths(dv), { new_ticket: 850, new_note: 850 });+ // The retry is handed the debts: the budget refuses the update of the first, and the second is paid all the same.+ attempt = 2;+ const retry = await budgetedRun(dv, spec, { owedLengths: owed });+ assert.strictEqual(retry.throttle.declined().count, 1, 'one update was refused for want of room');+ assert.strictEqual(retry.error, null);+ assert.deepStrictEqual(primaryLengths(dv), { new_ticket: 850, new_note: 180 });+ assert.deepStrictEqual(lengthEvents(retry).map((e) => [e.status, e.label]), [+ ['error', `primary column length new_ticket.new_name -> 120 (${OWED})`],+ ['ok', `primary column length new_note.new_notename -> 180 (${OWED})`],+ ]);+ assert.deepStrictEqual([...owed.keys()], ['new_ticket'], 'the debt of the table whose update was refused stays; the other was paid');+});++test('a length step the runner stopped before it began is not a length that was set: the debt stays, untried, the key is not asked for, and the settlement of a halted build pays it', async () => {+ const { settleOwedLengths } = require('../lib/entity-provision.js');+ const dv = fakeDataverse();+ const spec = keyedTable([NAME_KEY]);+ // The engine's contract is that a runner can stop a step before it calls the step's function — the budget's guard does — and the engine swallows that stop for a best-effort step.+ const stopsLengthSteps = (runner) => ({ ...runner, run: (phase, label, fn, options) => (/^primary column length /.test(label) ? Promise.reject(new Error('the runner stopped the step before it began')) : runner.run(phase, label, fn, options)) });+ const run = await budgetedRun(dv, spec, { runnerOf: stopsLengthSteps });+ assert.deepStrictEqual(lengthRequests(dv), [], 'no update was sent');+ assert.strictEqual(primaryLengths(dv).new_ticket, 850);+ assert.match(run.warnings.join('\n'), /could not set the length of the primary name column new_ticket\.new_name to 120 .*the runner stopped the step before it began/);+ assert.ok(run.error instanceof BuildHalt, 'the key that waits for the length is not made over a column that was not set');+ assert.strictEqual(run.error.code, 'alt-key-name-length-not-set');+ assert.match(run.error.message, /whose length the build could not set to 120 \(.*the runner stopped the step before it began/);+ assert.deepStrictEqual(keyPosts({ dv }), [], 'nothing was sent for the key');+ assert.deepStrictEqual([...run.owedLengths.keys()], ['new_ticket'], 'the debt stays');+ assert.strictEqual(run.owedLengths.get('new_ticket').tried, false, 'and no step has tried it, so a build that stops for good still pays it');+ const warnings = [];+ await settleOwedLengths({ sdk: run.sdk, provision: run.sdk, spec, owed: [...run.owedLengths.values()], warn: (m) => warnings.push(m), sleep: async () => {} });+ assert.deepStrictEqual(warnings, []);+ assert.deepStrictEqual(lengthRequests(dv), [120], 'the settlement sets it');+ assert.strictEqual(primaryLengths(dv).new_ticket, 120);+});++test('through the build, the budget refusing the first of two owed name lengths halts the build once — the second table is set, the length refused is not sent again, and the next run finishes', async () => {+ const { buildModelApp, isTransientHalt } = require('../build-model-app.js');+ const { runSdkBuild } = require('../lib/sdk-build.js');+ const { makeThrottleBudget } = require('../lib/throttle-budget.js');+ const dv = fakeDataverse({ updateFails: firstLengthThrottled() });+ const spec = { schemaVersion: 2, ...twoOwedLengths({ key: true }), app: { name: 'Budget app' } };+ // A run of the build is a process: its own budget, its own SDK, nothing carried from the last but what the environment holds.+ const buildOnce = async () => {+ const waits = [];+ const warnings = [];+ const throttle = makeThrottleBudget({ warn: (line) => warnings.push(line) });+ const { httpClient, sent, slept } = throughAzHttpClient(dv, { throttle });+ const sdk = await realSdk(httpClient);+ let attempts = 0;+ const error = await buildModelApp(spec, { apply: true, env: ORG, preResolvedLanguageCode: 1033 }, {+ sdk, provisionSdk: sdk, throttle, log: () => {}, warn: (m) => warnings.push(m), provisionedLanguages: async () => [1033], sleep: async (ms) => { waits.push(ms); },+ discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),+ runBuild: (s, o) => { attempts += 1; return runSdkBuild(s, { ...o, phases: ['data-model'] }); },+ }).then(() => null, (err) => err);+ return { error, attempts, waits: [...waits, ...slept], sent, warnings };+ };+ const first = await buildOnce();+ assert.ok(first.error, 'the build did not report a success: the service asked it to wait ten minutes');+ assert.strictEqual(first.error.code, 'throttle-budget-exhausted');+ assert.strictEqual(isTransientHalt(first.error), true);+ assert.strictEqual(first.attempts, 1, 'the phase was not run again to meet the same answer');+ assert.deepStrictEqual(first.waits, [], 'nothing was waited for, by the client or by the build');+ assert.deepStrictEqual(lengthRequests(dv), [120, 180], 'each table was asked once: what the build settles after its halt does not send the refused update again');+ assert.deepStrictEqual(primaryLengths(dv), { new_ticket: 850, new_note: 180 });+ const next = await buildOnce();+ assert.strictEqual(next.error, null, 'the next run finishes');+ assert.deepStrictEqual(keysOf(dv), { new_ticket: [], new_note: ['new_note_namekey'] });+ assert.deepStrictEqual(lengthRequests(dv), [120, 180], 'and sends no length: a run that finds the tables leaves their name columns as they are');+});+// A column whose options cannot even be built (a spec the validator would have refused) must not turn into a different failure for// being near a change set: the options are built inside the attempt, the attempt is abandoned with its reason, and the column then// fails in its own step, as it always did.@@ -2308,11 +2560,12 @@ test('the primary column length step is planned exactly when the spec asks for a});// --- an alternate key over a new table's name column ------------------------------------------------------------------------------// The platform validates a key when it is created, and a key may hold at most 900 bytes (KEY_BYTES_LIMIT, 2 a character of text). The-// name column of a new table has the length the spec asks for only once the length step has run — last in the phase, because its read-// carries labels (see the order tests above) — and an environment that ignores the length asked of the create makes it 850 characters,-// 1,700 bytes: far too long for a key. So a key over the name column of a table whose length is still to be set waits for that step,-// and is not asked for when the step failed.+// The platform validates a key when it is created, and a key may hold at most 1,700 bytes (KEY_BYTES_LIMIT, 2 a character of text), which+// the 850 characters an environment may make of a new name column fill by themselves. The name column of a new table has the length the+// spec asks for only once the length step has run — last in the phase, because its read carries labels (see the order tests above). So+// a key over the name column of a table whose length is still to be set waits for that step when its label goes out in one language, and+// is not asked for when the step failed. A key labelled in several languages is made ahead of it, unless the environment made the column+// too long for the key to fit beside the others (see below).const NAME_KEY = { schemaName: 'new_namekey', displayName: 'Name Key', columns: ['new_name'] };// One table with a name column as given and the alternate keys given, beside a text column `new_code`.@@ -2410,7 +2663,9 @@ test('a name column key that waits is created once, with the options the inline});test('a table found after the answer to its create was lost keeps its keys where they were: nothing shows that this build made it, so its name column is not written for a key', async () => {- const run = await provisionOver(keyedTable([NAME_KEY]), { dataverse: { createCommitsThenFails: lostAnswer }, capture: true });+ // A key over the name column and another column: at the 850 characters the environment made the column it is too large, which is what the platform then says.+ const pair = { ...NAME_KEY, columns: ['new_name', 'new_code'] };+ const run = await provisionOver(keyedTable([pair]), { dataverse: { createCommitsThenFails: lostAnswer }, capture: true });assert.deepStrictEqual(puts(run), [], 'the column is left alone');assert.strictEqual(keyPosts(run).length, 1, 'and the key is asked for where it always was');assert.ok(run.error instanceof BuildHalt && run.error.code !== 'alt-key-name-length-not-set', 'where the platform refuses it, as it did before');@@ -2426,7 +2681,8 @@ test('a key that waits for a length that could not be set is not asked for: theassert.deepStrictEqual(keyPosts(run), [], 'no request was sent for the key, so the platform said nothing about it');assert.match(run.error.message, /^data-model failed: alt key new_ticket\.new_namekey was not created: .*\bnew_name\b.*\b120\b/);assert.match(run.error.message, /The attribute cannot be changed right now/, 'with what stopped the length from being set');- assert.match(run.error.message, /900 bytes/, 'and why a key needs it');+ assert.match(run.error.message, /1,700 bytes/, 'and why a key needs it: with the limit the platform names');+ assert.doesNotMatch(run.error.message, /900 bytes/, 'not the one Microsoft Learn documents');assert.match(run.error.message, /Maker/, 'and what to do');assert.deepStrictEqual(run.events.filter((e) => e.status === 'error').map((e) => e.label), ['primary column length new_ticket.new_name -> 120', 'alt key new_ticket.new_namekey'], 'both steps are narrated as failed, the length first');assert.strictEqual(run.warnings.length, 1, 'and the length is warned about once, as ever');@@ -2636,6 +2892,14 @@ test('a length step that fails on its own stops the build at the key that waitedassert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], ['new_namekey']);assert.deepStrictEqual(run.attempts.map((a) => (a.owedIn || []).length), [0, 1]);+ // The key fits once the length is set, which the build could not promise: the stop of the first attempt and the warning of its length step said a+ // run MAY create the key, on that condition — and here the run that follows does.+ const stop = run.events.find((e) => e.attempt === 1 && e.status === 'error' && e.label === 'alt key new_ticket.new_namekey');+ assert.match(stop.detail, /Nothing was sent for the key\. Set new_name to 120 characters in Maker, or clear the cause above; running the build again may then create the key: it does if new_name at 120 characters leaves room for it\. That is not certain: the build counts at least 240 bytes for the key at that length/);+ assert.doesNotMatch(stop.detail, /it creates the key|cannot fit once the length is set/);+ const warned = run.warnings.filter((w) => w.attempt === 1).map((w) => w.text);+ assert.strictEqual(warned.length, 1);+ assert.match(warned[0], /which is over that column and is not asked for while the column is that long\. Running the build again once new_name is 120 characters long may create it: it does if new_name at 120 characters leaves room for it\./);});// The engine's own requests — the read of the column's length, the read of which table answers to a name and the update that pays a carried length (readTextColumn,@@ -3336,12 +3600,29 @@ test('what is sent decides, not the language the build is authored in: a key whoassert.deepStrictEqual(finished(other).slice(-2), finished(base).slice(-2), 'and the same last two steps: the length, then the key');});-test('a key labelled in several languages keeps its place ahead of the length step, and where the platform then refuses it the build says why and what to do — and the run that follows makes it, with both labels', async () => {+// The build asks for such a key where it always did and finds out from the platform whether it fits: it cannot know the limit of an+// environment that enforces the 900 bytes Microsoft Learn documents (the stub's `keyBytesLimit`), where even the name column alone is too+// long at 850 characters.+//+// What it can know of a key's size is a floor (keyBytesAtLeast): it counts a column that is not text, or that the spec does not describe, at+// one byte. Where the floor at the length the spec asks is within the limit, the build cannot tell whether setting that length makes room for+// the key, so after the platform refuses the key its warning promises nothing: a run again may create the key, on that condition, and where it+// is refused the same way the platform's error and the sizes of the key's columns say why. A label in one language changes where a key is+// made, not its size, so it is not offered as a way out.+function assertConditionalAdvice(advice, { column, asked, floor }) {+ assert.match(advice, new RegExp(`running the build again may create the key: it does if ${column} at ${asked} characters leaves room for it\\. That is not certain: the build counts at least ${floor} bytes for the key at that length`), 'what a run again may do, on what condition, and how far the build can tell');+ assert.match(advice, /and the platform may count more, or allow less than the 1,700 bytes measured\./, 'and why it cannot tell');+ assert.match(advice, /If the next run is refused the same way, compare the platform's error with the sizes of the key's columns, and take a column out of the key or make its text columns shorter\.$/, 'and where to look then');+ assert.doesNotMatch(advice, /so the key is created then/, 'no promise');+ assert.doesNotMatch(advice, /cannot fit at that length either/, 'nor a proof the build does not have');+ assert.doesNotMatch(advice, /labelled in one language/, 'and no label in one language as a way out');+}+test('a key labelled in several languages that the build had no reason to think too large is made ahead of the length step, and where the platform then refuses it the build says why and what to do — and the run that follows makes it, with both labels', async () => {const labelled = MAP_KEY({ 1033: 'Name Key', 3082: 'Clave del nombre' });- const run = await provisionOver(keyedTable([labelled]), { capture: true });+ const run = await provisionOver(keyedTable([labelled]), { dataverse: { keyBytesLimit: 900 }, capture: true });assert.ok(run.error instanceof BuildHalt, 'the build stops where the platform refuses the key');assert.deepStrictEqual(run.events.filter((e) => e.status === 'error').map((e) => e.label), ['alt key new_ticket.new_namekey'], 'at the key');- assert.match(run.error.message, /1700 bytes/, 'with the platform\'s own words');+ assert.match(run.error.message, /Index size exceeded the size limit of 900 bytes/, 'with the platform\'s own words');assert.notStrictEqual(run.error.code, 'alt-key-name-length-not-set', 'this is the platform\'s refusal: the key was asked for');const lines = run.dv.log.map(requestLine);assert.ok(lines.findIndex((l) => /\/Keys$/.test(l)) < lines.findIndex((l) => l.startsWith('PUT ')), 'the key is asked for before the length step, as it always was');@@ -3351,9 +3632,10 @@ test('a key labelled in several languages keeps its place ahead of the length stassert.match(advice[0], /It is over the name column new_name of a table this build created/);assert.match(advice[0], /its label is in several languages \(1033, 3082\), so the build creates it before it sets that column/, 'says why this key was made first, from the languages the label goes out in');assert.doesNotMatch(advice[0], /more than the build's language/, 'and not in terms of the build\'s language: only what goes out matters');- assert.match(advice[0], /900 bytes/, 'and what the platform refused it for');- assert.match(advice[0], /run the build again/, 'and what to do');- assert.match(advice[0], /A key labelled in one language is created after the length is set/, 'and how to have it made first time');+ assert.match(advice[0], /at most 1,700 bytes, 2 for each character of text/, 'and what the platform refuses a key for, with the limit the platform names');+ assert.match(advice[0], /850 characters .* no other column/, 'and what that makes of a name column of 850 characters');+ assert.doesNotMatch(advice[0], /900 bytes/, 'not the limit Microsoft Learn documents and the platform does not name');+ assertConditionalAdvice(advice[0], { column: 'new_name', asked: 120, floor: '240' });const again = await provisionAgain(run.dv, keyedTable([labelled]));assert.strictEqual(again.error, null, 'the run that follows finds the table with the length set');assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], ['new_namekey']);@@ -3379,6 +3661,406 @@ test('a key labelled in several languages that the platform accepts, or refusesassert.deepStrictEqual(existing.warnings, [], 'is not one the build set the length of, so the advice does not apply');});+// --- a key over the name column and another column, labelled in several languages -----------------------------------------------------+// A key labelled in several languages is made ahead of the length step, because that step's read carries labels (see above). The platform+// takes a key of at most 1,700 bytes, 2 for each character of text, so the 850 characters an environment may make of a new name column fill+// it by themselves: a key over that column alone fits, and a key that holds any other column beside it does not — the platform refuses it+// (HTTP 400, 0x80060895), where the first build used to stop, for the run that followed to make the key. Such a key cannot be made ahead of+// the step that shortens the column, so it is the one key labelled in several languages that is made after it: decided from the length the+// environment made of the column, which is read — narrowly, no labels — before the key is asked for, and only where waiting can change the+// platform's answer. Measured live: a key made after the length step keeps both of its labels (the SDK's `updateColumn`, then its+// `createAlternateKey`).+const PAIR_LABELS = { 1033: 'Pair Key', 3082: 'Clave de pareja' };+const PAIR_KEY = { schemaName: 'new_pairkey', displayName: PAIR_LABELS, columns: ['new_name', 'new_code'] };+const PAIR_BOTH = [[1033, 'Pair Key'], [3082, 'Clave de pareja']];+const labelsOfSteps = (run) => finished(run).map(([, label]) => label);++test('a key over the name column and another column, labelled in several languages, is made after the length step where the environment made the name column 850 characters long: the first build succeeds, with both labels', async () => {+ const run = await provisionOver(keyedTable([PAIR_KEY]), { capture: true });+ assert.strictEqual(run.error, undefined, 'the first build succeeds');+ assert.deepStrictEqual(run.dv.refusals, [], 'the platform refused nothing: the key was not asked for while it could not fit');+ const table = run.dv.tables.get('new_ticket');+ assert.strictEqual(table.primaryLength, 120, 'the name column has the length the spec asks for');+ assert.deepStrictEqual([...table.keys.keys()], ['new_pairkey'], 'and the key exists after the first build');+ assert.strictEqual(keyPosts(run).length, 1, 'the key is asked for once');+ assert.deepStrictEqual(keyLabels(run), [PAIR_BOTH], 'with both of its labels');+ const lines = run.dv.log.map(requestLine);+ assert.ok(lines.findIndex((l) => l.startsWith('PUT ')) < lines.findIndex((l) => /\/Keys$/.test(l)), 'after the length is written');+ assert.deepStrictEqual(labelsOfSteps(run), [+ 'table new_ticket', 'column new_ticket.new_code (Text)', 'primary column length new_ticket.new_name -> 120', 'alt key new_ticket.new_pairkey',+ ], 'the key is the last step, after the length');+ assert.strictEqual(lengthReads(run).length, 2, 'the column is read once to decide where the key goes and once by the length step, both typed and narrow');+ assert.deepStrictEqual(run.warnings, []);+});++test('a key over the name column alone, labelled in several languages, keeps its place ahead of the length step where the environment made the column 850 characters long: that is exactly the 1,700 bytes a key may hold, and the platform takes it', async () => {+ const labelled = MAP_KEY({ 1033: 'Name Key', 3082: 'Clave del nombre' });+ const run = await provisionOver(keyedTable([labelled]), { capture: true });+ assert.strictEqual(run.error, undefined, 'the first build succeeds');+ assert.deepStrictEqual(run.dv.refusals, [], 'the platform took the key while the column was 850 characters long');+ assert.deepStrictEqual(labelsOfSteps(run), [+ 'table new_ticket', 'column new_ticket.new_code (Text)', 'alt key new_ticket.new_namekey', 'primary column length new_ticket.new_name -> 120',+ ], 'it is made with its table, ahead of the length step, as it always was');+ const lines = run.dv.log.map(requestLine);+ assert.ok(lines.findIndex((l) => /\/Keys$/.test(l)) < lines.findIndex((l) => l.startsWith('PUT ')), 'on the wire too');+ assert.strictEqual(lengthReads(run).length, 1, 'the column is read once, by the length step: nothing is read to decide where a key that holds the name column alone goes');+ assert.deepStrictEqual(keyLabels(run), [[[1033, 'Name Key'], [3082, 'Clave del nombre']]]);+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);+ assert.deepStrictEqual(run.warnings, []);+});++test('a table with several keys: only the key labelled in several languages that cannot fit moves to the end — every other key keeps the place it has', async () => {+ const keys = [+ { schemaName: 'new_codekey', displayName: PAIR_LABELS, columns: ['new_code'] },+ { ...MAP_KEY({ 1033: 'Name Key', 3082: 'Clave del nombre' }), schemaName: 'new_namelabelled' },+ NAME_KEY,+ PAIR_KEY,+ ];+ const run = await provisionOver(keyedTable(keys), { capture: true });+ assert.strictEqual(run.error, undefined, 'the first build succeeds');+ assert.deepStrictEqual(labelsOfSteps(run), [+ 'table new_ticket',+ 'column new_ticket.new_code (Text)',+ 'alt key new_ticket.new_codekey', // another column: with its table, whatever its label+ 'alt key new_ticket.new_namelabelled', // the name column alone, labelled in several languages: ahead of the length step, which fits+ 'primary column length new_ticket.new_name -> 120',+ 'alt key new_ticket.new_namekey', // the name column, labelled in one language: after the length step, as it always was+ 'alt key new_ticket.new_pairkey', // the name column and another, labelled in several languages: after it too, because it could not fit before+ ]);+ assert.deepStrictEqual(run.dv.refusals, []);+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], ['new_codekey', 'new_namelabelled', 'new_namekey', 'new_pairkey']);+ assert.deepStrictEqual(keyLabels(run).map((labels) => labels.length), [2, 2, 1, 2], 'each with the labels it was given');+ assert.deepStrictEqual(run.warnings, []);+});++test('where the environment keeps the length asked, a key over the name column and another column, labelled in several languages, is made where it always was: ahead of the length step, which is a skip', async () => {+ const run = await provisionOver(keyedTable([PAIR_KEY]), { dataverse: HONOURING, capture: true });+ assert.strictEqual(run.error, undefined);+ assert.deepStrictEqual(labelsOfSteps(run), [+ 'table new_ticket', 'column new_ticket.new_code (Text)', 'alt key new_ticket.new_pairkey', 'primary column length new_ticket.new_name (already 120)',+ ]);+ assert.deepStrictEqual(puts(run), [], 'nothing is written to the column');+ assert.deepStrictEqual(run.dv.refusals, []);+ assert.deepStrictEqual(keyLabels(run), [PAIR_BOTH]);+ assert.strictEqual(lengthReads(run).length, 2, 'one narrow read to decide, which shows the column is as long as the spec asks, and one by the length step');+ assert.deepStrictEqual(run.warnings, []);+});++test('the run after a first build that made such a key after the length step finds the table, the length and the key, and has nothing to do', async () => {+ const first = await provisionOver(keyedTable([PAIR_KEY]), { capture: true });+ assert.strictEqual(first.error, undefined);+ const again = await provisionAgain(first.dv, keyedTable([PAIR_KEY]));+ assert.strictEqual(again.error, null, 'the run after succeeds');+ assert.deepStrictEqual(again.events.filter((e) => e.status !== 'start').map((e) => [e.status, e.label]), [+ ['skip', 'table new_ticket (exists — reuse)'],+ ['skip', 'primary column length new_ticket.new_name (table exists — kept)'],+ ['skip', 'column new_ticket.new_code (exists)'],+ ['skip', 'alt key new_ticket.new_pairkey (exists)'],+ ], 'every step is a skip, the key\'s too: the platform answers that it exists');+ assert.deepStrictEqual(again.warnings, []);+ assert.strictEqual(puts(first).length, 1, 'the one write of the length is the first build\'s');+ assert.strictEqual(first.dv.tables.get('new_ticket').primaryLength, 120);+ assert.deepStrictEqual([...first.dv.tables.get('new_ticket').keys.keys()], ['new_pairkey'], 'and there is one key');+});++test('where the length the environment made cannot be read, such a key is made where it always was, and where the platform then refuses it the build says why with the platform\'s numbers — and the run that follows makes it, with both labels', async () => {+ const run = await provisionOver(keyedTable([PAIR_KEY]), { dataverse: { lengthRead: (n) => (n === 1 ? SERVICE_UNAVAILABLE : undefined) }, capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the build stops where the platform refuses the key, as it did before');+ assert.match(run.error.message, /Index size exceeded the size limit of 1700 bytes/, 'with the platform\'s own words');+ const lines = run.dv.log.map(requestLine);+ assert.ok(lines.findIndex((l) => /\/Keys$/.test(l)) < lines.findIndex((l) => l.startsWith('PUT ')), 'the key is asked for ahead of the length step');+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120, 'the length is set as the build stops');+ const advice = run.warnings.filter((w) => /alt key new_ticket\.new_pairkey/.test(w));+ assert.strictEqual(advice.length, 1, 'one warning names the key');+ assert.match(advice[0], /at most 1,700 bytes, 2 for each character of text/, 'with the limit the platform names');+ assert.match(advice[0], /850 characters .* no other column/, 'and what a name column of 850 characters leaves a key');+ assert.doesNotMatch(advice[0], /900 bytes/);+ // The build could not read the length, so it cannot tell whether setting it makes room: it says the run after MAY create the key, and here it does.+ assertConditionalAdvice(advice[0], { column: 'new_name', asked: 120, floor: '440' });+ const again = await provisionAgain(run.dv, keyedTable([PAIR_KEY]));+ assert.strictEqual(again.error, null, 'the run that follows finds the table with the length set');+ assert.deepStrictEqual(keyLabels({ dv: run.dv }).slice(-1), [PAIR_BOTH], 'and makes the key with both of its labels');+});++test('a key that would not fit at the length the spec asks either is not made later: waiting would change nothing, so it is asked for where it always was and nothing is read to decide', async () => {+ const wide = { ...textColumn('new_wide'), maxLength: 900 };+ const key = { schemaName: 'new_widekey', displayName: PAIR_LABELS, columns: ['new_name', 'new_wide'] };+ const run = await provisionOver(keyedTable([key], asksFor(120), [wide]), { capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the platform refuses it, as it did');+ assert.match(run.error.message, /Index size exceeded the size limit of 1700 bytes/);+ const lines = run.dv.log.map(requestLine);+ assert.ok(lines.findIndex((l) => /\/Keys$/.test(l)) < lines.findIndex((l) => l.startsWith('PUT ')), 'ahead of the length step');+ assert.strictEqual(lengthReads(run).length, 1, 'the length step reads the column; nothing else does');+});++test('a key that waits because it could not fit is not asked for when the length step failed: the build stops there and says why, with the platform\'s numbers', async () => {+ const run = await provisionOver(keyedTable([PAIR_KEY]), { dataverse: { updateFails: refusal }, capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the build stops');+ assert.strictEqual(run.error.code, 'alt-key-name-length-not-set');+ assert.deepStrictEqual(keyPosts(run), [], 'no request was sent for the key');+ assert.deepStrictEqual(run.dv.refusals.map((r) => r.message), ['The attribute cannot be changed right now'], 'the platform refused the length and nothing else');+ assert.match(run.error.message, /^data-model failed: alt key new_ticket\.new_pairkey was not created: .*\bnew_name\b.*\b120\b/);+ assert.match(run.error.message, /at most 1,700 bytes, 2 for each character of text/);+ assert.doesNotMatch(run.error.message, /900 bytes/);+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'error').map((e) => e.label), ['primary column length new_ticket.new_name -> 120', 'alt key new_ticket.new_pairkey']);+ assert.match(run.warnings[0], /the build stops at alt key new_ticket\.new_pairkey, which is over that column and is not asked for while the column is that long\. /);+ assert.doesNotMatch(run.warnings[0], /cannot be created while the column is that long/, 'no claim about a key the build did not ask for');+});++test('the retry that pays a length an attempt owed makes such a key after it, with both labels — and the attempt that never got as far as the key did not ask for it', async () => {+ const spec = retriedTicket({ key: false });+ spec.entities[0].alternateKeys = [{ ...PAIR_KEY, columns: ['new_name', 'new_title'] }];+ const run = await buildWithRetries(spec, { faults: { createFile: 1, setLength: 1 } });+ assert.strictEqual(run.result.ok, true, 'the build completed');+ assert.strictEqual(run.retries, 1);+ assert.deepStrictEqual(run.requests(1).filter((r) => /\/Keys$/.test(r.path)), [], 'the first attempt did not ask for the key');+ const retry = run.requests(2).map(requestLine);+ assert.strictEqual(retry.filter((l) => /\/Keys$/.test(l)).length, 1, 'the retry asked for it once');+ assert.ok(retry.findIndex((l) => l.startsWith('PUT ')) < retry.findIndex((l) => /\/Keys$/.test(l)), 'after the length');+ assert.deepStrictEqual(run.dv.refusals, [], 'and the platform refused nothing');+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], ['new_pairkey']);+ assert.deepStrictEqual(keyLabels({ dv: run.dv }), [PAIR_BOTH]);+ assert.deepStrictEqual(run.steps(2, /^(primary column length|alt key) /), [`ok primary column length new_ticket.new_name -> 120${OWED_NOTE}`, 'ok alt key new_ticket.new_pairkey']);+});++test('a spec with such a key narrates exactly the steps the plan has, so [n/total] holds, under both behaviours of the platform', async () => {+ const { planFor } = require('../lib/sdk-build.js');+ for (const [what, dataverse] of [['the platform makes the name column 850 characters long', {}], ['the platform keeps the length', HONOURING]]) {+ const spec = keyedTable([PAIR_KEY]);+ const run = await provisionOver(spec, { dataverse });+ const planned = planFor(spec, { phases: ['data-model'] });+ assert.strictEqual(run.events.filter((e) => e.status !== 'start').length, planned.length, `${what}: as many steps as the plan has`);+ assert.strictEqual(Math.max(...run.events.map((e) => e.n)), planned.length, `${what}: and n ends on the total`);+ }+});++test('where such a key is made: after the length step where the name column reads 850 characters, ahead of it where the environment kept the length, and with its table where the table already existed', async (t) => {+ const key = { schemaName: 'new_k', columns: ['new_x', 'new_n'], displayName: { 1033: 'Key', 3082: 'Clave' } };+ const reading = (maxLength) => (doubles) => {+ const get = doubles.provision.dataverse.get;+ doubles.provision.dataverse.get = async (url) => (/StringAttributeMetadata\?\$select=MaxLength$/.test(url) ? { status: 200, body: { MaxLength: maxLength } } : get(url));+ };+ for (const [what, arrange, existing, expected] of [+ ['a name column of 850 characters', () => {}, [], [...A_FIRST, ...THEN_B, SET_A_LENGTH, KEY_ON_A]],+ ['a name column that is already the length asked', reading(120), [], [...A_FIRST, KEY_ON_A, ...THEN_B]],+ ['a name column the environment made 300 characters long: the key fits beside it, so it is made ahead of the length step, where it always was', reading(300), [], [...A_FIRST, KEY_ON_A, ...THEN_B, SET_A_LENGTH]],+ ['a table that already existed: its name column is never written', () => {}, ['new_a'], ['createColumn new_a.new_x', KEY_ON_A, ...THEN_B]],+ ]) {+ await t.test(what, async () => {+ const doubles = orderDoubles({ existing });+ arrange(doubles);+ await runOrder(doubles, KEYED_PAIR(key));+ assert.deepStrictEqual(doubles.calls, expected);+ });+ }+});++// --- the size of a key is judged by the columns the build creates ---------------------------------------------------------------------+// Whether a key over the name column and another column is made after the length step comes from sums over the lengths the build creates the+// key's columns with: it cannot fit while the name column is as long as the environment made it, and can at the length the spec asks+// (keyHasRoomOnlyAfterLength, keyMustWaitForShorterNameColumn). The build sends a column's `maxLength` only for a column that names its type+// Text (maxLengthSent, the rule columnOptions follows), so an auto-number column, and a column that gives no type, are the 100 characters the SDK+// gives a text column whatever maxLength they carry. A key sized from the lengths the spec writes instead moved a key that fits and kept one that+// does not.+const REF_COLUMN = (extra = {}) => ({ schemaName: 'new_ref', displayName: 'Reference', type: 'AutoNumber', autoNumberFormat: 'R-{SEQNUM:4}', ...extra });+const UNTYPED_REF = (extra = {}) => ({ schemaName: 'new_ref', displayName: 'Reference', ...extra });+const REF_KEY = { schemaName: 'new_refkey', displayName: PAIR_LABELS, columns: ['new_name', 'new_ref'] };+// A column as it went on the wire, in the change set or in a request of its own, by schema name.+const wireColumn = (run, schemaName) => [...batchColumns(run), ...columnPosts(run).map((r) => r.body)].find((c) => c.SchemaName === schemaName);++test('an auto-number column, or a column that gives no type, is created 100 characters long whatever maxLength it carries, so a key over the name column and it is made after the length step where the name column is 850 characters long: the first build succeeds, with both labels', async () => {+ const { planFor } = require('../lib/sdk-build.js');+ for (const [what, column] of [['an auto-number column', REF_COLUMN({ maxLength: 900 })], ['a column that gives no type', UNTYPED_REF({ maxLength: 900 })]]) {+ const spec = keyedTable([REF_KEY], asksFor(120), [column]);+ const run = await provisionOver(spec, { capture: true });+ assert.strictEqual(run.error, undefined, `${what}: the first build succeeds`);+ assert.strictEqual(wireColumn(run, 'new_ref').MaxLength, 100, `${what}: the build sent no length for it, so the SDK made it 100 characters long`);+ assert.deepStrictEqual(run.dv.refusals, [], `${what}: the platform refused nothing: the key was not asked for while it could not fit`);+ assert.deepStrictEqual(labelsOfSteps(run), [+ 'table new_ticket', `column new_ticket.new_ref (${column.type || 'Text'})`, 'primary column length new_ticket.new_name -> 120', 'alt key new_ticket.new_refkey',+ ], `${what}: the key is the last step, after the length`);+ assert.deepStrictEqual(keyLabels(run), [PAIR_BOTH], `${what}: with both of its labels`);+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120, what);+ assert.strictEqual(run.events.filter((e) => e.status !== 'start').length, planFor(spec, { phases: ['data-model'] }).length, `${what}: as many steps as the plan has`);+ assert.deepStrictEqual(run.warnings, [], what);+ }+});++test('a key that really fits is not moved: beside a name column of 600 characters an auto-number column that carries a maxLength is 100 characters, 1,400 bytes in all — it is made ahead of the length step, where it always was, and a length that cannot be set does not stop the build at it', async () => {+ const spec = keyedTable([REF_KEY], asksFor(120), [REF_COLUMN({ maxLength: 500 })]);+ const run = await provisionOver(spec, { dataverse: { plainPrimaryLength: 600 }, capture: true });+ assert.strictEqual(run.error, undefined, 'the first build succeeds');+ assert.deepStrictEqual(run.dv.refusals, [], 'the platform took the key beside the column of 600 characters');+ assert.deepStrictEqual(labelsOfSteps(run), [+ 'table new_ticket', 'column new_ticket.new_ref (AutoNumber)', 'alt key new_ticket.new_refkey', 'primary column length new_ticket.new_name -> 120',+ ], 'with its table, ahead of the length step');+ const lines = run.dv.log.map(requestLine);+ assert.ok(lines.findIndex((l) => /\/Keys$/.test(l)) < lines.findIndex((l) => l.startsWith('PUT ')), 'on the wire too');+ assert.strictEqual(lengthReads(run).length, 2, 'one narrow read to decide, which shows the column fits, and one by the length step');+ assert.deepStrictEqual(keyLabels(run), [PAIR_BOTH]);+ assert.deepStrictEqual(run.warnings, []);+ // Nothing waits for the length, so one that cannot be set is a warning and the build goes on, as it did before the build read the column.+ const refused = await provisionOver(spec, { dataverse: { plainPrimaryLength: 600, updateFails: refusal }, capture: true });+ assert.strictEqual(refused.error, undefined, 'the build goes on');+ assert.deepStrictEqual([...refused.dv.tables.get('new_ticket').keys.keys()], ['new_refkey'], 'with the key made');+ assert.strictEqual(refused.warnings.length, 1, 'and one warning, for the length');+ assert.match(refused.warnings[0], /^could not set the length of the primary name column new_ticket\.new_name to 120 — .*and the rest of the build continues: asked 120, the platform made 600: /);+});++test('a Text column is created at the maxLength the spec writes, so it counts in full: a Text column of 700 characters beside the name column is 1,640 bytes at the length asked and 3,100 at 850, and the key is made after the length step', async () => {+ const key = { ...REF_KEY, schemaName: 'new_widekey', columns: ['new_name', 'new_wide'] };+ const run = await provisionOver(keyedTable([key], asksFor(120), [{ ...textColumn('new_wide'), maxLength: 700 }]), { capture: true });+ assert.strictEqual(run.error, undefined, 'the first build succeeds');+ assert.strictEqual(wireColumn(run, 'new_wide').MaxLength, 700, 'the build sent the length');+ assert.deepStrictEqual(run.dv.refusals, []);+ assert.deepStrictEqual(labelsOfSteps(run).slice(-2), ['primary column length new_ticket.new_name -> 120', 'alt key new_ticket.new_widekey']);+});++test('the floor of a key counts each column as the platform holds it once the build has created it — a single line of text at its MaxLength, a column of any other type at one byte — for every type the build creates, in the change set and one request each', async () => {+ const { keyBytesAtLeast } = require('../lib/app-spec.js');+ const { SDK_COLUMN_TYPE } = require('../lib/entity-provision.js');+ const columns = [+ ...ORDINARY,+ ...PER_COLUMN,+ { ...textColumn('new_t300'), maxLength: 300 },+ { ...textColumn('new_t0'), maxLength: 0 },+ REF_COLUMN({ schemaName: 'new_a_plain' }),+ REF_COLUMN({ schemaName: 'new_a900', maxLength: 900 }),+ UNTYPED_REF({ schemaName: 'new_u_plain' }),+ UNTYPED_REF({ schemaName: 'new_u900', maxLength: 900 }),+ { schemaName: 'new_m900', displayName: 'Long Notes', type: 'Memo', maxLength: 900 },+ { schemaName: 'new_n900', displayName: 'Number', type: 'Integer', maxLength: 900 },+ { schemaName: 'new_picture', displayName: 'Picture', type: 'Image' },+ ];+ assert.deepStrictEqual(Object.keys(SDK_COLUMN_TYPE).filter((type) => !columns.some((c) => (c.type || 'Text') === type)), [], 'a column of every type the build creates');+ for (const [how, inlineColumns] of [['in one change set', true], ['one request each', false]]) {+ const spec = keyedTable([], asksFor(120), columns);+ const run = await provisionOver(spec, { inlineColumns });+ assert.strictEqual(batchPosts(run).length > 0, inlineColumns, how);+ const table = run.dv.tables.get('new_ticket');+ for (const column of columns) {+ const made = table.columns.get(column.schemaName.toLowerCase());+ assert.ok(made, `${how}: ${column.schemaName} was created`);+ const text = /\.StringAttributeMetadata$/.test(made.body['@odata.type']);+ assert.strictEqual(+ keyBytesAtLeast(spec.entities[0], { schemaName: 'new_k', columns: [column.schemaName] }, 120),+ text ? 2 * made.body.MaxLength : 1,+ `${how}: ${column.schemaName} (${column.type || 'no type'}) is ${text ? `a single line of text ${made.body.MaxLength} characters long` : made.body['@odata.type']} on the platform`,+ );+ }+ }+});++// The size decides what the build says, too. A key that cannot fit even at the length the spec asks is not moved (waiting changes nothing), so it+// is made ahead of the length step, where the platform refuses it; the run after would be refused the same way, so the warning must not send the+// reader to run the build again, as it may for a key whose size the build cannot tell.+test('a key that cannot fit even at the length the spec asks is not promised to the run after: the warning says it cannot fit, with the bytes its columns take, and the run after is refused as the first build was', async () => {+ const key = { schemaName: 'new_widekey', displayName: PAIR_LABELS, columns: ['new_name', 'new_wide'] };+ const spec = keyedTable([key], asksFor(120), [{ ...textColumn('new_wide'), maxLength: 900 }]);+ const run = await provisionOver(spec, { capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the platform refuses the key');+ assert.match(run.error.message, /Index size exceeded the size limit of 1700 bytes/);+ const advice = run.warnings.filter((w) => /alt key new_ticket\.new_widekey/.test(w));+ assert.strictEqual(advice.length, 1, 'one warning names the key');+ assert.match(advice[0], /its label is in several languages \(1033, 3082\), so the build creates it before it sets that column to 120 characters/, 'why it was made first, as before');+ assert.match(advice[0], /with new_name at 120 characters the key's columns take at least 2,040 bytes, and a key may hold at most 1,700, 2 for each character of text/, 'what it holds at the length the spec asks, counted from the columns as the build creates them');+ assert.match(advice[0], /running the build again does not create it/);+ assert.match(advice[0], /Take a column out of the key, or make its text columns shorter\.$/, 'and what to change');+ assert.doesNotMatch(advice[0], /the length is set as the build stops, so the key is created then/, 'not the advice for a key the length step makes room for');+ assert.doesNotMatch(advice[0], /A key labelled in one language is created after the length is set/, 'nor the way out a one-language label gives, which makes no room either');+ // What the platform enforces agrees: the run after finds the table with the length set, asks for the key with it, and is refused the same way.+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120, 'the length is set as the build stops');+ const again = await provisionAgain(run.dv, spec);+ assert.ok(again.error instanceof BuildHalt, 'the run after stops at the key too');+ assert.match(again.error.message, /Index size exceeded the size limit of 1700 bytes/);+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], [], 'and there is no key');+});++// A key the build's count does NOT show too large can be too large all the same: the count is a floor, and it counts a column that is not text, or+// that the spec does not describe, at one byte. Beside a name column of 849 characters (1,698 bytes) one byte fits and anything more does not; the+// stub counts such a column at 8 bytes (SQL Server stores an integer in 4 and a datetime in 8), and any count over two bytes gives the same answer.+// The environment keeps the length asked, so the length step has nothing to set, and the run after asks for the same key at the same size.+for (const [what, key, columns, dataverse] of [+ ['an Integer column', { schemaName: 'new_countkey', displayName: PAIR_LABELS, columns: ['new_name', 'new_count'] }, [{ schemaName: 'new_count', displayName: 'Count', type: 'Integer' }], HONOURING],+ ['createdon, a column every table has that the spec does not describe', { schemaName: 'new_createdkey', displayName: PAIR_LABELS, columns: ['new_name', 'createdon'] }, [], { ...HONOURING, createdOnColumn: true }],+]) {+ test(`a key whose size the build cannot tell is not promised to the run after: over a name column asked and made 849 characters long and ${what}, the build counts 1,699 bytes, the platform refuses the key, and the run after is refused the same way`, async () => {+ const spec = keyedTable([key], asksFor(849), columns);+ const label = `alt key new_ticket.${key.schemaName}`;+ const run = await provisionOver(spec, { dataverse, capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the platform refuses the key');+ assert.match(run.error.message, /Index size exceeded the size limit of 1700 bytes/, 'for its size');+ assert.deepStrictEqual(labelsOfSteps(run).slice(-2), [label, 'primary column length new_ticket.new_name (already 849)'], 'made ahead of the length step, which has nothing to set');+ const advice = run.warnings.filter((w) => w.startsWith(`${label} was not created.`));+ assert.strictEqual(advice.length, 1, 'one warning names the key');+ assertConditionalAdvice(advice[0], { column: 'new_name', asked: 849, floor: '1,699' });+ const again = await provisionAgain(run.dv, spec);+ assert.ok(again.error instanceof BuildHalt, 'the run after stops at the key too: nothing it does changes the key\'s size');+ assert.match(again.error.message, /Index size exceeded the size limit of 1700 bytes/);+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], [], 'and there is no key');+ });+}++// --- the stop for a key that waited for a length that could not be set ------------------------------------------------------------+// When the length step fails, a key that waits for it is not asked for: the build stops at it (createWaitingKeys, `alt-key-name-length-not-set`),+// and the warning of the step names it (alignPrimaryNameLength). Both say what the build can tell of the key at the length the spec asks, in the+// words of the warning above, from the same floor: a key proven too large there is promised to no run, and one whose size the build cannot tell is+// promised nothing either way — setting the length MAY make room. What "no run" and "may" are worth is shown against the platform: the length is+// then set as a maker sets it in Maker, and the run that follows asks for the key.+const setInMaker = (dv, length) => { dv.tables.get('new_ticket').primaryLength = length; };++test('a key that waits for a length step that fails, and is proven too large at the length the spec asks, is promised to no run: the stop and the warning give its size and what to change — and once the length is set, the platform refuses it', async () => {+ // Labelled in one language, so it waits for the length step whatever its size (keyWaitsForNameLength); beside the name column at the 120 characters+ // the spec asks, a Text column of 900 makes it 2,040 bytes at least.+ const key = { schemaName: 'new_widekey', displayName: 'Wide Key', columns: ['new_name', 'new_wide'] };+ const spec = keyedTable([key], asksFor(120), [{ ...textColumn('new_wide'), maxLength: 900 }]);+ const run = await provisionOver(spec, { dataverse: { updateFails: refusal }, capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the build stops at the key, as it did');+ assert.strictEqual(run.error.code, 'alt-key-name-length-not-set');+ assert.strictEqual(run.error.recoverable, true);+ assert.deepStrictEqual(keyPosts(run), [], 'and sends nothing for it');+ const proven = 'It cannot fit once the length is set either: with new_name at 120 characters the key\'s columns take at least 2,040 bytes, and a key may hold at most 1,700, 2 for each character of text — so no run creates it as the spec has it. Take a column out of the key, or make its text columns shorter.';+ assert.ok(run.error.message.endsWith(`Nothing was sent for the key. ${proven}`), `the stop says it cannot fit, with its size, and what to change: ${run.error.message}`);+ assert.doesNotMatch(run.error.message, /it creates the key|may then create|in Maker/, 'and promises nothing, nor sends the reader to set a length that makes no room');+ assert.strictEqual(run.warnings.length, 1, 'the length step warns once');+ assert.ok(run.warnings[0].startsWith('could not set the length of the primary name column new_ticket.new_name to 120 — it keeps the length the platform gave it, and the build stops at alt key new_ticket.new_widekey, which is over that column and is not asked for while the column is that long. '+ + `${proven} Why the length could not be set: asked 120, the platform made 850: `), `the warning says the same of the key: ${run.warnings[0]}`);+ assert.doesNotMatch(run.warnings[0], /cannot be created while the column is that long/, 'and no claim about the key at the length the column was left at');+ // What the platform enforces agrees: with the length set as the spec asks, the run that follows asks for the key, and it is refused.+ setInMaker(run.dv, 120);+ const again = await provisionAgain(run.dv, spec);+ assert.ok(again.error instanceof BuildHalt, 'no run creates it');+ assert.match(again.error.message, /Index size exceeded the size limit of 1700 bytes/);+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], []);+});++test('a key moved after the length step because it could not fit, whose size the build cannot tell, is promised nothing when that step fails: the stop and the warning say setting the length may make room — and here, once the length is set, the platform still refuses it', async () => {+ // Labelled in several languages, over the name column and an Integer column: at least 1,701 bytes beside the 850 characters the environment made of+ // the column, so the build moves it after the length step; 1,699 at the 849 the spec asks, which the platform still refuses (the stub counts an+ // Integer at 8 bytes; any count over two bytes is too many).+ const key = { schemaName: 'new_countkey', displayName: PAIR_LABELS, columns: ['new_name', 'new_count'] };+ const spec = keyedTable([key], asksFor(849), [{ schemaName: 'new_count', displayName: 'Count', type: 'Integer' }]);+ const run = await provisionOver(spec, { dataverse: { updateFails: refusal }, capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the build stops at the key, as it did');+ assert.strictEqual(run.error.code, 'alt-key-name-length-not-set');+ assert.deepStrictEqual(keyPosts(run), [], 'and sends nothing for it');+ assert.strictEqual(lengthReads(run).length, 2, 'the narrow read that moved the key, and the length step\'s: nothing more');+ const inconclusive = 'running the build again may then create the key: it does if new_name at 849 characters leaves room for it. That is not certain: the build counts at least 1,699 bytes for the key at that length — one byte for a column that is not text, or that the spec does not describe — and the platform may count more, or allow less than the 1,700 bytes measured. If the next run is refused the same way, compare the platform\'s error with the sizes of the key\'s columns, and take a column out of the key or make its text columns shorter.';+ assert.ok(run.error.message.endsWith(`Nothing was sent for the key. Set new_name to 849 characters in Maker, or clear the cause above; ${inconclusive}`), `the stop: ${run.error.message}`);+ assert.doesNotMatch(run.error.message, /it creates the key|cannot fit once the length is set/, 'neither a promise nor a proof');+ assert.strictEqual(run.warnings.length, 1, 'the length step warns once');+ assert.match(run.warnings[0], /the build stops at alt key new_ticket\.new_countkey, which is over that column and is not asked for while the column is that long\. Running the build again once new_name is 849 characters long may create it: it does if new_name at 849 characters leaves room for it\. That is not certain: the build counts at least 1,699 bytes/, 'the warning says the same');+ assert.doesNotMatch(run.warnings[0], /cannot be created while the column is that long/);+ // What the platform enforces: with the length set as the spec asks, the run that follows asks for the key, and it is refused — "may" was all the+ // build could say.+ setInMaker(run.dv, 849);+ const again = await provisionAgain(run.dv, spec);+ assert.ok(again.error instanceof BuildHalt);+ assert.match(again.error.message, /Index size exceeded the size limit of 1700 bytes/);+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], []);+});+// --- the dry run and the apply agree on where a key goes ------------------------------------------------------------------------// The plan lists the steps in the order the apply takes them. Where a key over the name column goes depends only on what the key is// sent as, so the plan cannot disagree with the apply about it — whichever language the spec, the command line and the label name. This@@ -3441,7 +4123,7 @@ test('a length that could not be set: the warning promises the build goes on wheconst waiting = await provisionOver(keyedTable([NAME_KEY]), { dataverse: { updateFails: refuse }, capture: true });assert.strictEqual(waiting.error.code, 'alt-key-name-length-not-set', 'the build stops at the key');assert.strictEqual(waiting.warnings.length, 1);- assert.match(waiting.warnings[0], /^could not set the length of the primary name column new_ticket\.new_name to 120 — it keeps the length the platform gave it, and the build stops at alt key new_ticket\.new_namekey, which is over that column and cannot be created while the column is that long: asked 120, the platform made 850: .*invalid length/);+ assert.match(waiting.warnings[0], /^could not set the length of the primary name column new_ticket\.new_name to 120 — it keeps the length the platform gave it, and the build stops at alt key new_ticket\.new_namekey, which is over that column and is not asked for while the column is that long\. Running the build again once new_name is 120 characters long may create it: .* Why the length could not be set: asked 120, the platform made 850: .*invalid length/);assert.doesNotMatch(waiting.warnings[0], /rest of the build continues/, 'it does not promise what the build is about to refuse');const two = await provisionOver(keyedTable([NAME_KEY, { schemaName: 'new_pairkey', columns: ['new_code', 'new_name'] }]), { dataverse: { updateFails: refuse }, capture: true });assert.match(two.warnings[0], /the build stops at alt keys new_ticket\.new_namekey, new_ticket\.new_pairkey, which are over that column/, 'every key that waits is named');@@ -3453,7 +4135,8 @@ test('where the phase stops before the length step and a key that waits was notawait assert.rejects(runOrder(doubles, KEYED_PAIR({ schemaName: 'new_k', columns: ['new_n'] }), events), /createRelationship new_a_b/);const warned = events.filter((e) => e.warning).map((e) => e.warning);assert.strictEqual(warned.length, 1);- assert.match(warned[0], /^could not set the length of the primary name column new_a\.new_n to 120 — it keeps the length the platform gave it, and because the data-model phase stopped, and a run that finds the table already there leaves its name column as it is, change the length in Maker if it matters — it does for alt key new_a\.new_k, which is over that column and is refused while the column is that long: /);+ assert.match(warned[0], /^could not set the length of the primary name column new_a\.new_n to 120 — it keeps the length the platform gave it, and because the data-model phase stopped, and a run that finds the table already there leaves its name column as it is, change the length in Maker if it matters — alt key new_a\.new_k is over that column\. Running the build again once new_n is 120 characters long may create it: it does if new_n at 120 characters leaves room for it\. That is not certain: .* Why the length could not be set: /);+ assert.doesNotMatch(warned[0], /refused while the column is that long|it creates the key/, 'no claim about the key at the length the column was left at, and no promise');assert.doesNotMatch(warned[0], /rest of the build continues/);assert.ok(!doubles.calls.includes('createAlternateKey new_a.new_k'), 'the key was not made');});diff --git a/plugins/model-apps/scripts/tests/teardown-model-app.test.js b/plugins/model-apps/scripts/tests/teardown-model-app.test.jsindex bf826dd53..97a4c3393 100644--- a/plugins/model-apps/scripts/tests/teardown-model-app.test.js+++ b/plugins/model-apps/scripts/tests/teardown-model-app.test.js@@ -282,6 +282,8 @@ function loadTeardownCli({// in for it with the very call the script made before it existed, so what this test pins — where the workspace is, and that it is removed — is as it was.if (id === './lib/temp-workspace.js') return { makeTempWorkspace: (prefix) => fakeFs.mkdtempSync(path.join('D:\\Projects\\power-platform-skills-sdk\\.test-workspace', prefix)) };if (id === 'node:os') return { tmpdir: () => 'D:\\Projects\\power-platform-skills-sdk\\.test-workspace' };+ // The real module: the script makes this sandbox's stand-in streams blocking before a last write, and a stand-in has no handle to change.+ if (id === './lib/output-redaction.js') return require('../lib/output-redaction.js');if (id === './lib/app-spec.js') {return {validateAppSpec: () => validation,diff --git a/plugins/model-apps/scripts/tests/teardown-row-summary-lookup.test.js b/plugins/model-apps/scripts/tests/teardown-row-summary-removal.test.jssimilarity index 55%rename from plugins/model-apps/scripts/tests/teardown-row-summary-lookup.test.jsrename to plugins/model-apps/scripts/tests/teardown-row-summary-removal.test.jsindex 4c053fb81..929e918e6 100644--- a/plugins/model-apps/scripts/tests/teardown-row-summary-lookup.test.js+++ b/plugins/model-apps/scripts/tests/teardown-row-summary-removal.test.js@@ -1,8 +1,9 @@'use strict';-// Teardown's row-summary step says what it found. The SDK's `removeRowSummary` answers nothing whether it removed a row summary or found none to remove, and the step took-// "the call did not throw" for "one was deleted": a table with no row summary was reported `✓ row summary <table> (1 deleted)`, in the line and in the closing count. The step now-// looks first — with the request the SDK itself makes — and reports what that read found, like every other step. The step stays best-effort, as it always was (a failure of-// the lookup or of the removal fails nothing), but what it could not do is said on its line instead of being counted as a deletion.+// Teardown's row-summary step says what the SDK found. `removeRowSummary` looks the table's skill row up itself and answers `{ removed: true }` when the table had a row summary and it is+// gone, and `{ removed: false }` — deleting nothing — when it had none (cds-maker-sdk 9a0c9f03). The SDK used to answer nothing in both cases, so the step took "the call did not throw" for "one+// was deleted" and a table with no row summary was reported `✓ row summary <table> (1 deleted)`; 2.16.0 looked for the skill row first, with a read of its own, to tell them apart. The step now+// reads nothing of its own: what the removal answers is what its line says, like every other step. It stays best-effort, as it always was (a failure of the lookup or of the removal fails nothing),+// but what it could not do is said on its line instead of being counted as a deletion.const { test } = require('node:test');const assert = require('node:assert');const fs = require('node:fs');@@ -26,24 +27,25 @@ const SPEC = {ai: { summaries: { default: 'auto' } },};const SKILL_ROW = { aiskillconfigid: '11111111-1111-1111-1111-111111111111' };-const LOOKUP = "/aiskillconfigs?$select=aiskillconfigid&$filter=uniquename eq 'ais_RowSummary_new_memo'&$top=1";+const LOOKUP_URL = `${ENV}/api/data/v9.0/aiskillconfigs?$select=aiskillconfigid,_aimodel_value&$filter=uniquename eq 'ais_RowSummary_new_memo'&$top=1`;-// An SDK double whose Dataverse holds `rows` as the skill rows the lookup finds, and which records every call. `lookup` and `remove` replace the answer of the read and the-// removal (to answer another status, or to throw). `solution: false` is an environment without the spec's solution, so that nothing else of the plan is deleted either.-function summarySdk({ rows = [], lookup, remove, solution = true } = {}) {+// An SDK double whose `removeRowSummary` answers `answer` (`{ removed: true }` unless told otherwise, and nothing at all for `answer: undefined`) and records every call. `remove` replaces the+// answer with a failure to throw. A read through `sdk.dataverse` fails the test: the step makes none. `solution: false` is an environment without the spec's solution, so that nothing else of the+// plan is deleted either.+function summarySdk(options = {}) {+ const { remove, solution = true } = options;+ const answer = 'answer' in options ? options.answer : { removed: true };const calls = [];const sdk = {resolveArtifact: async (kind) => (kind === 'solution' && solution ? [{ id: 'sol-1', name: 'AiTest' }] : []),queryRecords: async () => [],dataverse: {- get: async (url) => {- calls.push({ method: 'get', path: url });- return lookup ? lookup() : { status: 200, body: { value: rows } };- },+ get: async (url) => { throw new Error(`the row-summary step must read nothing of its own, and read ${url}`); },},removeRowSummary: async (args) => {calls.push({ method: 'removeRowSummary', ...args });if (remove) throw remove();+ return answer;},deleteTable: async () => { throw Object.assign(new Error('Could not find an entity with specified id'), { statusCode: 404 }); },deleteSolution: async () => {},@@ -51,6 +53,9 @@ function summarySdk({ rows = [], lookup, remove, solution = true } = {}) {return { sdk, calls, removals: () => calls.filter((c) => c.method === 'removeRowSummary') };}+// What the SDK throws when a request of its own is refused: a ConnectionError carrying the url and the status (cds-maker-sdk `ConnectionError`).+const refusal = (status, words, url = LOOKUP_URL) => Object.assign(new Error(`HTTP ${status} from ${url}: ${words}`), { code: 'CONNECTION_ERROR', statusCode: status, url });+const stepEvents = (events) => events.filter((e) => e.phase === 'ai-summaries' && e.status !== 'start');async function run(sdk, spec = SPEC) {const events = [];@@ -58,18 +63,18 @@ async function run(sdk, spec = SPEC) {return { result, events: stepEvents(events) };}-test('a table with no row summary is reported as not found, and nothing is sent to remove one', async () => {- const { sdk, removals } = summarySdk({ rows: [] });+test('a table with no row summary is reported as not found: the SDK deleted nothing, and nothing deleted is counted', async () => {+ const { sdk, removals } = summarySdk({ answer: { removed: false } });const { result, events } = await run(sdk);assert.strictEqual(result.ok, true, JSON.stringify(result.errors));assert.deepStrictEqual(events.map((e) => [e.status, e.skip, e.label]), [['skip', 'not-found', 'row summary new_memo (not found)']]);- assert.deepStrictEqual(removals(), [], 'there is nothing to remove');+ assert.strictEqual(removals().length, 1, 'the SDK is asked once, and it looks for the row summary itself');assert.strictEqual(result.deleted.aiSummary, undefined, 'and nothing deleted is counted');assert.ok(result.skipped.includes('row summary new_memo'));});test('a row summary the environment holds is removed once, and reported as deleted', async () => {- const { sdk, removals } = summarySdk({ rows: [SKILL_ROW] });+ const { sdk, removals } = summarySdk({ answer: { removed: true } });const { result, events } = await run(sdk);assert.strictEqual(result.ok, true, JSON.stringify(result.errors));assert.deepStrictEqual(events.map((e) => [e.status, e.label]), [['ok', 'row summary new_memo (1 deleted)']]);@@ -77,39 +82,54 @@ test('a row summary the environment holds is removed once, and reported as deletassert.deepStrictEqual(result.deleted.aiSummary, ['new_memo']);});-test('the step looks for the skill row by the SDK\u2019s own request, before it removes anything', async () => {- const { sdk, calls } = summarySdk({ rows: [SKILL_ROW] });- await run(sdk);- assert.deepStrictEqual(calls.filter((c) => c.method === 'get').map((c) => c.path), [LOOKUP]);- assert.ok(calls.findIndex((c) => c.method === 'get') < calls.findIndex((c) => c.method === 'removeRowSummary'));+test('the step makes no request of its own: the SDK\u2019s removal is the only call it makes for a table', async () => {+ // The double fails the test on any read through `sdk.dataverse`; the plan's other steps read through `resolveArtifact`/`queryRecords`, which this spec's steps do not use for a row summary.+ for (const answer of [{ removed: true }, { removed: false }]) {+ const { sdk, calls } = summarySdk({ answer });+ const { result } = await run(sdk);+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));+ assert.deepStrictEqual(calls.map((c) => c.method), ['removeRowSummary'], JSON.stringify(answer));+ }+});++test('only an explicit { removed: false } says that nothing was there: an answer that says nothing is counted as it always was', async () => {+ // A double (or an SDK) that answers nothing cannot say that no row summary was found, so the removal that did not throw is a deletion, as it was before the lookup existed.+ for (const answer of [undefined, null, {}, { removed: undefined }]) {+ const { sdk } = summarySdk({ answer });+ const { result, events } = await run(sdk);+ assert.strictEqual(result.ok, true, JSON.stringify(result.errors));+ assert.deepStrictEqual(events.map((e) => [e.status, e.label]), [['ok', 'row summary new_memo (1 deleted)']], JSON.stringify(answer));+ }});-test('an environment that has no AI skill table holds no row summary: not found, not a failure', async () => {- const { sdk, removals } = summarySdk({ lookup: () => ({ status: 404, body: { error: { message: "Resource not found for the segment 'aiskillconfigs'." } } }) });+test('an environment that has no AI skill table holds no row summary: the SDK\u2019s lookup answers 404, and the step says not found, not failed', async () => {+ const { sdk, removals } = summarySdk({ remove: () => refusal(404, "Resource not found for the segment 'aiskillconfigs'.") });const { result, events } = await run(sdk);assert.strictEqual(result.ok, true, JSON.stringify(result.errors));assert.deepStrictEqual(events.map((e) => [e.status, e.skip, e.label]), [['skip', 'not-found', 'row summary new_memo (not found)']]);- assert.deepStrictEqual(removals(), []);+ assert.strictEqual(removals().length, 1);+ assert.strictEqual(result.deleted.aiSummary, undefined);});-test('a lookup that cannot be made leaves what is there unknown: said on the step, nothing removed, nothing failed', async () => {- for (const [what, lookup, reason] of [- ['a refusal', () => ({ status: 403, body: { error: { message: 'no read privilege' } } }), /^row summary new_memo \(not looked up \u2014 the lookup answered HTTP 403; a row summary left behind is reported by the table's delete\)$/],- ['an answer that is no list', () => ({ status: 200, body: { value: 'busy' } }), /^row summary new_memo \(not looked up \u2014 the lookup's answer was no list; a row summary left behind is reported by the table's delete\)$/],- ['a request that failed', () => { throw new Error('socket hang up'); }, /^row summary new_memo \(not looked up \u2014 socket hang up; a row summary left behind is reported by the table's delete\)$/],+test('a lookup or a removal that fails leaves what is there unknown: said on the step in the SDK\u2019s words, nothing counted as deleted, nothing failed', async () => {+ for (const [what, failure, words] of [+ ['a refusal of the lookup', () => refusal(403, 'no read privilege'), `HTTP 403 from ${LOOKUP_URL}: no read privilege`],+ ['an answer that is no list', () => Object.assign(refusal(200, "the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got a string"), { statusCode: 200 }), `HTTP 200 from ${LOOKUP_URL}: the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got a string`],+ ['a first row that is no row', () => refusal(200, 'the row-summary skill lookup returned a malformed row \u2014 expected an object but got null'), `HTTP 200 from ${LOOKUP_URL}: the row-summary skill lookup returned a malformed row \u2014 expected an object but got null`],+ ['a request that failed', () => new Error('socket hang up'), 'socket hang up'],]) {- const { sdk, removals } = summarySdk({ lookup });+ const { sdk, removals } = summarySdk({ remove: failure });const { result, events } = await run(sdk);assert.strictEqual(result.ok, true, `${what}: the step is best-effort, as it was: ${JSON.stringify(result.errors)}`);- assert.deepStrictEqual(events.map((e) => [e.status, e.skip]), [['skip', 'kept']], what);- assert.match(events[0].label, reason, what);- assert.deepStrictEqual(removals(), [], `${what}: the SDK\u2019s own removal would have made the same request`);+ assert.deepStrictEqual(events.map((e) => [e.status, e.skip, e.label]), [['skip', 'kept', `row summary new_memo (kept \u2014 1 not removed: ${words})`]], what);+ assert.strictEqual(removals().length, 1, what);+ assert.strictEqual(result.deleted.aiSummary.length, 0, what);}});test('a removal that fails is not a deletion: said on the step in the SDK\u2019s words, kept like a step that left its artifact, and it still fails nothing', async () => {const words = "The row summary of 'new_memo' was removed, but its AI model '22222222-2222-2222-2222-222222222222' was not deleted (HTTP 400: refused).";- const { sdk, removals } = summarySdk({ rows: [SKILL_ROW], remove: () => Object.assign(new Error(words), { code: 'ROW_SUMMARY_MODEL_NOT_DELETED' }) });+ const { sdk, removals } = summarySdk({ remove: () => Object.assign(new Error(words), { code: 'ROW_SUMMARY_MODEL_NOT_DELETED' }) });const { result, events } = await run(sdk);assert.strictEqual(result.ok, true, 'best-effort: the table\u2019s delete that follows reports what still depends on the row summary');assert.deepStrictEqual(events.map((e) => [e.status, e.skip, e.label]), [['skip', 'kept', `row summary new_memo (kept \u2014 1 not removed: ${words})`]]);@@ -126,7 +146,7 @@ const CLOSING_WHEN_NOTHING_WAS_DELETED = /\u2014 0 deleted, 5 not found, 0 failetest('a removal that wholly fails is not in the closing count of deleted steps: it is kept, with the table that is kept', async () => {const words = 'HTTP 403 from https://contoso.crm.dynamics.com/api/data/v9.0/aiskillconfigs(11111111-1111-1111-1111-111111111111): no delete privilege';const logs = [];- const { sdk } = summarySdk({ rows: [SKILL_ROW], solution: false, remove: () => new Error(words) });+ const { sdk } = summarySdk({ solution: false, remove: () => new Error(words) });const result = await teardownModelApp(RETAINED, { apply: true, allowDestructive: true }, { sdk, log: (m) => logs.push(m) });assert.strictEqual(result.ok, true, JSON.stringify(result.errors));assert.deepStrictEqual(result.deleted.aiSummary, [], 'the JSON result deletes nothing');@@ -136,7 +156,7 @@ test('a removal that wholly fails is not in the closing count of deleted steps:test('a removal that succeeds is still counted as the deletion it is, beside the table that is kept', async () => {const logs = [];- const { sdk } = summarySdk({ rows: [SKILL_ROW], solution: false });+ const { sdk } = summarySdk({ solution: false });await teardownModelApp(RETAINED, { apply: true, allowDestructive: true }, { sdk, log: (m) => logs.push(m) });assert.match(logs.find((l) => /teardown complete/.test(l)), /\u2014 1 deleted, 5 not found, 0 failed, 1 kept \(7 steps\)$/, logs.join('\n'));});@@ -151,8 +171,8 @@ test('the printed step and the closing counts follow what was found', async () =assert.ok(closing, logs.join('\n'));return { logs, deleted: Number(closing[1]), notFound: Number(closing[2]), steps: Number(closing[3]) };};- const none = await tally({ rows: [] });- const one = await tally({ rows: [SKILL_ROW] });+ const none = await tally({ answer: { removed: false } });+ const one = await tally({ answer: { removed: true } });assert.ok(none.logs.some((l) => /^ {2}\[\d+\/\d+\] \u2298 row summary new_memo \(not found\)$/.test(l)), none.logs.join('\n'));assert.ok(!none.logs.some((l) => /row summary new_memo \(1 deleted\)/.test(l)));assert.ok(one.logs.some((l) => /^ {2}\[\d+\/\d+\] \u2713 row summary new_memo \(1 deleted\)$/.test(l)), one.logs.join('\n'));@@ -164,9 +184,8 @@ test('the printed step and the closing counts follow what was found', async () =// --- the real SDK -----------------------------------------------------------------------------------------------------------------------------------------------// `removeRowSummary` finds the row summary by its skill row — `GET /aiskillconfigs?…$filter=uniquename eq 'ais_RowSummary_<table>'` — and the step must look for the same row, or a-// row summary the SDK would remove is reported as not there and left to block the table's delete. The unique name is a constant inside the bundle, so the one the step uses is held to what-// the real bundle asks for, over a fake Dataverse that answers by the filter.+// The real bundle over a fake Dataverse that answers by the filter: `removeRowSummary` looks the row summary up by its skill row — `GET /aiskillconfigs?…$filter=uniquename eq 'ais_RowSummary_<table>'` — and+// what the step reports is what that call answers, so these hold the step to the requests the bundle really makes and to the words it really answers in.function fakeSkillOrg({ rows = [], status = 200, deleteStatus = 204 } = {}) {const requests = [];const json = (statusCode, body) => ({ statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });@@ -195,20 +214,37 @@ async function realSdk(org) {}const skillFilters = (requests) => requests.map((r) => /\/aiskillconfigs\?.*\$filter=([^&]+)/.exec(r.path)).filter(Boolean).map((m) => m[1]);-test('REAL BUNDLE: the step\u2019s lookup asks for the unique name the bundle\u2019s own removal asks for', async () => {- const bundleOrg = fakeSkillOrg();- await (await realSdk(bundleOrg)).removeRowSummary({ entityLogicalName: 'new_memo' });- const stepOrg = fakeSkillOrg();- assert.deepStrictEqual(await KIND_HANDLERS.aiSummary.resolve(await realSdk(stepOrg), { entityLogicalName: 'new_memo' }), []);- assert.deepStrictEqual(skillFilters(bundleOrg.requests), ["uniquename eq 'ais_RowSummary_new_memo'"]);- assert.deepStrictEqual(skillFilters(stepOrg.requests), skillFilters(bundleOrg.requests));- assert.strictEqual(stepOrg.requests.length, 1, 'one read, and nothing else is asked');+const withoutPage = { entities: SPEC.entities, ai: SPEC.ai };+const deleteRequests = (requests) => requests.filter((r) => r.method === 'DELETE').map((r) => r.path.replace(/^\/api\/data\/v9\.\d\//, ''));++test('REAL BUNDLE: the removal of a table with no skill row answers { removed: false }, and the step reports not found after the SDK\u2019s one lookup, sending nothing', async () => {+ const direct = fakeSkillOrg({ rows: [] });+ assert.deepStrictEqual(await KIND_HANDLERS.aiSummary.del(await realSdk(direct), { id: 'new_memo', entityLogicalName: 'new_memo' }), { removed: false });+ const org = fakeSkillOrg({ rows: [] });+ const { result, events } = await run(await realSdk(org), withoutPage);+ assert.deepStrictEqual(events.map((e) => [e.status, e.label]), [['skip', 'row summary new_memo (not found)']], JSON.stringify(result.errors));+ assert.deepStrictEqual(skillFilters(org.requests), ["uniquename eq 'ais_RowSummary_new_memo'"], 'one lookup, by the unique name the build gave the row summary: the SDK\u2019s own');+ assert.deepStrictEqual(deleteRequests(org.requests).filter((p) => /aiskillconfigs|msdyn_aimodels/.test(p)), [], 'and no row summary was deleted (the table\u2019s own delete, which the plan makes next, is not this step\u2019s)');+ assert.strictEqual(result.deleted.aiSummary, undefined);});-test('REAL BUNDLE: a skill row the environment holds is found, and one it does not hold is not', async () => {- const found = await KIND_HANDLERS.aiSummary.resolve(await realSdk(fakeSkillOrg({ rows: [SKILL_ROW] })), { entityLogicalName: 'new_memo' });- assert.deepStrictEqual(found, [{ id: 'new_memo', entityLogicalName: 'new_memo' }]);- assert.deepStrictEqual(await KIND_HANDLERS.aiSummary.resolve(await realSdk(fakeSkillOrg({ rows: [] })), { entityLogicalName: 'new_memo' }), []);+test('REAL BUNDLE: a skill row the environment holds is removed by the SDK, which is the one that looks for it: one lookup, one delete, reported as deleted', async () => {+ const org = fakeSkillOrg({ rows: [SKILL_ROW] });+ const { result, events } = await run(await realSdk(org), withoutPage);+ assert.deepStrictEqual(events.map((e) => [e.status, e.label]), [['ok', 'row summary new_memo (1 deleted)']], JSON.stringify(result.errors));+ assert.deepStrictEqual(skillFilters(org.requests), ["uniquename eq 'ais_RowSummary_new_memo'"], 'the step makes no lookup of its own');+ assert.deepStrictEqual(deleteRequests(org.requests).filter((p) => /aiskillconfigs|msdyn_aimodels/.test(p)), ['aiskillconfigs(11111111-1111-1111-1111-111111111111)'], 'one delete, of the skill row (the table\u2019s own, which the plan makes next, is not this step\u2019s)');+ assert.deepStrictEqual(result.deleted.aiSummary, ['new_memo']);+});++test('REAL BUNDLE: a first row that is no row is a failure of the SDK\u2019s lookup, kept in its words — not a table with no row summary — and no row summary is deleted', async () => {+ const org = fakeSkillOrg({ rows: [null] });+ const { result, events } = await run(await realSdk(org), withoutPage);+ assert.strictEqual(result.ok, true, 'best-effort, as it always was');+ assert.deepStrictEqual(events.map((e) => [e.status, e.skip]), [['skip', 'kept']]);+ assert.match(events[0].label, /^row summary new_memo \(kept \u2014 1 not removed: HTTP 200 from https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.\d\/aiskillconfigs\?[^:]*: the row-summary skill lookup returned a malformed row \u2014 expected an object but got /);+ assert.deepStrictEqual(deleteRequests(org.requests).filter((p) => /aiskillconfigs|msdyn_aimodels/.test(p)), []);+ assert.deepStrictEqual(result.deleted.aiSummary, []);});test('REAL BUNDLE: an environment with no AI skill table is reported as not found through the whole teardown', async () => {diff --git a/plugins/model-apps/scripts/tests/throttle-budget.test.js b/plugins/model-apps/scripts/tests/throttle-budget.test.jsindex 610823ed9..740dafda4 100644--- a/plugins/model-apps/scripts/tests/throttle-budget.test.js+++ b/plugins/model-apps/scripts/tests/throttle-budget.test.js@@ -1,11 +1,11 @@'use strict';-// lib/throttle-budget.js: the budget a run allows its own retry layers for waiting out a throttled service — in the page backend (the waits between a page write's sends) and in the build's own retry loop (the wait before it runs again). The HTTP client's own re-sends are not drawn from it.+// lib/throttle-budget.js: the budget a run allows itself for waiting out a throttled service — in the HTTP client (the waits before it sends a throttled request again), in the page backend (the waits between a page write's sends) and in the build's own retry loop (the wait before it runs again).// The layers wait with seams of their own, so the budget only COUNTS: what a wait is, and whether it fits, is decided here, once.const test = require('node:test');const assert = require('node:assert');const fs = require('node:fs');const path = require('node:path');-const { THROTTLE_BUDGET_MS, QUIET_WAIT_MS, makeThrottleBudget, waitDoesNotFit, spentNote } = require('../lib/throttle-budget.js');+const { THROTTLE_BUDGET_MS, QUIET_WAIT_MS, makeThrottleBudget, waitDoesNotFit, refusedWait, spentNote } = require('../lib/throttle-budget.js');test('the budget is five minutes, and a wait of up to five seconds is not worth a line', () => {assert.strictEqual(THROTTLE_BUDGET_MS, 5 * 60 * 1000);@@ -66,6 +66,27 @@ test('waitDoesNotFit: says what the service asked, how much of the budget is lefassert.match(waitDoesNotFit(makeThrottleBudget({ totalMs: 60000 }), { askedMs: 120000, waitMs: 120000 }), /what is left of the 1 minute a run allows itself/);});+// The line the HTTP client's refusal leaves on the warn seam is read by callers that have no business with what to run next: the upload script's client refuses a publish AFTER the page was created, where the same command again would create a+// second page. So it says what happened — what the service asked, that it does not fit, that the request was not sent again — and leaves the advice to the caller that knows its own state.+test('refusedWait: says what the service asked and that the request was not sent again — and nothing of what to run next', () => {+ const budget = makeThrottleBudget();+ budget.spend(245500);+ assert.strictEqual(+ refusedWait(budget, { askedMs: 600000, waitMs: 600000 }),+ 'the service asked to wait 600 s before this request is sent again, which does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service (246 s are spent), so it was not sent again.',+ );+ assert.strictEqual(+ refusedWait(budget, { waitMs: 9000 }),+ 'the next wait before this request is sent again, 9 s, does not fit in what is left of the 5 minutes a run allows itself for waiting out a throttled service (246 s are spent), so it was not sent again.',+ 'with no request from the service the wait is the schedule\'s',+ );+ assert.match(refusedWait(budget, { askedMs: 60001, waitMs: 60001 }), /^the service asked to wait 61 s before this request/, 'rounded up, as the halt\'s sentence is');+ assert.match(refusedWait(makeThrottleBudget({ totalMs: 90000 }), { askedMs: 120000, waitMs: 120000 }), /what is left of the 90 seconds a run allows itself/, 'a budget that is not whole minutes is said in seconds');+ for (const said of [refusedWait(budget, { askedMs: 600000, waitMs: 600000 }), refusedWait(budget, { waitMs: 9000 })]) {+ assert.doesNotMatch(said, /same command|again later|Nothing more is sent now|continues from here/, 'no advice: whether a run of anything again is safe is not the client\'s to say');+ }+});+test('spentNote: how much of the budget is gone, in the words of the line that announces a wait', () => {const budget = makeThrottleBudget();budget.spend(46500);@@ -73,6 +94,73 @@ test('spentNote: how much of the budget is gone, in the words of the line that aassert.strictEqual(spentNote(makeThrottleBudget({ totalMs: 90000 })), '0 s of the 90 seconds a run allows itself for waiting out a throttled service are spent');});+// The HTTP client's waits can OVERLAP: it sends several requests at once (the build runs four at a time), a service that throttles them answers them alike, and they wake together. What a run waited is the time it spent waiting, not+// the sum of its requests' waits, so a wait that is PLACED on the clock (`at`, the moment it starts) adds only what runs past the end of the waits already placed. The layers that wait one at a time — the page backend, the build's own+// loop — place nothing, and what they spend is added whole, as it always was.+test('a wait placed on the clock adds only what runs past the waits already under way — requests throttled together wake together, and the run waited once', () => {+ const budget = makeThrottleBudget();+ assert.strictEqual(budget.spend(60000, 1000), 60000, 'the first wait is added whole: the time it takes');+ assert.strictEqual(budget.spend(60000, 1005), 5, 'one that starts 5 ms later ends 5 ms later, and those 5 ms are all it adds');+ assert.strictEqual(budget.spend(30000, 1010), 0, 'one that ends before the others do adds nothing');+ assert.strictEqual(budget.spentMs(), 60005);+ assert.strictEqual(budget.spend(60000, 61005), 60000, 'a wait that starts when the others are over is a wait of its own, added whole');+ assert.strictEqual(budget.spentMs(), 120005);+ assert.strictEqual(budget.spend(1000, 200000), 1000, 'and so is one a long time after');+});++test('fits answers for a placed wait by what it would add — a wait inside the waits under way always fits, and one that runs past them fits when only the part past them does', () => {+ const budget = makeThrottleBudget({ totalMs: 100000 });+ budget.spend(60000, 0);+ assert.strictEqual(budget.fits(60000, 10), true, 'it adds 10 ms');+ assert.strictEqual(budget.fits(100000, 10), false, 'it would add 40.01 s, and 40 s are left');+ assert.strictEqual(budget.fits(100000, 0), true, 'it would add exactly the 40 s that are left');+ budget.spend(40000, 60000);+ assert.strictEqual(budget.remainingMs(), 0);+ assert.strictEqual(budget.fits(30000, 1000), true, 'nothing is left, and a wait that ends before the others do still adds nothing');+ assert.strictEqual(budget.fits(30000, 100000), false, 'one that starts when they are over would add all of it');+ assert.strictEqual(budget.fits(1), false, 'and a wait with no place is whole, as ever: nothing is left');+});++test('a wait with no place is added whole whatever has been placed — the page backend and the build wait one at a time and are never made smaller by the client\'s', () => {+ const budget = makeThrottleBudget();+ budget.spend(60000, 1000);+ assert.strictEqual(budget.spend(60000), 60000, 'it overlaps the placed wait on no clock, and is added whole');+ assert.strictEqual(budget.spend(5000), 5000);+ assert.strictEqual(budget.spentMs(), 125000);+ for (const nothing of [undefined, null, Number.NaN, -5, 0, 'x']) assert.strictEqual(budget.spend(nothing, 5), 0, `${nothing} is no wait, placed or not`);+ assert.strictEqual(budget.spentMs(), 125000);+ assert.strictEqual(budget.spend(1000, Number.NaN), 1000, 'a place that is not a moment is no place');+});++// A wait the HTTP client would not take is the client's to say: it hands the throttled answer back as it came — the SDK reports it as the 429 it is, and an answer carries nothing of what the service asked, nor of why nothing+// more was sent — so the budget is where it is written down, for the build, which owns the halt, to read.+test('decline: a wait that did not fit is counted, with the longest ask and wait, and said on the warn seam once for each longer wait', () => {+ const lines = [];+ const budget = makeThrottleBudget({ warn: (message) => lines.push(message) });+ assert.deepStrictEqual(budget.declined(), { count: 0, askedMs: 0, waitMs: 0 });+ budget.spend(250000);+ budget.decline({ askedMs: 90000, waitMs: 90000 });+ assert.deepStrictEqual(budget.declined(), { count: 1, askedMs: 90000, waitMs: 90000 });+ assert.deepStrictEqual(lines, [refusedWait(budget, { askedMs: 90000, waitMs: 90000 })], 'in the words of a refusal: what the service asked and that the request was not sent again');+ assert.doesNotMatch(lines[0], /same command|again later|Nothing more is sent now/, 'with no advice the caller that owns the state has to give');+ budget.decline({ askedMs: 60000, waitMs: 60000 });+ assert.deepStrictEqual(budget.declined(), { count: 2, askedMs: 90000, waitMs: 90000 }, 'a shorter one is counted, and the longest stays');+ assert.strictEqual(lines.length, 1, 'and is not said again: four requests that are refused together are one line');+ budget.decline({ waitMs: 120000 });+ assert.deepStrictEqual(budget.declined(), { count: 3, askedMs: 90000, waitMs: 120000 }, 'a longer wait with no ask of the service is the schedule\'s');+ assert.strictEqual(lines.length, 2);+ assert.match(lines[1], /^the next wait before this request is sent again, 120 s, does not fit in what is left of the 5 minutes/);+ assert.doesNotThrow(() => makeThrottleBudget().decline({ waitMs: 1000 }), 'a budget with no warn seam says nothing, and is counted all the same');+ assert.strictEqual(makeThrottleBudget().declined().count, 0, 'a budget counts its own declines');+});++test('note: how much of the budget is gone, in the words of the line that announces a wait', () => {+ const budget = makeThrottleBudget();+ budget.spend(46500);+ assert.strictEqual(budget.note(), spentNote(budget));+ assert.strictEqual(budget.note(), '47 s of the 5 minutes a run allows itself for waiting out a throttled service are spent');+});+// What the module is NOT: it writes nothing itself. The lines it announces go to the caller's `warn` seam, which the build wires to stderr — stdout carries the JSON result of the run.test('the module never writes to stdout or stderr itself — what it announces goes to the seam the caller gives', () => {const source = fs.readFileSync(path.join(__dirname, '..', 'lib', 'throttle-budget.js'), 'utf8');diff --git a/plugins/model-apps/scripts/tests/throttle-client-budget.test.js b/plugins/model-apps/scripts/tests/throttle-client-budget.test.jsnew file mode 100644index 000000000..eeefc3c21--- /dev/null+++ b/plugins/model-apps/scripts/tests/throttle-client-budget.test.js@@ -0,0 +1,134 @@+'use strict';+// The HTTP client draws its waits for a throttled answer from the run's throttle budget (lib/sdk-http-client.js, lib/throttle-budget.js): these tests hold the WIRING that gives every client of a run the one budget — the build's SDK, the+// page backend's, and the upload script's — and nothing else. What the client does with a budget is held in sdk-http-client.test.js, and what the build's loop does with a wait the client was refused is held in build-model-app.test.js;+// sdk-build-pages-deploy.test.js runs all three together over the real SDK.+const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { loadCli } = require('./helpers/cli-harness.js');+const { FakeGenPageServer, INSTANCE } = require('./helpers/fake-genpage-server.js');+const { makeGenpageSdk } = require('../lib/genpage-sdk.js');+const { makeThrottleBudget } = require('../lib/throttle-budget.js');++const scriptsDir = path.join(__dirname, '..');+const SOURCE = "import * as React from 'react';\nexport default function Page() { return <div>Hello</div>; }\n";+const isBudget = (value) => ['fits', 'spend', 'announce', 'decline', 'declined', 'note'].every((name) => typeof (value && value[name]) === 'function');++// ── The page backend ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────+// The backend makes the HTTP client of its own SDK (the build's pages phase, the verify after it and the upload script all use one), and hands it the budget it was given: what the client waits for on a throttled read or publish is+// then the run's, with the backend's own waits for a page write.+test('the page backend gives the budget it was handed to the HTTP client it makes — and none when it was handed none', async () => {+ for (const [what, deps, expected] of [['a budget', { throttle: makeThrottleBudget() }, 'given'], ['none', {}, undefined]]) {+ const server = new FakeGenPageServer();+ const seen = [];+ const genpage = makeGenpageSdk(INSTANCE, { ...deps, createHttpClient: (env, options) => { seen.push({ env, options }); return server.http(); } });+ try {+ assert.strictEqual((await genpage.enumerateEnv()).ok, true, what);+ assert.strictEqual(seen.length, 1, `${what}: one client, made once`);+ assert.strictEqual(seen[0].env, INSTANCE);+ assert.strictEqual(seen[0].options.throttle, expected === 'given' ? deps.throttle : undefined, `${what}: the client is given the backend's budget, or none`);+ } finally {+ await genpage.dispose();+ }+ }+});++test('a client that is injected is the caller\'s own: the backend does not make one, and so hands a budget to nothing', async () => {+ const server = new FakeGenPageServer();+ let made = 0;+ const genpage = makeGenpageSdk(INSTANCE, { httpClient: server.http(), throttle: makeThrottleBudget(), createHttpClient: () => { made += 1; return server.http(); } });+ try {+ assert.strictEqual((await genpage.enumerateEnv()).ok, true);+ assert.strictEqual(made, 0);+ } finally {+ await genpage.dispose();+ }+});++// A page write is given the run's budget by the build (`args.throttle`); the upload script gives none to its write, and hands its backend one instead, so the write's resends and the client's waits are drawn from the same+// five minutes. A backend that was handed nothing gives each write a budget of its own, as it always did.+test('a page write that is given no budget spends the one its backend was handed — the client\'s waits and the write\'s resends are one budget — and one it is given wins', async () => {+ const throttledFirst = () => {+ const server = new FakeGenPageServer();+ server.failBatch = (n) => (n === 1 ? { status: 429, headers: { 'retry-after': '9' } } : undefined);+ return server;+ };+ const backend = (server, deps, slept) => makeGenpageSdk(INSTANCE, { httpClient: server.http(), sleep: async (ms) => { slept.push(ms); }, random: () => 0, ...deps });+ // Handed to the backend: the write draws from it.+ const own = makeThrottleBudget();+ const slept = [];+ const genpage = backend(throttledFirst(), { throttle: own }, slept);+ try {+ const out = await genpage.create({ name: 'Overview', source: SOURCE, prompt: 'p', agentMessage: 'r' });+ assert.deepStrictEqual(slept, [9000]);+ assert.strictEqual(own.spentMs(), 9000, 'the wait is the backend\'s budget\'s');+ assert.ok(out.pageId);+ } finally { await genpage.dispose(); }+ // Handed to the write as well: the write's own wins, and the backend's is not touched.+ const backendBudget = makeThrottleBudget();+ const writeBudget = makeThrottleBudget();+ const slept2 = [];+ const second = backend(throttledFirst(), { throttle: backendBudget }, slept2);+ try {+ await second.create({ name: 'Overview', source: SOURCE, prompt: 'p', agentMessage: 'r', throttle: writeBudget });+ assert.deepStrictEqual([writeBudget.spentMs(), backendBudget.spentMs()], [9000, 0]);+ } finally { await second.dispose(); }+ // Handed nothing: a budget of its own for each write, so two writes that are throttled for 200 s each both fit, as they always did.+ const slept3 = [];+ const server = new FakeGenPageServer();+ server.failBatch = (n) => (n === 1 || n === 3 ? { status: 429, headers: { 'retry-after': '200' } } : undefined);+ const plain = backend(server, {}, slept3);+ try {+ await plain.create({ name: 'First', source: SOURCE, prompt: 'p', agentMessage: 'r' });+ await plain.create({ name: 'Second', source: SOURCE.replace('Hello', 'Other'), prompt: 'p', agentMessage: 'r' });+ assert.deepStrictEqual(slept3, [200000, 200000], 'each write had its own five minutes');+ } finally { await plain.dispose(); }+});++test('a budget that is not one is no budget — the backend\'s write makes one of its own, and its client is given none', async () => {+ const server = new FakeGenPageServer();+ server.failBatch = (n) => (n === 1 ? { status: 429, headers: { 'retry-after': '9' } } : undefined);+ const slept = [];+ const seen = [];+ const genpage = makeGenpageSdk(INSTANCE, { createHttpClient: (env, options) => { seen.push(options); return server.http(); }, throttle: { fits: true }, sleep: async (ms) => { slept.push(ms); }, random: () => 0 });+ try {+ await genpage.create({ name: 'Overview', source: SOURCE, prompt: 'p', agentMessage: 'r' });+ assert.deepStrictEqual(slept, [9000]);+ assert.strictEqual(isBudget(seen[0].throttle), false);+ } finally { await genpage.dispose(); }+});++// ── The build ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────+// build-model-app.js's main() makes the run's budget before anything else that sends, and hands that one object to the HTTP client its SDK is made over — both SDK instances share it, and verify's isolated reader — and to the+// engine, whose pages phase gives it to the page backend and to every page write, and to the retry loop. Run here as the CLI runs, over stand-ins for the SDK, the client and the engine, so the wires are what is held.+test('build-model-app.js makes ONE budget and hands it to the HTTP client of its SDK and to the engine — the same object, with the warn seam on stderr', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'throttle-wiring-'));+ try {+ fs.copyFileSync(path.join(scriptsDir, '..', 'samples', 'app-spec.support-desk.json'), path.join(dir, 'app-spec.json'));+ const authCli = loadCli(path.join(scriptsDir, 'lib', 'dataverse-auth.js'));+ const clients = [];+ const engines = [];+ const cli = loadCli(path.join(scriptsDir, 'build-model-app.js'), {+ argv: ['--env', INSTANCE, '--spec', `@${path.join(dir, 'app-spec.json')}`, '--no-live-plan'],+ requires: {+ './lib/dataverse-auth.js': authCli.exports,+ './lib/sdk-http-client.js': { createAzHttpClient: (env, deps) => { clients.push(deps); return {}; }, SQL_DEADLOCK_VICTIM: /Sql Number: 1205/ },+ './lib/maker-sdk.js': { createNodeWorkspaceStorage: (d) => ({ dir: d }), createMakerSdk: () => ({ initWorkspace: async () => {} }) },+ './lib/sdk-build.js': { ...require('../lib/sdk-build.js'), runSdkBuild: async (spec, options) => { engines.push(options); return { ok: true, dryRun: true, planItems: [] }; } },+ },+ });+ await assert.rejects(cli.main(), (err) => err && err.exitCode === 0);+ assert.strictEqual(clients.length, 1, 'one client, which both SDK instances and the isolated reader share');+ assert.ok(clients[0] && isBudget(clients[0].throttle), 'and it is made with the run\'s budget');+ assert.strictEqual(engines.length, 1);+ assert.strictEqual(engines[0].throttle, clients[0].throttle, 'the engine\'s pages phase spends from the very same one');+ // What the budget says goes to stderr — stdout carries the JSON result.+ clients[0].throttle.announce('a long wait', 60000);+ assert.deepStrictEqual(cli.stderr.filter((line) => /a long wait/.test(line)), ['⚠ a long wait\n']);+ assert.deepStrictEqual(cli.stdout.filter((line) => /a long wait/.test(line)), []);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/scripts/tests/throttle-engine-stop.test.js b/plugins/model-apps/scripts/tests/throttle-engine-stop.test.jsnew file mode 100644index 000000000..e47b36f9a--- /dev/null+++ b/plugins/model-apps/scripts/tests/throttle-engine-stop.test.js@@ -0,0 +1,150 @@+'use strict';+// The engine's step guard (lib/entity-provision.js, makeRunner). Once a run's throttle budget has refused to wait for a throttled request (lib/throttle-budget.js, `decline`), the run is over: the build's retry loop stops with+// `throttle-budget-exhausted` instead of running the phases again to meet the same answer. A refusal can be swallowed on its way up the engine — a best-effort step reports a failure and goes on, a fallback answers a refused request+// with others — and the run would then go on sending requests to a service that asked it to hold back, and could even end as a success. So no step STARTS after a refusal; a step that is already running finishes. These tests hold+// the guard on the runner itself; the column change set it was made for is held in table-columns-in-create.test.js, against the real SDK.+const test = require('node:test');+const assert = require('node:assert');+const { makeRunner, runBestEffort, mapLimit, BuildHalt } = require('../lib/entity-provision.js');+const { makeThrottleBudget, waitDoesNotFit } = require('../lib/throttle-budget.js');+const { isTransientHalt } = require('../build-model-app.js');++const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+// What the HTTP client does when the wait the service asked for does not fit: it tells the budget.+const refuse = (budget, askedMs = 600000) => budget.decline({ askedMs, waitMs: askedMs });+const narrated = (events) => events.map((e) => `${e.status} ${e.label}`);+const stopOf = (budget, phase) => `${phase ? `${phase} stopped` : 'the build stopped'}: ${waitDoesNotFit(budget, budget.declined())}`;++test('before any refusal the runner is what it was — steps run, are narrated and fail as they did — with a budget, with one that has refused nothing, and with none', async () => {+ const idle = makeThrottleBudget();+ for (const [what, throttle] of [['a budget that refused nothing', idle], ['no budget', undefined], ['a budget that cannot be asked', { fits: () => true }]]) {+ const events = [];+ const runner = makeRunner({ emit: (e) => events.push(e), total: 2, ...(throttle ? { throttle } : {}) });+ assert.strictEqual(await runner.run('data-model', 'one', async () => 7), 7, what);+ await assert.rejects(runner.run('data-model', 'two', async () => { throw new Error('boom'); }), (error) => {+ assert.ok(error instanceof BuildHalt, what);+ assert.strictEqual(error.message, 'data-model failed: boom', what);+ assert.notStrictEqual(error.code, 'throttle-budget-exhausted', what);+ return true;+ });+ assert.deepStrictEqual(narrated(events), ['start one', 'ok one', 'start two', 'error two'], what);+ assert.doesNotThrow(() => runner.stopIfRefused('data-model'), what);+ }+ assert.strictEqual(makeRunner({ emit: () => {}, total: 0 }).mapLimit, mapLimit, 'a runner with no budget is given the one limiter');+});++test('after the budget has refused a wait no step starts — the function is not called, nothing is narrated, and the halt is the budget\'s: transient, saying what the service asked', async () => {+ const budget = makeThrottleBudget();+ const events = [];+ const runner = makeRunner({ emit: (e) => events.push(e), total: 3, throttle: budget });+ assert.strictEqual(await runner.run('data-model', 'first', async () => 1), 1);+ refuse(budget);+ let called = 0;+ await assert.rejects(runner.run('data-model', 'second', async () => { called += 1; }), (error) => {+ assert.ok(error instanceof BuildHalt);+ assert.strictEqual(error.code, 'throttle-budget-exhausted');+ assert.strictEqual(error.phase, 'data-model');+ assert.strictEqual(error.recoverable, true);+ assert.strictEqual(error.statusCode, 429);+ assert.strictEqual(isTransientHalt(error), true, 'a later run goes on from here');+ assert.strictEqual(error.message, stopOf(budget, 'data-model'));+ assert.match(error.message, /^data-model stopped: the service asked to wait 600 s before the next send, which does not fit in what is left of the 5 minutes/);+ return true;+ });+ assert.strictEqual(called, 0, 'the step was not run');+ assert.deepStrictEqual(narrated(events), ['start first', 'ok first'], 'and not narrated: it never started');+ assert.throws(() => runner.stopIfRefused(), (error) => error.code === 'throttle-budget-exhausted' && /^the build stopped: /.test(error.message), 'asked outside a phase, the guard says "the build"');+});++test('a refusal made before the runner was is not its run\'s — one runner is one run of the phases, and what an earlier run met is over', async () => {+ const budget = makeThrottleBudget();+ refuse(budget);+ const runner = makeRunner({ emit: () => {}, total: 1, throttle: budget });+ assert.strictEqual(await runner.run('data-model', 'step', async () => 'ran'), 'ran');+ refuse(budget, 60000);+ await assert.rejects(runner.run('data-model', 'next', async () => {}), (error) => error.code === 'throttle-budget-exhausted');+});++test('a best-effort step after a refusal does not run and says why — and the next step that is required stops the phase', async () => {+ const budget = makeThrottleBudget();+ const runner = makeRunner({ emit: () => {}, total: 2, throttle: budget });+ refuse(budget);+ const warnings = [];+ let called = 0;+ const out = await runBestEffort(runner, 'data-model', 'optional', async () => { called += 1; }, (w) => warnings.push(w), 'could not do the optional thing');+ assert.strictEqual(out, undefined);+ assert.strictEqual(called, 0);+ assert.strictEqual(warnings.length, 1);+ assert.match(warnings[0], /^could not do the optional thing: data-model stopped: the service asked to wait 600 s before the next send/);+ await assert.rejects(runner.run('data-model', 'required', async () => { called += 1; }), (error) => error.code === 'throttle-budget-exhausted');+ assert.strictEqual(called, 0);+});++// A caller that records what a step came to inside its function (the primary name column's length step) cannot tell a step that ran and succeeded from one the runner stopped before it began — the stop is swallowed with the failures —+// unless the runner says so. `onFailure` is that: what the step failed with, whichever of the two it was.+test('runBestEffort tells a caller what a step failed with — what the step threw, or the stop that kept it from running — and hands the runner only the options the runner knows', async () => {+ const budget = makeThrottleBudget();+ const runner = makeRunner({ emit: () => {}, total: 4, throttle: budget });+ const failures = [];+ const options = { onFailure: (error) => failures.push(error) };+ let called = 0;+ assert.strictEqual(await runBestEffort(runner, 'data-model', 'fails', async () => { called += 1; throw new Error('boom'); }, () => {}, 'could not do it', options), undefined);+ assert.strictEqual(called, 1);+ assert.strictEqual(failures.length, 1);+ assert.ok(failures[0] instanceof BuildHalt, 'what the runner made of the failure');+ assert.strictEqual(failures[0].cause.message, 'boom');+ assert.strictEqual(await runBestEffort(runner, 'data-model', 'works', async () => 'done', () => {}, 'could not do it', options), 'done');+ assert.strictEqual(failures.length, 1, 'a step that succeeded says nothing');+ refuse(budget);+ assert.strictEqual(await runBestEffort(runner, 'data-model', 'stopped', async () => { called += 1; }, () => {}, 'could not do it', options), undefined);+ assert.strictEqual(called, 1, 'the function was not called');+ assert.strictEqual(failures.length, 2);+ assert.strictEqual(failures[1].code, 'throttle-budget-exhausted', 'and the hook has the stop');+ assert.strictEqual(await runBestEffort(runner, 'data-model', 'settles', async () => 'settled', () => {}, 'could not do it', { ...options, settling: true }), 'settled');+ assert.strictEqual(failures.length, 2, 'a step that settles is not stopped');+ const seen = [];+ const recording = { run: async (phase, label, fn, runOptions) => { seen.push(runOptions); return fn(); } };+ await runBestEffort(recording, 'data-model', 'x', async () => 1, undefined, 'could not do it', { skipIf: () => false, onFailure() {} });+ assert.deepStrictEqual(Object.keys(seen[0]).sort(), ['recoverable', 'skipIf'], 'the hook is not one of the options of the runner');+});++test('what settles a halt is let through after a refusal, and a skip is still narrated — neither sends a request that the service has asked the run to hold back', async () => {+ const budget = makeThrottleBudget();+ const events = [];+ const runner = makeRunner({ emit: (e) => events.push(e), total: 2, throttle: budget });+ refuse(budget);+ assert.strictEqual(await runner.run('data-model', 'settle what the halt left', async () => 'settled', { settling: true }), 'settled', 'a step that settles what a halted phase owes is not a step of the phase');+ runner.skip('data-model', 'skipped');+ assert.deepStrictEqual(narrated(events), ['start settle what the halt left', 'ok settle what the halt left', 'skip skipped']);+});++test('the runner\'s fan-out starts no item after a refusal — an item already running finishes, and the stop is what it reports', async () => {+ const budget = makeThrottleBudget();+ const runner = makeRunner({ emit: () => {}, total: 9, throttle: budget });+ const started = [];+ const finished = [];+ await assert.rejects(runner.mapLimit(['a', 'b', 'c', 'd'], 2, async (item) => {+ started.push(item);+ if (item === 'a') { await sleep(5); refuse(budget); finished.push('a'); return; }+ await sleep(40);+ finished.push(item);+ }), (error) => {+ assert.strictEqual(error.code, 'throttle-budget-exhausted');+ assert.strictEqual(isTransientHalt(error), true);+ return true;+ });+ assert.deepStrictEqual(started, ['a', 'b'], 'c and d never started');+ assert.deepStrictEqual(finished.sort(), ['a', 'b'], 'b was already running, and finished before the stop was reported');+ // Before a refusal it is the limiter it always was: input order, and the first failure reported once the items in flight settle.+ const quiet = makeRunner({ emit: () => {}, total: 9, throttle: makeThrottleBudget() });+ assert.deepStrictEqual(await quiet.mapLimit([30, 5, 15], 2, async (ms, index) => { await sleep(ms); return index; }), [0, 1, 2]);+ const failure = new Error('first failure');+ const seen = [];+ await assert.rejects(quiet.mapLimit(['fails', 'slow', 'later'], 2, async (item) => {+ seen.push(item);+ if (item === 'fails') { await sleep(5); throw failure; }+ await sleep(30);+ return item;+ }), (error) => error === failure);+ assert.deepStrictEqual(seen, ['fails', 'slow'], 'nothing is started after the first failure');+});diff --git a/plugins/model-apps/scripts/tests/translation-labels.test.js b/plugins/model-apps/scripts/tests/translation-labels.test.jsnew file mode 100644index 000000000..c6446d030--- /dev/null+++ b/plugins/model-apps/scripts/tests/translation-labels.test.js@@ -0,0 +1,475 @@+'use strict';+// lib/translation-labels.js: the captions of a solution's forms, read from ONE translation export.+//+// The platform's form reads carry the labels of some languages only (a form built with Spanish captions in an English-language organization reads back+// in English alone), and a translation export is the one read that carries every provisioned language. This module turns the export into an answer to+// "what is the caption of this tab or section, in this language": the workbook the export holds is read by the plugin's strict XML reader and by rules+// of its own, and ANYTHING it does not recognise — a structure, a type, a reference, a row it cannot place — is "not readable", never a guess. These+// tests drive the whole path with synthesized exports (helpers/translation-export.js), from the answer of the request down to a cell.+const test = require('node:test');+const assert = require('node:assert');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const { parseTranslationWorkbook, readTranslationLabels, settleCaption, isTranslationExport, WORKBOOK_ENTRY, LABELS_SHEET } = require('../lib/translation-labels.js');+const { workbookXml, zipOf, exportZip, exportAnswer, EXPORT_PATH, SPREADSHEET_NAMESPACE } = require('./helpers/translation-export.js');++const TAB = '0a0a0a0a-0000-4000-8000-000000000001';+const SECTION = '0a0a0a0a-0000-4000-8000-000000000002';+const OTHER = '0a0a0a0a-0000-4000-8000-000000000003';+const CELL = '0a0a0a0a-0000-4000-8000-000000000004';+const rows = () => [+ { entity: 'new_ticket', id: TAB, texts: { 1033: 'Tab One', 3082: 'Pestana Uno' } },+ { entity: 'new_ticket', id: SECTION, texts: { 1033: 'Details', 3082: 'Detalles' } },+ { entity: 'new_ticket', id: OTHER, texts: { 1033: 'Notes' } },+ { entity: 'new_ticket', id: CELL, column: 'DisplayName', texts: { 1033: 'Name', 3082: 'Nombre' } },+];+const parsed = (over) => {+ const read = parseTranslationWorkbook(workbookXml({ captions: rows(), ...over }));+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ return read;+};+const refused = (xml) => {+ const read = parseTranslationWorkbook(xml);+ assert.strictEqual(read.ok, false, 'a workbook it cannot read with certainty is refused');+ assert.strictEqual(typeof read.detail, 'string');+ return read.detail;+};+// The workbook has the same header texts in `Display Strings` and `Localized Labels`; the last one is the sheet that is read.+const replaceLast = (text, from, to) => {+ const at = text.lastIndexOf(from);+ assert.ok(at >= 0, `${from} is in the workbook`);+ return text.slice(0, at) + to + text.slice(at + from.length);+};++test('translation workbook: the captions of the measured shape are found by the id of the tab or section, in every language column', () => {+ const read = parsed();+ assert.deepStrictEqual(read.languages, [1033, 3082]);+ assert.deepStrictEqual([...read.lookup('new_ticket', TAB).texts], [[1033, 'Tab One'], [3082, 'Pestana Uno']]);+ assert.deepStrictEqual([...read.lookup('new_ticket', SECTION).texts], [[1033, 'Details'], [3082, 'Detalles']]);+ // A caption with no translation is an EMPTY cell: the row is there, and says nothing in that language.+ assert.deepStrictEqual([...read.lookup('new_ticket', OTHER).texts], [[1033, 'Notes'], [3082, '']]);+ assert.strictEqual(WORKBOOK_ENTRY, 'CrmTranslations.xml');+ assert.strictEqual(LABELS_SHEET, 'Localized Labels');+});++test('translation workbook: a row is found by its table and its id, whatever the case of either and whether the id has braces — and by nothing else', () => {+ const read = parsed();+ for (const [entity, id] of [['NEW_TICKET', TAB.toUpperCase()], ['new_ticket', `{${TAB}}`], ['New_Ticket', `{${TAB.toUpperCase()}}`]]) {+ assert.strictEqual(read.lookup(entity, id).found, true, `${entity} ${id}`);+ }+ assert.deepStrictEqual(read.lookup('new_other', TAB), { found: false }, 'the id of another table\u2019s form is not this form\u2019s');+ assert.deepStrictEqual(read.lookup('new_ticket', '11111111-2222-3333-4444-555555555555'), { found: false });+ for (const bad of [undefined, null, '', 'not-a-guid', 123, {}]) assert.deepStrictEqual(read.lookup('new_ticket', bad), { found: false }, String(bad));+ assert.deepStrictEqual(read.lookup(undefined, TAB), { found: false });+});++test('translation workbook: only the rows of the column `displayname` are captions — a table\u2019s or a column\u2019s display name, keyed by another id, is not', () => {+ const read = parsed({ captions: [...rows(), { entity: 'new_ticket', id: TAB, column: 'description', texts: { 1033: 'Not a caption', 3082: 'No es un titulo' } }, { entity: 'new_ticket', id: SECTION, column: 'DisplayName', texts: { 1033: 'Wrong case', 3082: 'Mayuscula' } }] });+ assert.strictEqual(read.lookup('new_ticket', TAB).ambiguous, false, 'a `description` row of the same id is not a second caption');+ assert.strictEqual(read.lookup('new_ticket', TAB).texts.get(1033), 'Tab One');+ assert.strictEqual(read.lookup('new_ticket', SECTION).texts.get(1033), 'Details', 'the column is spelled `displayname`, and only that');+ assert.deepStrictEqual(read.lookup('new_ticket', CELL), { found: false });+});++test('translation workbook: an id that two rows of one table carry is ambiguous, and no text is given for it', () => {+ const read = parsed({ captions: [...rows(), { entity: 'new_ticket', id: TAB.toUpperCase(), texts: { 1033: 'A copy of the form', 3082: 'Una copia' } }] });+ assert.deepStrictEqual(read.lookup('new_ticket', TAB), { found: true, ambiguous: true });+ assert.strictEqual(read.lookup('new_ticket', SECTION).ambiguous, false, 'the others are untouched');+ // The same id under another table is another row.+ const split = parsed({ captions: [...rows(), { entity: 'new_other', id: TAB, texts: { 1033: 'Same id, other table', 3082: 'Otra tabla' } }] });+ assert.strictEqual(split.lookup('new_ticket', TAB).texts.get(1033), 'Tab One');+ assert.strictEqual(split.lookup('new_other', TAB).texts.get(1033), 'Same id, other table');+});++test('translation workbook: the language columns are the LCIDs of the header row, in its order — one, or many', () => {+ assert.deepStrictEqual(parsed({ languages: [1033] , captions: [{ entity: 'new_ticket', id: TAB, texts: { 1033: 'Tab One' } }] }).languages, [1033]);+ const three = parsed({ languages: [3082, 1033, 1036], captions: [{ entity: 'new_ticket', id: TAB, texts: { 1033: 'One', 1036: 'Un', 3082: 'Uno' } }] });+ assert.deepStrictEqual(three.languages, [3082, 1033, 1036]);+ assert.deepStrictEqual([...three.lookup('new_ticket', TAB).texts], [[3082, 'Uno'], [1033, 'One'], [1036, 'Un']]);+});++test('translation workbook: a cell is its text exactly — references decoded, white space kept, a line end read as XML reads it', () => {+ const xml = workbookXml({ captions: [{ entity: 'new_ticket', id: TAB, texts: { 1033: ' R & D <1> "q" ', 3082: 'Pesta\u00f1a' } }] })+ .replace('R & D', 'R & D éA x')+ .replace('Pesta\u00f1a', 'Pestaña\r\nb\rc d');+ const read = parseTranslationWorkbook(xml);+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ const texts = read.lookup('new_ticket', TAB).texts;+ assert.strictEqual(texts.get(1033), ' R & D \u00e9A\nx <1> "q" ');+ assert.strictEqual(texts.get(3082), 'Pesta\u00f1a\nb\nc\rd', 'a literal CR LF and a lone CR are line feeds, as in any XML parser; a CR written as a reference stays one');+});++test('translation workbook: a cell may leave out its Data, its type or its tail — an empty cell is the empty text, and ss:Index skips to a column', () => {+ const sheet = (body) => workbookXml({ captions: [] }).replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?<\/Row>)([\s\S]*?)(<\/Table>)/, `$1${body}$3`);+ const empties = parseTranslationWorkbook(sheet(`<Row><Cell><Data ss:Type="String">new_ticket</Data></Cell><Cell><Data ss:Type="String">${TAB}</Data></Cell><Cell><Data ss:Type="String">displayname</Data></Cell><Cell/><Cell ss:StyleID="s24"></Cell></Row>`));+ assert.strictEqual(empties.ok, true, JSON.stringify(empties));+ assert.deepStrictEqual([...empties.lookup('new_ticket', TAB).texts], [[1033, ''], [3082, '']]);+ const short = parseTranslationWorkbook(sheet(`<Row><Cell><Data ss:Type="String">new_ticket</Data></Cell><Cell><Data ss:Type="String">${TAB}</Data></Cell><Cell><Data ss:Type="String">displayname</Data></Cell><Cell><Data ss:Type="String">Only English</Data></Cell></Row>`));+ assert.deepStrictEqual([...short.lookup('new_ticket', TAB).texts], [[1033, 'Only English'], [3082, '']], 'a row that ends before the last column is empty there');+ const skipped = parseTranslationWorkbook(sheet(`<Row><Cell><Data ss:Type="String">new_ticket</Data></Cell><Cell><Data ss:Type="String">${TAB}</Data></Cell><Cell><Data ss:Type="String">displayname</Data></Cell><Cell ss:Index="5"><Data ss:Type="String">Solo espanol</Data></Cell></Row>`));+ assert.deepStrictEqual([...skipped.lookup('new_ticket', TAB).texts], [[1033, ''], [3082, 'Solo espanol']]);+ const blank = parseTranslationWorkbook(sheet(`<Row/><Row><Cell><Data ss:Type="String">new_ticket</Data></Cell><Cell><Data ss:Type="String">${TAB}</Data></Cell><Cell><Data ss:Type="String">displayname</Data></Cell><Cell><Data ss:Type="String">2024</Data></Cell></Row>`));+ assert.strictEqual(blank.lookup('new_ticket', TAB).texts.get(1033), '2024', 'an empty row is skipped');+});++test('translation workbook: a document that is not one well-formed XML document is not read — whatever it would have said', () => {+ const good = workbookXml({ captions: rows() });+ assert.match(refused('not xml'), /one XML document/);+ assert.match(refused(good.slice(0, good.length - 12)), /one XML document/, 'cut short');+ assert.match(refused(`<!DOCTYPE Workbook [<!ENTITY x "y">]>${good.replace('<?xml version="1.0"?>', '')}`), /one XML document/, 'a document type declaration');+ assert.match(refused(good.replace('Tab One', 'Tab One')), /one XML document/, 'an entity that is not predefined');+ assert.match(refused(good.replace('Tab One', 'Tab \u0001 One')), /one XML document/, 'a character XML does not allow');+ assert.match(refused(`${good}<Workbook/>`), /one XML document/, 'a second root element');+ assert.match(refused(''), /one XML document/);+ assert.match(refused(undefined), /one XML document/);+});++test('translation workbook: it is read as the platform\u2019s spreadsheet and nothing else — the root, its namespace, the sheet, its header', () => {+ const good = workbookXml({ captions: rows() });+ assert.match(refused(good.replace('<Workbook ', '<Book ').replace('</Workbook>', '</Book>')), /not a spreadsheet workbook/);+ assert.match(refused(good.replace(`<Workbook xmlns="${SPREADSHEET_NAMESPACE}"`, '<Workbook xmlns="urn:example:other"')), /not a spreadsheet workbook/);+ assert.match(refused(good.replace(`xmlns:ss="${SPREADSHEET_NAMESPACE}"`, 'xmlns:ss="urn:example:other"')), /not a spreadsheet workbook/);+ assert.match(refused(good.replace('ss:Name="Localized Labels"', 'ss:Name="Labels"')), /no worksheet named 'Localized Labels'/);+ assert.match(refused(good.replace(/<Worksheet ss:Name="Information"/, '<Worksheet ss:Name="Localized Labels"')), /more than one worksheet named 'Localized Labels'/);+ assert.match(refused(good.replace('>Object ID<', '>Object Id<')), /header of 'Localized Labels' is not/);+ assert.match(refused(replaceLast(good, '>Entity name<', '>Table<')), /header of 'Localized Labels' is not/);+ assert.match(refused(good.replace('>Object Column Name<', '>Column<')), /header of 'Localized Labels' is not/);+ assert.match(refused(replaceLast(good, '<Data ss:Type="Number">3082</Data>', '<Data ss:Type="Number">Spanish</Data>')), /header of 'Localized Labels' names a language that is not an LCID/);+ assert.match(refused(replaceLast(good, '<Data ss:Type="Number">3082</Data>', '<Data ss:Type="Number">1033</Data>')), /header of 'Localized Labels' names language 1033 twice/);+ assert.match(refused(workbookXml({ languages: [], captions: [] })), /header of 'Localized Labels' names no language/);+ const noHeader = good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)<Row[\s\S]*<\/Table>/, '$1</Table>');+ assert.match(refused(noHeader), /has no header row/);+});++test('translation workbook: a row it cannot place with certainty makes the whole export unreadable', () => {+ const good = workbookXml({ captions: rows() });+ const inSheet = (body) => good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)(<\/Table>)/, `$1${body}$2`);+ const cell = (text) => `<Cell><Data ss:Type="String">${text}</Data></Cell>`;+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}</Row>`)), /row 6 .*fewer than the three cells/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}${cell('a')}${cell('b')}${cell('c')}</Row>`)), /row 6 has more cells than the header/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell ss:Index="9">${''}</Cell></Row>`)), /row 6 has more cells than the header/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell ss:Index="3">${''}</Cell></Row>`)), /ss:Index/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell ss:Index="x"/></Row>`)), /ss:Index/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell ss:MergeAcross="1">${''}</Cell></Row>`)), /merged|formula|ss:MergeAcross/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell ss:Formula="=1"><Data ss:Type="String">x</Data></Cell></Row>`)), /merged|formula|ss:Formula/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell><Data ss:Type="String">a</Data><Data ss:Type="String">b</Data></Cell></Row>`)), /more than one Data/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell><Data ss:Type="Boolean">1</Data></Cell></Row>`)), /type 'Boolean'/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell><Data ss:Type="String">a <B>b</B></Data></Cell></Row>`)), /markup inside a cell/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell><Data ss:Type="String"><![CDATA[a]]></Data></Cell></Row>`)), /markup inside a cell/);+ assert.match(refused(inSheet(`<Row>${cell('new_ticket')}${cell(TAB)}${cell('displayname')}<Cell><Data>a</Data></Cell></Row>`)), /no ss:Type/);+ assert.match(refused(inSheet('<Row><Row/></Row>')), /is not where the spreadsheet puts one/);+ assert.match(refused(good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?<\/Table>)/, '$1<Table></Table>')), /more than one Table/);+});++test('translation workbook: a table of the workbook other than the Localized Labels sheet is none of its business, whatever it holds', () => {+ const strange = workbookXml({ captions: rows() }).replace(/(<Worksheet ss:Name="Information"[\s\S]*?<Table>)/, '$1<Row><Cell ss:Formula="=1"><Data ss:Type="Boolean">1</Data><Data>2</Data></Cell></Row>');+ const read = parseTranslationWorkbook(strange);+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ assert.strictEqual(read.lookup('new_ticket', TAB).texts.get(1033), 'Tab One');+});++// --- The sheet is validated WHOLE before anything is read from it ------------------------------------------------------------------------------+//+// The strict XML reader reads names as written — `ss:Row` is not `Row` to it — while to Excel (and to the namespace rules) `<ss:Row>` under the root's+// `xmlns:ss` IS the spreadsheet's Row. A reader that picked `Row`, `Cell` and `Data` out by name passed such a row over: a second, conflicting caption+// row vanished, and the first one settled the caption. So every element of `Localized Labels` must be one the platform writes, where it writes it, with+// the attributes it writes, and anything else — a prefixed or unknown element, a namespace declaration, an attribute it does not write — makes the WHOLE+// export unreadable: its captions stay unverified, never verified.+const inLabels = (body) => workbookXml({ captions: rows() }).replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)(<\/Table>)/, `$1${body}$2`);+const rowWith = (texts, prefix = '') => `<${prefix}Row>${['new_ticket', TAB, 'displayname', ...texts].map((text) => `<${prefix}Cell><${prefix}Data ss:Type="String">${text}</${prefix}Data></${prefix}Cell>`).join('')}</${prefix}Row>`;+const spanishFor = (read) => settleCaption(read, { entity: 'new_ticket', id: TAB, lcid: 3082, text: 'Pestana Uno' });++test('translation workbook: a row, a cell or a Data written with a prefix — the spreadsheet\u2019s own elements under another name — makes the export unreadable, never a skipped row', async () => {+ // The control: the same conflicting row, unprefixed, makes the caption ambiguous.+ const control = parseTranslationWorkbook(inLabels(rowWith(['Tab One', 'Antiguo'])));+ assert.deepStrictEqual(spanishFor(control).state, 'unsettled');+ for (const [what, xml, detail] of [+ ['a duplicate row in the spreadsheet namespace\u2019s own prefix', inLabels(rowWith(['Tab One', 'Antiguo'], 'ss:')), /has an element <ss:Row>, which the platform's sheet does not have/],+ ['a prefixed cell in an ordinary row', inLabels(`<Row><Cell><Data ss:Type="String">new_ticket</Data></Cell><ss:Cell><Data ss:Type="String">${TAB}</Data></ss:Cell></Row>`), /<ss:Cell>/],+ ['a prefixed Data in an ordinary cell', inLabels('<Row><Cell><ss:Data ss:Type="String">new_ticket</ss:Data></Cell></Row>'), /<ss:Data>/],+ ['a row of another namespace\u2019s prefix', inLabels(rowWith(['Tab One', 'Antiguo'], 'x:')), /<x:Row>/],+ ['a prefix the document never declares', inLabels(rowWith(['Tab One', 'Antiguo'], 'q:')), /<q:Row>/],+ ]) {+ assert.match(refused(xml), detail, what);+ }+ // Through the reader of the export, as --verify asks: an answer that is not readable, so the caption is never settled from the first row.+ const read = await readTranslationLabels({ post: async () => exportAnswer(exportZip(inLabels(rowWith(['Tab One', 'Antiguo'], 'ss:')))) }, 'Contoso_Review');+ assert.strictEqual(read.ok, false);+ assert.match(read.reason, /^the workbook of the export is not readable: the worksheet 'Localized Labels' has an element <ss:Row>/);+});++test('translation workbook: a worksheet, or anything in the sheet, that declares a namespace — or a second prefix for the spreadsheet\u2019s — makes the export unreadable', () => {+ const good = workbookXml({ captions: rows() });+ const sheetTag = '<Worksheet ss:Name="Localized Labels"';+ for (const [what, xml, detail] of [+ ['the sheet rebinds the default namespace', good.replace(sheetTag, '<Worksheet xmlns="urn:example:not-spreadsheet" ss:Name="Localized Labels"'), /worksheet with the attribute xmlns,/],+ ['the sheet rebinds ss:', good.replace(sheetTag, '<Worksheet xmlns:ss="urn:example:other" ss:Name="Localized Labels"'), /worksheet with the attribute xmlns:ss/],+ ['another sheet declares a namespace', good.replace('<Worksheet ss:Name="Information"', '<Worksheet xmlns="urn:example:other" ss:Name="Information"'), /worksheet with the attribute xmlns,/],+ ['the table declares one', good.replace(/(<Worksheet ss:Name="Localized Labels"[^>]*>)<Table>/, '$1<Table xmlns="urn:example:other">'), /a Table has the attribute xmlns/],+ ['a row rebinds ss:', inLabels(`<Row xmlns:ss="urn:example:other">${''}</Row>`), /a Row has the attribute xmlns:ss/],+ ['a Data declares the HTML namespace of rich text', inLabels(`<Row><Cell><Data ss:Type="String" xmlns="http://www.w3.org/TR/REC-html40">x</Data></Cell></Row>`), /a Data has the attribute xmlns/],+ ['the root names the spreadsheet namespace with a second prefix', good.replace('xmlns:o=', `xmlns:s2="${SPREADSHEET_NAMESPACE}" xmlns:o=`), /prefix other than ss: \(xmlns:s2\)/],+ ['the sheet\u2019s options are not in Excel\u2019s namespace', good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">/, `$1<WorksheetOptions xmlns="${SPREADSHEET_NAMESPACE}">`), /WorksheetOptions are not in Excel's namespace/],+ ]) {+ assert.match(refused(xml), detail, what);+ }+});++test('translation workbook: a worksheet the spreadsheet would see is found wherever it is written — prefixed, nested, or named in other letters — and makes the export unreadable', () => {+ const good = workbookXml({ captions: rows() });+ const second = (tag) => good.replace('</Workbook>', `<${tag} ss:Name="Localized Labels"><Table><Row/></Table></${tag.split(' ')[0]}></Workbook>`);+ assert.match(refused(second('ss:Worksheet')), /worksheet that is not where the spreadsheet puts one \(<ss:Worksheet> in Workbook\)/);+ assert.match(refused(second('o:Worksheet')), /<o:Worksheet>/);+ assert.match(refused(good.replace('<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"></DocumentProperties>', '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Worksheet ss:Name="Localized Labels"/></DocumentProperties>')), /<Worksheet> in Workbook\/DocumentProperties/);+ assert.match(refused(good.replace('ss:Name="Information"', 'ss:Name="LOCALIZED LABELS"')), /more than one worksheet named 'Localized Labels'/, 'Excel tells sheet names apart without regard to case');+ assert.match(refused(good.replace('<Worksheet ss:Name="Information"', '<Worksheet x:Name="Localized Labels" ss:Name="Information"')), /worksheet with the attribute x:Name/);+ assert.match(refused(good.replace(/<Worksheet ss:Name="Information" ss:Id="Information"/, '<Worksheet ss:Id="Information"')), /worksheet with no ss:Name/);+});++test('translation workbook: every element and attribute of the sheet is one the platform writes, where and in the order it writes it — or nothing is read', () => {+ const good = workbookXml({ captions: rows() });+ const cells = `<Cell><Data ss:Type="String">new_ticket</Data></Cell><Cell><Data ss:Type="String">${TAB}</Data></Cell><Cell><Data ss:Type="String">displayname</Data></Cell>`;+ for (const [what, xml, detail] of [+ ['an element the sheet does not have, in the table', inLabels('<Names/>'), /has an element <Names>/],+ ['a cell comment', inLabels(`<Row>${cells}<Cell><Data ss:Type="String">x</Data><Comment/></Cell></Row>`), /has an element <Comment>/],+ ['a named cell', inLabels(`<Row>${cells}<Cell><NamedCell ss:Name="x"/></Cell></Row>`), /has an element <NamedCell>/],+ ['an element after the options', good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?<\/WorksheetOptions>)/, '$1<AutoFilter/>'), /has an element <AutoFilter>/],+ ['an element inside an option', good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)<Unsynced \/>/, '$1<Unsynced><Panes/></Unsynced>'), /has an element <Panes>/],+ ['an option inside an option', good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)<Unsynced \/>/, '$1<Unsynced><Selected/></Unsynced>'), /a Selected is not where the spreadsheet puts one/],+ ['a row the spreadsheet places itself (ss:Index)', inLabels(`<Row ss:Index="9">${cells}</Row>`), /a Row has the attribute ss:Index/],+ ['a row that stands for several (ss:Span)', inLabels(`<Row ss:Span="2">${cells}</Row>`), /a Row has the attribute ss:Span/],+ ['a hidden row', inLabels(`<Row ss:Hidden="1">${cells}</Row>`), /a Row has the attribute ss:Hidden/],+ ['a link on a cell', inLabels(`<Row>${cells}<Cell ss:HRef="https://contoso.example/"><Data ss:Type="String">x</Data></Cell></Row>`), /a Cell has the attribute ss:HRef/],+ ['an index with no prefix', inLabels(`<Row>${cells}<Cell Index="5"><Data ss:Type="String">x</Data></Cell></Row>`), /a Cell has the attribute Index/],+ ['an index under another prefix', inLabels(`<Row>${cells}<Cell x:Index="5"><Data ss:Type="String">x</Data></Cell></Row>`), /a Cell has the attribute x:Index/],+ ['a table that counts its rows', good.replace(/(<Worksheet ss:Name="Localized Labels"[^>]*>)<Table>/, '$1<Table ss:ExpandedRowCount="9">'), /a Table has the attribute ss:ExpandedRowCount/],+ ['a column after a row', inLabels('<Column ss:Width="10" />'), /a Column comes after a Row/],+ ['the options before the table', good.replace(/(<Worksheet ss:Name="Localized Labels"[^>]*>)(<Table>[\s\S]*?<\/Table>)(<WorksheetOptions[\s\S]*?<\/WorksheetOptions>)/, '$1$3$2'), /WorksheetOptions are not one element after its Table/],+ ['two sets of options', good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)(<WorksheetOptions[\s\S]*?<\/WorksheetOptions>)/, '$1$2$2'), /WorksheetOptions are not one element after its Table/],+ ['a second worksheet inside the sheet', inLabels('<Worksheet ss:Name="x"/>'), /worksheet that is not where the spreadsheet puts one \(<Worksheet> in Workbook\/Worksheet\/Table\)/],+ ['text between rows', inLabels('<Row/>text'), /text inside <Table>, which holds elements only/],+ ['text in a row, beside its cells', inLabels(`<Row>${cells}Antiguo</Row>`), /text inside <Row>, which holds elements only/],+ ['text in a cell, beside its Data', inLabels(`<Row>${cells}<Cell>Antiguo<Data ss:Type="String">x</Data></Cell></Row>`), /text inside <Cell>, which holds elements only/],+ ['a CDATA section in a row', inLabels('<Row><![CDATA[x]]></Row>'), /a CDATA section inside <Row>/],+ ['a comment in the table', inLabels('<!-- a row was here -->'), /a comment inside <Table>/],+ ['an instruction in a cell', inLabels(`<Row>${cells}<Cell><?p x?></Cell></Row>`), /a processing instruction inside <Cell>/],+ ]) {+ assert.match(refused(xml), detail, what);+ }+ // White space between the elements, as a writer that indents its output puts it, is not text: the sheet reads the same (an empty Data stays empty).+ const indented = parseTranslationWorkbook(good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?<\/Worksheet>)/, (sheet) => sheet.replace(/>(?=<(?!\/Data>))/g, '>\r\n ')));+ assert.strictEqual(indented.ok, true, JSON.stringify(indented));+ assert.deepStrictEqual([...indented.lookup('new_ticket', TAB).texts], [[1033, 'Tab One'], [3082, 'Pestana Uno']]);+ assert.deepStrictEqual([...indented.lookup('new_ticket', OTHER).texts], [[1033, 'Notes'], [3082, '']]);+ // What the platform writes in the options of a sheet it selects is read too.+ const selected = parseTranslationWorkbook(good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)<Unsynced \/>/, '$1<Selected /><Unsynced />'));+ assert.strictEqual(selected.ok, true, JSON.stringify(selected));+});++test('translation workbook: a caption is text — a Number cell in a row makes the export unreadable; the header\u2019s languages may be either', () => {+ const good = workbookXml({ captions: rows() });+ // The probe that found it: a Number cell whose text is a caption, not a number, settled the caption.+ const number = good.replace('<Data ss:Type="String">Pestana Uno</Data>', '<Data ss:Type="Number">Pestana Uno</Data>');+ assert.match(refused(number), /row \d+ has a Number cell, and the cells of a row are text \(String\)/);+ assert.match(refused(inLabels(`<Row><Cell><Data ss:Type="Number">1</Data></Cell><Cell><Data ss:Type="String">${TAB}</Data></Cell><Cell><Data ss:Type="String">displayname</Data></Cell></Row>`)), /has a Number cell/);+ assert.match(refused(replaceLast(good, '<Data ss:Type="String">Object ID</Data>', '<Data ss:Type="Number">Object ID</Data>')), /header of 'Localized Labels' has a Number where it names a column \(Object ID\)/);+ // The header's LCIDs are Numbers as the platform writes them; written as text they name the same language.+ const asText = parseTranslationWorkbook(replaceLast(good, '<Data ss:Type="Number">3082</Data>', '<Data ss:Type="String">3082</Data>'));+ assert.strictEqual(asText.ok, true, JSON.stringify(asText));+ assert.deepStrictEqual(asText.languages, [1033, 3082]);+});++// --- A workbook that would cost more than it is worth is refused WHILE it is read ----------------------------------------------------------------+//+// The strict reader gives every element it answers the names of its ancestors, so a workbook nested thousands deep and asked for at every level costs the+// square of its depth: 6,000 nested worksheets — 138 KB of XML, 819 bytes of zip — took the heap of a process past its limit and ended it, with no answer+// at all. The read is bounded as it goes — by the depth, by the length of a name, by the number of worksheets and of the sheet's elements — and what goes+// over is an export that cannot be read, which leaves the captions unverified.+const nest = (depth, name, inner = '') => `${`<${name}>`.repeat(depth)}${inner}${`</${name}>`.repeat(depth)}`;+const workbookAround = (inner) => `<Workbook xmlns="${SPREADSHEET_NAMESPACE}" xmlns:ss="${SPREADSHEET_NAMESPACE}">${inner}</Workbook>`;++test('translation workbook: a workbook nested deeper than the platform\u2019s, or with a name or a count no export has, is refused as it is read — in a moment', () => {+ const started = Date.now();+ assert.match(refused(workbookAround(nest(6000, 'Worksheet'))), /nested more than 16 levels deep/, 'the probe that ended the process');+ assert.match(refused(workbookAround(nest(6000, 'Style'))), /nested more than 16 levels deep/, 'an element nobody asks for is bounded too');+ assert.match(refused(workbookXml({ captions: rows() }).replace('<Styles>', `<Styles>${nest(15, 'Style')}`)), /nested more than 16 levels deep/);+ assert.match(refused(inLabels(nest(6000, 'Row'))), /nested more than 16 levels deep/, 'the workbook\u2019s bound holds inside the sheet as well');+ assert.match(refused(inLabels(nest(5, 'Row'))), /the worksheet 'Localized Labels' is not read \(elements nested more than 6 levels deep/, 'and the sheet\u2019s own, closer one');+ assert.match(refused(inLabels(`<Row><Cell><Data ss:Type="String">${nest(3, 'Data')}</Data></Cell></Row>`)), /nested more than 6 levels deep|has an element <Data>|is not where/);+ const long = `S${'t'.repeat(64)}`;+ assert.match(refused(workbookXml({ captions: rows() }).replace('<Styles>', `<Styles><${long}/>`)), /an element whose name is longer than 64 characters/);+ assert.match(refused(workbookXml({ captions: rows(), sheetsAfter: '<Worksheet ss:Name="x"><Table/></Worksheet>'.repeat(62) })), /more than 64 worksheets/);+ assert.match(refused(`<Workbook xmlns="${SPREADSHEET_NAMESPACE}" xmlns:ss="${SPREADSHEET_NAMESPACE}"><Styles>${'<Workbook/>'.repeat(5000)}</Styles></Workbook>`), /more than one Workbook element/);+ assert.ok(Date.now() - started < 5000, `${Date.now() - started} ms`);+ // The bounds are above what the platform writes: its depth, its names and its worksheets read as they did.+ const read = parseTranslationWorkbook(workbookXml({ captions: rows(), sheetsAfter: '<Worksheet ss:Name="x"><Table/></Worksheet>'.repeat(61) }).replace('<Styles>', `<Styles>${nest(14, 'Style')}<${'S'.repeat(64)}/>`));+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ assert.strictEqual(read.lookup('new_ticket', TAB).texts.get(3082), 'Pestana Uno');+});++test('readTranslationLabels: a small export nested deep answers "not readable" in a process whose heap is small — it is never the end of the process', () => {+ const { spawnSync } = require('node:child_process');+ const path = require('node:path');+ // In its own process, with a 64 MB heap, so that the failure this guards against — the end of the process — cannot touch the test runner's.+ const script = `+ const { readTranslationLabels } = require(${JSON.stringify(path.join(__dirname, '..', 'lib', 'translation-labels.js'))});+ const { exportZip, exportAnswer, workbookXml, SPREADSHEET_NAMESPACE } = require(${JSON.stringify(path.join(__dirname, 'helpers', 'translation-export.js'))});+ const nest = (depth, name) => ('<' + name + '>').repeat(depth) + ('</' + name + '>').repeat(depth);+ const cases = {+ worksheets: '<Workbook xmlns="' + SPREADSHEET_NAMESPACE + '" xmlns:ss="' + SPREADSHEET_NAMESPACE + '">' + nest(6000, 'Worksheet') + '</Workbook>',+ rows: workbookXml({ captions: [] }).replace(/(<Worksheet ss:Name="Localized Labels"[\\s\\S]*?)(<\\/Table>)/, '$1' + nest(6000, 'Row') + '$2'),+ };+ (async () => {+ const answers = {};+ for (const [name, xml] of Object.entries(cases)) {+ const archive = exportZip(xml);+ const read = await readTranslationLabels({ post: async () => exportAnswer(archive) }, 'Contoso_Review');+ answers[name] = { ok: read.ok, reason: read.reason, zipBytes: archive.length };+ }+ process.stdout.write(JSON.stringify(answers));+ })();+ `;+ const child = spawnSync(process.execPath, ['--max-old-space-size=64', '-e', script], { encoding: 'utf8', timeout: 120000, windowsHide: true });+ assert.strictEqual(child.status, 0, `the process ended with ${child.status} ${child.signal || ''}: ${String(child.stderr).split(/\r?\n/).filter((line) => /FATAL|heap|Error/.test(line)).slice(0, 3).join(' | ')}`);+ const answers = JSON.parse(child.stdout);+ for (const [name, answer] of Object.entries(answers)) {+ assert.strictEqual(answer.ok, false, name);+ assert.match(answer.reason, /^the workbook of the export is not readable: .*nested more than \d+ levels deep/, name);+ assert.ok(answer.zipBytes < 4096, `${name}: a small archive (${answer.zipBytes} bytes)`);+ }+});++test('translation workbook: a large export is read in one pass', () => {+ const many = [];+ for (let i = 0; i < 4000; i += 1) many.push({ entity: 'new_ticket', id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, texts: { 1033: `Caption ${i}`, 3082: `Titulo ${i}` } });+ const read = parseTranslationWorkbook(workbookXml({ captions: many }));+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ assert.strictEqual(read.lookup('new_ticket', '00000000-0000-4000-8000-000000003999').texts.get(3082), 'Titulo 3999');+});++// --- settleCaption: one caption against the export ---------------------------------------------------------------------------------------------++test('settleCaption: the same text is settled, a different one or an empty cell is a difference, and the others are not settled at all', () => {+ const read = parsed();+ const settle = (over) => settleCaption(read, { entity: 'new_ticket', id: TAB, lcid: 3082, text: 'Pestana Uno', ...over });+ assert.deepStrictEqual(settle({}), { state: 'same' });+ assert.deepStrictEqual(settle({ text: 'Pestana Dos' }), { state: 'different', have: 'Pestana Uno', others: [{ lcid: 1033, text: 'Tab One' }] });+ assert.deepStrictEqual(settle({ id: OTHER, text: 'Notas' }), { state: 'different', have: '', others: [{ lcid: 1033, text: 'Notes' }] }, 'an empty cell is a caption that is not there');+ assert.deepStrictEqual(settle({ lcid: 1033, text: 'Tab One' }), { state: 'same' });+ assert.deepStrictEqual(settle({ text: 'pestana uno' }), { state: 'different', have: 'Pestana Uno', others: [{ lcid: 1033, text: 'Tab One' }] }, 'a caption is compared exactly');+ assert.match(settle({ id: '11111111-2222-3333-4444-555555555555' }).why, /no caption row for the tab or section \(id 11111111-2222-3333-4444-555555555555, table new_ticket\)/);+ assert.strictEqual(settle({ id: undefined }).state, 'unsettled');+ assert.match(settle({ id: undefined }).why, /gives a tab or section no id/);+ assert.match(settle({ lcid: 1036 }).why, /no column for language 1036/);+ assert.match(settle({ id: OTHER, what: 'section \'sec_notes\'' }).state, /same|different/);+ assert.match(settle({ id: '11111111-2222-3333-4444-555555555555', what: 'section \'sec_notes\'' }).why, /no caption row for section 'sec_notes' \(id 11111111-2222-3333-4444-555555555555, table new_ticket\)/);+ const twice = parsed({ captions: [...rows(), { entity: 'new_ticket', id: TAB, texts: { 1033: 'again' } }] });+ assert.match(settleCaption(twice, { entity: 'new_ticket', id: TAB, lcid: 3082, text: 'Pestana Uno' }).why, /more than one caption row for the tab or section \(id 0a0a0a0a-0000-4000-8000-000000000001, table new_ticket\)/);+});++// --- readTranslationLabels: the request, the answer and the archive ---------------------------------------------------------------------------++const clientAnswering = (answer, seen = []) => ({ post: async (path, body, options) => { seen.push({ path, body, options }); return typeof answer === 'function' ? answer(path, body) : answer; } });+const workbook = () => workbookXml({ captions: rows() });++test('readTranslationLabels: asks the solutions collection to export the solution\u2019s translations once, and reads the workbook out of the answer', async () => {+ const seen = [];+ const read = await readTranslationLabels(clientAnswering(exportAnswer(exportZip(workbook())), seen), 'Contoso_Tickets');+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ assert.deepStrictEqual(read.languages, [1033, 3082]);+ assert.strictEqual(read.lookup('new_ticket', SECTION).texts.get(3082), 'Detalles');+ assert.strictEqual(seen.length, 1, 'one request');+ assert.match(seen[0].path, EXPORT_PATH);+ assert.strictEqual(seen[0].path, '/solutions/Microsoft.Dynamics.CRM.ExportTranslation', 'bound to the solutions collection — the unbound action answers 404');+ assert.deepStrictEqual(seen[0].body, { SolutionName: 'Contoso_Tickets' });+});++test('readTranslationLabels: an answer it cannot use is a reason, never an exception and never an answer', async () => {+ const good = exportAnswer(exportZip(workbook()));+ const withFile = (file) => ({ status: 200, headers: {}, body: { ExportTranslationFile: file } });+ const failures = [+ ['no client', undefined, /no Dataverse client/],+ ['a client that cannot post', {}, /no Dataverse client/],+ ['a request that fails', { post: async () => { throw new Error('socket hang up'); } }, /socket hang up/],+ ['a request that fails before it returns', { post: () => { throw new Error('refused to send'); } }, /refused to send/],+ ['no answer', clientAnswering(undefined), /no answer/],+ ['a 403 with the platform\u2019s message', clientAnswering({ status: 403, headers: {}, body: { error: { code: '0x80040220', message: 'Principal user is missing prvExportTranslation privilege' } } }), /HTTP 403: Principal user is missing prvExportTranslation privilege/],+ ['a 404', clientAnswering({ status: 404, headers: {}, body: { error: { message: 'Resource not found for the segment' } } }), /HTTP 404: Resource not found for the segment/],+ ['a 500 with no body', clientAnswering({ status: 500, headers: {}, body: undefined }), /HTTP 500/],+ ['a 200 with no file', clientAnswering({ status: 200, headers: {}, body: { '@odata.context': 'x' } }), /ExportTranslationFile/],+ ['a 200 with a body that is text', clientAnswering({ status: 200, headers: {}, body: '<html>sign in</html>' }), /ExportTranslationFile/],+ ['a file that is not text', clientAnswering(withFile(42)), /ExportTranslationFile/],+ ['an empty file', clientAnswering(withFile('')), /ExportTranslationFile/],+ ['a file that is not base64', clientAnswering(withFile('not base64 !!')), /not base64/],+ ['a file with a bad length', clientAnswering(withFile('QUJD=')), /not base64/],+ ['bytes that are no zip', clientAnswering(withFile(Buffer.from('not a zip file at all, only text that goes on').toString('base64'))), /archive of the export is not readable: .*end-of-central-directory/],+ ['a zip without the workbook', clientAnswering(exportAnswer(zipOf([{ name: 'Other.xml', data: '<a/>' }]))), /archive of the export is not readable: .*no entry named 'CrmTranslations\.xml'/],+ ['a workbook that is not XML', clientAnswering(exportAnswer(zipOf([{ name: 'CrmTranslations.xml', data: 'plain text' }]))), /workbook of the export is not readable: .*one XML document/],+ ['a workbook in bytes that are not UTF-8', clientAnswering(exportAnswer(zipOf([{ name: 'CrmTranslations.xml', data: Buffer.from([0x3c, 0x61, 0x3e, 0xff, 0xfe, 0x3c, 0x2f, 0x61, 0x3e]) }]))), /not valid UTF-8/],+ ['a workbook that declares another encoding', clientAnswering(exportAnswer(zipOf([{ name: 'CrmTranslations.xml', data: workbook().replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="utf-16"?>') }]))), /declares the encoding utf-16/],+ ];+ for (const [what, client, reason] of failures) {+ const read = await readTranslationLabels(client, 'Contoso_Tickets');+ assert.strictEqual(read.ok, false, what);+ assert.match(read.reason, reason, what);+ assert.strictEqual(read.lookup, undefined, `${what}: nothing is answered from it`);+ }+ // A solution that is named by no text is not asked about.+ const asked = [];+ for (const name of [undefined, null, '', ' ', 42]) {+ const read = await readTranslationLabels(clientAnswering(good, asked), name);+ assert.strictEqual(read.ok, false, String(name));+ assert.match(read.reason, /no solution name/);+ }+ assert.deepStrictEqual(asked, [], 'no request was made');+});++test('readTranslationLabels: an export larger than it will read is left unread, with the size said — before anything is inflated', async () => {+ const archive = exportZip(workbook());+ const directory = archive.readUInt32LE(archive.length - 22 + 16);+ const huge = 32 * 1024 * 1024 + 1;+ archive.writeUInt32LE(huge, directory + 24);+ archive.writeUInt32LE(huge, 22);+ const read = await readTranslationLabels(clientAnswering(exportAnswer(archive)), 'Contoso_Tickets');+ assert.strictEqual(read.ok, false);+ assert.match(read.reason, /archive of the export is not readable: the entry 'CrmTranslations\.xml' is larger than 33554432 bytes/);+});++test('readTranslationLabels: reads the workbook of an archive with a byte order mark, an XML declaration naming UTF-8, and non-ASCII captions', async () => {+ const text = workbook().replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="UTF-8"?>').replace('Detalles', 'Pesta\u00f1a \u2014 \u65e5\u672c');+ const read = await readTranslationLabels(clientAnswering(exportAnswer(zipOf([{ name: 'CrmTranslations.xml', data: Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(text, 'utf8')]) }]))), 'Contoso_Tickets');+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ assert.strictEqual(read.lookup('new_ticket', SECTION).texts.get(3082), 'Pesta\u00f1a \u2014 \u65e5\u672c');+});++// --- the request is sent once ------------------------------------------------------------------------------------------------------------------++test('isTranslationExport: names the ExportTranslation request of the solutions collection, and no other', () => {+ const base = 'https://contoso.crm.dynamics.com/api/data/v9.2';+ assert.strictEqual(isTranslationExport('POST', `${base}/solutions/Microsoft.Dynamics.CRM.ExportTranslation`), true);+ assert.strictEqual(isTranslationExport('post', 'https://contoso.crm.dynamics.com/api/data/v9.0/solutions/Microsoft.Dynamics.CRM.ExportTranslation'), true);+ for (const [method, url] of [+ ['GET', `${base}/solutions/Microsoft.Dynamics.CRM.ExportTranslation`],+ ['POST', `${base}/ExportTranslation`],+ ['POST', `${base}/solutions/Microsoft.Dynamics.CRM.ImportTranslation`],+ ['POST', `${base}/solutions/Microsoft.Dynamics.CRM.ExportTranslationX`],+ ['POST', `${base}/ExportSolution`],+ ['POST', `${base}/$batch`],+ ['POST', 'not a url'],+ ['POST', undefined],+ ]) assert.strictEqual(isTranslationExport(method, url), false, `${method} ${url}`);+});++test('the translation export is sent exactly once by the plugin\u2019s client — a gateway error ends it, a retry would run a second export of the same solution', async () => {+ const sent = [];+ const request = async (r) => { sent.push(`${r.method} ${r.url}`); return { statusCode: 503, headers: {}, body: JSON.stringify({ error: { message: 'Service Unavailable' } }) }; };+ const once = createAzHttpClient('https://contoso.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {}, sendOnce: isTranslationExport });+ const read = await readTranslationLabels({ post: (path, body) => once.post(`https://contoso.crm.dynamics.com/api/data/v9.2${path}`, body) }, 'Contoso_Tickets');+ assert.strictEqual(read.ok, false);+ assert.match(read.reason, /HTTP 503: Service Unavailable/);+ assert.strictEqual(sent.length, 1, sent.join(' | '));+ // …where the same client, told nothing, sends a throttled or unavailable request again, as it does every other request of the plugin.+ sent.length = 0;+ const usual = createAzHttpClient('https://contoso.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });+ await usual.post('https://contoso.crm.dynamics.com/api/data/v9.2/solutions/Microsoft.Dynamics.CRM.ExportTranslation', { SolutionName: 'x' });+ assert.ok(sent.length > 1, 'the policy is the one the export is taken out of');+});diff --git a/plugins/model-apps/scripts/tests/type-parameter-heads.test.js b/plugins/model-apps/scripts/tests/type-parameter-heads.test.jsindex 17cabdc90..616c29613 100644--- a/plugins/model-apps/scripts/tests/type-parameter-heads.test.js+++ b/plugins/model-apps/scripts/tests/type-parameter-heads.test.js@@ -11,7 +11,7 @@const { test } = require('node:test');const assert = require('node:assert');-const { opensTypeParameters, blankNonCodePreservingTemplateExpressions, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES } = require('../lib/source-literals.js');+const { opensTypeParameters, blankNonCodePreservingTemplateExpressions, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING } = require('../lib/source-literals.js');const { resolvePageRefs, navigationFrontier } = require('../lib/pageref-resolver.js');const { loadTypescriptOracle, loadBaseLexer } = require('./helpers/typescript-oracle.js');const { cleanSourceFile, readingAt, isElement, tokenVocabulary } = require('./helpers/angle-frames.js');@@ -1529,23 +1529,26 @@ test('a class that is complete before a method — the value of a property, the}assert.ok(declared >= 40, `${declared} pages are valid to TypeScript`);t.diagnostic(`${valid} pages with a class value and ${declared} with a declaration valid to TypeScript`);- // What stays as it was: a field named `new` that no `;` and no initializer ends, and a method after it on the next line, read as the operator `new` and an expression; and the same with the `;`.+ // A field named `new` that no `;` and no initializer ends, and a method after it on the next line: the field is the name of a member of the class, no operator, and the braces of the method are its body. The same with the `;`.const element = 'void <span>(MARK); // note</span>;';const field = `class C { new\n render() { ${element} } }\n${CALL};`;assert.ok(cleanSourceFile(ts, field), `TypeScript parses ${visible(field)}`);- assert.ok(guessesOf(field).length > 0, 'a guess is named after a field named `new`');- assert.deepStrictEqual(readPage(field).rewritten, [], 'and the call after it is not rewritten');+ assert.deepStrictEqual(guessesOf(field), [], 'no guess after a field named `new`');+ assert.ok(!readsAsCode(field), 'the text of the element is text');+ assert.strictEqual(readPage(field).rewritten.length, 1, 'and the call after it is rewritten');const ended = `class C { new;\n render() { ${element} } }\n${CALL};`;assert.deepStrictEqual(guessesOf(ended), [], 'no guess where a `;` ends the field');assert.strictEqual(readPage(ended).rewritten.length, 1);- // A class whose own base is a class expression has the braces of the base inside its head: the braces of the class are the second, after a `}`, and the scan does not read that head back across them. The guess side, never a block.+ // A class whose own base is a class expression has the braces of the base inside its head: the braces of the class are the second, after a `}`. The head is read back across the first, as the head of a class that is complete, and the braces of the method after it are its body.for (const nested of [`const registry = { Adapter: class extends class {} {}, render() { ${element} } };\n${CALL};`, `class Q extends class {} {}\nfunction implements() { ${element} }\n${CALL};`]) {assert.ok(cleanSourceFile(ts, nested), `TypeScript parses ${visible(nested)}`);- assert.ok(guessesOf(nested).length > 0, `a guess is named: ${visible(nested)}`);- assert.deepStrictEqual(readPage(nested).rewritten, [], `and the call after it is not rewritten: ${visible(nested)}`);+ assert.deepStrictEqual(guessesOf(nested), [], `no guess: ${visible(nested)}`);+ assert.ok(!readsAsCode(nested), `the text of the element is text: ${visible(nested)}`);+ assert.strictEqual(readPage(nested).rewritten.length, 1, `and the call after it is rewritten: ${visible(nested)}`);}// A run of members whose braces the scan crosses one after the other (as many as the window of 2,000 characters holds): it reads the head of each braces that it meets, and none of them twice. A scan that read the heads of all the braces before them for each would take time that doubles with every member.- for (const [what, member, length] of [['methods', (k) => `m${k}() { return ${k}; }`, 60], ['properties with a class', (k) => `p${k}: class extends B${k} {}`, 60], ['methods with a call in the head', (k) => `m${k}(a = f(${k})) { return a; }`, 45]]) {+ for (const [what, member, length] of [['methods', (k) => `m${k}() { return ${k}; }`, 60], ['properties with a class', (k) => `p${k}: class extends B${k} {}`, 60], ['methods with a call in the head', (k) => `m${k}(a = f(${k})) { return a; }`, 45],+ ['properties with a class whose base is a class expression', (k) => `p${k}: class extends class B${k} {} {}`, 40], ['methods with a class whose base is a class expression between them', (k) => (k % 3 === 0 ? `p${k}: class extends class {} {}` : `m${k}() { return ${k}; }`), 60]]) {const run = `const registry = {\n ${Array.from({ length }, (unused, k) => member(k)).join(',\n ')},\n render() { ${element} }\n};\n${CALL};`;assert.ok(cleanSourceFile(ts, run), `TypeScript parses a run of ${what}`);const started = Date.now();@@ -1564,3 +1567,168 @@ test('a class that is complete before a method — the value of a property, theassert.ok(!/<span>\(MARK/.test(maskOf(code)), `${visible(heritage)}: the element in the body of a method is text`);}});++// ─── A class whose base is a class expression, and a field named `new` ──────────────────────────────────────────────────────────────────────────────────++// A class expression in the head of a class has its braces inside the head, so the braces of the class come after a `}` (`{ a: class extends class {} {}, m() { … } }`). The head is read back across them, as the head of a class that is complete is, and the braces of the method after it are its body,+// where an element is read for certain. So it is for a base that is an element of `implements`, one after a comma or after `new`, with members, decorators and type parameters of its own, and for a chain of them: no more than HEAD_NESTING deep.+const NESTED_BASE_HEADS = ['class extends class {}', 'class extends class A {}', 'class A extends class B {}', 'class extends class extends B {}', 'class extends class extends class {} {}', 'class extends class {} implements I', 'class implements class {}', 'class extends A implements class {}', 'class extends A implements class {}, class {}',+ 'class extends class {}, class {}', 'class extends class {}.x', 'class extends class {}()', 'class extends class {}!', 'class extends new class {}', 'class extends new @d class {}', 'class extends class { m() { return class {}; } }', 'class extends class Named<T> extends Base<T> implements I {}', 'class extends class implements I {}',+ 'class extends class<T> {}', 'class extends class\n{}', 'class\nextends\nclass\n{}', 'class extends class /* c */ {} /* d */', 'class extends class {}\n.x', 'class implements class {}, class {}, class {}, class {}, class {}, class {}, class {}', `${'class extends '.repeat(HEAD_NESTING)}class {}${' {}'.repeat(HEAD_NESTING - 1)}`];+const NESTED_BASE_FRAMES = [+ ['the value of a property', (head, n, b) => `const registry = { Adapter: ${head} {}, ${n}() { ${b} } };`], ['a property between the class and the method', (head, n, b) => `const registry = { Adapter: ${head} {}, label: 'x', ${n}() { ${b} } };`],+ ['the value of a property in an argument', (head, n, b) => `register({ Adapter: ${head} {}, ${n}() { ${b} } });`], ['two classes', (head, n, b) => `const registry = { A: ${head} {}, B: ${head} {}, ${n}() { ${b} } };`],+ ['the value of a property in a class', (head, n, b) => `class Host { make() { return { adapter: ${head} {}, ${n}() { ${b} } }; } }`], ['the initializer of a field', (head, n, b) => `class Host { adapter = ${head} {}\n ${n}() { ${b} } }`],+ ['a generator after the value', (head, n, b) => `const registry = { Adapter: ${head} {}, *${n}() { ${b} } };`], ['an async method after the value', (head, n, b) => `const registry = { Adapter: ${head} {}, async ${n}() { ${b} } };`],+ ['a declaration before a function', (head, n, b) => `${head} {}\nfunction ${n}() { ${b} }`], ['a declaration and a comment before a function', (head, n, b) => `${head} {} // note\nfunction ${n}() { ${b} }`], ['an expression before a function', (head, n, b) => `const Adapter = ${head} {}\nfunction ${n}() { ${b} }`],+];+test('a class whose base is a class expression, as the value before a method, the initializer of a field or a declaration before a function, has its head read back across the braces of the base: the braces of the method after it are its body, and an element in it is read for certain', (t) => {+ const ts = loadTypescriptOracle();+ if (!ts) return t.skip(SKIP);+ const bodies = ['void <span>(MARK); // details</span>;', 'return <>(MARK) // details</>;', 'return <span>(MARK) // detail</span>;', 'x;\nvoid <span>(MARK); // note</span>;'];+ let valid = 0;+ for (const head of NESTED_BASE_HEADS) {+ for (const [place, frame] of NESTED_BASE_FRAMES) {+ for (const name of ['render', 'implements', 'extends']) {+ for (const body of bodies) {+ const code = `${frame(head, name, body)}\n${CALL};`;+ if (!cleanSourceFile(ts, code)) continue;+ valid += 1;+ const label = `${place} / ${visible(head)} / ${name} / ${visible(body)}`;+ assert.deepStrictEqual(guessesOf(code), [], `${label}: no guess`);+ assert.ok(!readsAsCode(code), `${label}: the text of the element is text`);+ assert.strictEqual(readPage(code).rewritten.length, 1, `${label}: the call after it is rewritten`);+ }+ }+ }+ }+ assert.ok(valid >= 1000, `${valid} pages are valid to TypeScript`);+ t.diagnostic(`${valid} pages valid to TypeScript`);+ // The braces of the class itself hold members, wherever the class stands: a method named like an operator that has type parameters is code after such a head, and the closing tag of its type parameter in the note after it is data.+ let members = 0;+ for (const head of NESTED_BASE_HEADS) {+ for (const wrap of [(c) => c, (c) => `const o = { a: ${c}, b: 1 };`, (c) => `function f() { ${c} }`, (c) => `const K = ${c};`, (c) => `class H { a = ${c} }`, (c) => `f(${c});`]) {+ const code = pageOf(wrap(`${head} { delete<U>(y: U): MARK {} }`), 'U');+ if (!cleanSourceFile(ts, code)) continue;+ members += 1;+ assertRead(code, 'exact', visible(head));+ assert.ok(readsAsCode(code), `${visible(head)}: the method is code`);+ }+ }+ assert.ok(members >= 100, `${members} pages are valid to TypeScript`);+});++test('a class whose base is a class expression and a field named `new` leave as they were what they never resolved: a function expression or an object literal in a head, type arguments after the base, a chain that is deeper than HEAD_NESTING, a `new` that no member of a class begins', (t) => {+ const ts = loadTypescriptOracle();+ if (!ts) return t.skip(SKIP);+ const element = 'void <span>(MARK); // note</span>;';+ const chain = (depth) => `${'class extends '.repeat(depth)}class {}${' {}'.repeat(depth)}`;+ // The braces of a function expression or an object literal in a head have no `class` of their own, and a class read back across them would take the `class` of the head for theirs; type arguments after the base are the guess `brace` of the `}` before them. A `new` that is no+ // field — an operator on a line of its own in a function, a property that a field's initializer ends in, a private name — has no member of a class begin at it, and a class whose head is not read leaves its field named `new` where it was.+ const refused = [+ ['a function expression for the base', `const registry = { Adapter: class extends function () {} {}, render() { ${element} } };`], ['an async function expression for the base', `const registry = { Adapter: class extends async function () {} {}, render() { ${element} } };`],+ ['an object literal for the base', `const registry = { Adapter: class extends {} {}, render() { ${element} } };`], ['a function expression after a class expression', `const registry = { Adapter: class extends class {}, function () {} {}, render() { ${element} } };`],+ ['a declaration with a function expression for the base', `class Q extends function () {} {}\nfunction implements() { ${element} }`], ['type arguments after the base', `const registry = { Adapter: class extends class {}<T> {}, render() { ${element} } };`],+ [`${HEAD_NESTING + 1} bases, one in the head of the other`, `const registry = { Adapter: ${chain(HEAD_NESTING + 1)}, render() { ${element} } };`],+ ['a field named `new` in a class whose base is a function expression', `class C extends function () {} { new\n m() { ${element} } }`], ['a field named `new` in a class whose base is an object literal', `class C extends {} { new\n m() { ${element} } }`],+ ['an operator `new` and a block on the next line', `function g() {\n new Foo()\n { ${element} }\n}`], ['an operator `new` that a line break separates from its name, and a block', `function g() {\n new\n Foo()\n { ${element} }\n}`],+ ['a property named `new` that ends a field\'s initializer', `class C { a = x.new\n render() { ${element} } }`], ['a private field named `new`', `class C { #new\n render() { ${element} } }`],+ ];+ for (const [what, text] of refused) {+ const code = `${text}\n${CALL};`;+ assert.ok(cleanSourceFile(ts, code), `TypeScript parses ${what}`);+ assert.ok(guessesOf(code).length > 0, `${what}: a guess is named`);+ assert.deepStrictEqual(readPage(code).rewritten, [], `${what}: the call after it is not rewritten`);+ }+ // A chain of HEAD_NESTING bases is read, and so is a long list of class expressions that are no more than one deep.+ for (const [what, text] of [[`${HEAD_NESTING} bases, one in the head of the other`, `const registry = { Adapter: ${chain(HEAD_NESTING)}, render() { ${element} } };`], ['seven class expressions in a list', `const registry = { Adapter: class implements ${Array(7).fill('class {}').join(', ')} {}, render() { ${element} } };`]]) {+ const code = `${text}\n${CALL};`;+ assert.ok(cleanSourceFile(ts, code), `TypeScript parses ${what}`);+ assert.deepStrictEqual(guessesOf(code), [], `${what}: no guess`);+ assert.strictEqual(readPage(code).rewritten.length, 1, `${what}: the call after it is rewritten`);+ }+});++// A field named `new` that a line break ends is the name of a member, and the call on the next line is the head of a method, whose braces are its body: an element there is read for certain. After `extends`, `implements` or a comma of a heritage list the same words are the operator and an element+// of the list, whose braces hold members. What stands before the `new` tells them apart: a member of a class begins at the field — after the start of the body, a separator, a modifier or a decorator — and no keyword or comma of a heritage list is before it.+const NEW_FIELDS = ['new', 'static new', 'readonly new', 'declare new', 'public new', 'private new', 'protected new', 'abstract new', 'accessor new', 'override new', '@d new', '@d() new', '@a.b new', 'static readonly new', '@d static new'];+const NEW_FIELD_PLACES = [+ ['a class', (f, m) => `class C { ${f}\n ${m} }`], ['a class expression', (f, m) => `const K = class { ${f}\n ${m} };`], ['a class that extends a name', (f, m) => `class C extends B { ${f}\n ${m} }`], ['a class that extends a call', (f, m) => `class C extends mixin(A) { ${f}\n ${m} }`],+ ['a class that extends new', (f, m) => `class C extends new X() { ${f}\n ${m} }`], ['a class that implements a call after a comma', (f, m) => `class C implements A, B() { ${f}\n ${m} }`], ['an abstract class', (f, m) => `abstract class C { ${f}\n ${m} }`],+ ['a class in a function', (f, m) => `function g() { class C { ${f}\n ${m} } }`], ['the class of a property', (f, m) => `const o = { k: class { ${f}\n ${m} }, l() { x; } };`], ['a class whose base is a class expression', (f, m) => `class C extends class {} { ${f}\n ${m} }`],+ ['a class after a member', (f, m) => `class C { a() {}\n ${f}\n ${m} }`], ['a class after a field', (f, m) => `class C { a = 1;\n ${f}\n ${m} }`], ['a class after a static block', (f, m) => `class C { static { x; }\n ${f}\n ${m} }`],+ // What ends the member before the field, with no `;`: a name, a type, a modifier mark, a call, a bracket, a literal, a regex, a postfix operator and another field named `new`.+ ['a class after a field with no `;`', (f, m) => `class C { a = 1\n ${f}\n ${m} }`], ['a class after a typed field', (f, m) => `class C { a: string\n ${f}\n ${m} }`], ['a class after an optional field', (f, m) => `class C { a?: string\n ${f}\n ${m} }`], ['a class after a definite field', (f, m) => `class C { a!: string\n ${f}\n ${m} }`],+ ['a class after a call', (f, m) => `class C { a = g()\n ${f}\n ${m} }`], ['a class after an array', (f, m) => `class C { a = [1]\n ${f}\n ${m} }`], ['a class after a string', (f, m) => `class C { a = 'x'\n ${f}\n ${m} }`], ['a class after a template', (f, m) => `class C { a = \`x\`\n ${f}\n ${m} }`],+ ['a class after a regex', (f, m) => `class C { a = /x/\n ${f}\n ${m} }`], ['a class after an increment', (f, m) => `class C { a = x++\n ${f}\n ${m} }`], ['a class after a static field', (f, m) => `class C { static a\n ${f}\n ${m} }`], ['a class after a field named `new`', (f, m) => `class C { new\n ${f}\n ${m} }`],+ ['a comment before the line break', (f, m) => `class C { ${f} // c\n ${m} }`], ['a comment that holds the line break', (f, m) => `class C { ${f} /* c\n */ ${m} }`], ['a CR LF', (f, m) => `class C { ${f}\r\n ${m} }`], ['the initializer of a field', (f, m) => `class H { a = class C { ${f}\n ${m} } }`],+];+const AFTER_NEW_FIELD = ['m() { B }', 'static m() { B }', 'async m() { B }', '*m() { B }', 'get m() { B }', 'set m(v) { B }', 'implements() { B }', 'extends() { B }', 'new() { B }', 'constructor() { B }', 'x = 1\n m() { B }', '@d m() { B }'];+test('a class expression whose own head holds the braces of an object literal or of a function expression is no class that is complete: the heritage that holds it is read as it was, and the braces after the call that ends its list hold members', (t) => {+ const ts = loadTypescriptOracle();+ if (!ts) return t.skip(SKIP);+ // The braces of an object literal or a function expression have no `class` of their own: a head that holds them is read to no `class`, and the `class` of the head that holds it is not theirs. A scan that took one for the other found the keyword of the outer class behind the+ // braces, took the inner class for a class that is complete, and read the comma after it back to the start of the source: a heritage that no list was found in, and the braces after the call that ends it for a function's body.+ const heritages = ['class A extends class extends {} {}, mixin(A)', 'class A extends B, class extends { a: 1 } {}, mixin(A)', 'class A extends class extends function () {} {}, mixin(A)', 'class A implements class extends {} {}, B()', 'class A extends class B extends class C extends {} {} {}, mixin(A)',+ 'class A extends class extends async function () {} {}, mixin(A)', 'class A extends class extends {} {} implements (B)', 'class A extends new class extends {} {}, mixin(A)', 'class A extends class<T> extends { a: 1 } {}.x, mixin(A)', 'class A extends class extends {} {}, class extends {} {}, mixin(A)',+ 'class A extends class extends B {}, class extends {} {}, mixin(A)', 'class A extends class implements class extends {} {} {}, mixin(A)', 'class A extends new @d class extends {} {}, mixin(A)'];+ let valid = 0;+ for (const heritage of heritages) {+ for (const wrap of [(c) => c, (c) => `const o = { a: ${c}, b: 1 };`, (c) => `function f() { ${c} }`, (c) => `class H { a = ${c} }`, (c) => `f(${c});`]) {+ const code = pageOf(wrap(`${heritage} { delete<U>(y: U): MARK {} }`), 'U');+ if (!cleanSourceFile(ts, code)) continue;+ valid += 1;+ assertRead(code, 'exact', visible(heritage));+ assert.ok(readsAsCode(code), `${visible(heritage)}: the method is code`);+ }+ }+ assert.ok(valid >= 40, `${valid} pages are valid to TypeScript`);+ t.diagnostic(`${valid} pages valid to TypeScript`);+});++test('a field named `new` that a line break ends, whatever modifier or decorator it has and wherever its class stands, is no operator: the braces of the method after it are its body, and an element in it is read for certain', (t) => {+ const ts = loadTypescriptOracle();+ if (!ts) return t.skip(SKIP);+ const bodies = ['void <span>(MARK); // details</span>;', 'return <>(MARK) // details</>;', 'x;\nvoid <span>(MARK); // note</span>;', 'const e = <in U>(MARK); // note</in>;'];+ let valid = 0;+ for (const field of NEW_FIELDS) {+ for (const [place, frame] of NEW_FIELD_PLACES) {+ for (const method of AFTER_NEW_FIELD) {+ for (const body of bodies) {+ const code = `${frame(field, method.replace('B', body))}\n${CALL};`;+ if (!cleanSourceFile(ts, code)) continue;+ valid += 1;+ const label = `${place} / ${visible(field)} / ${visible(method)} / ${visible(body)}`;+ assert.deepStrictEqual(guessesOf(code), [], `${label}: no guess`);+ assert.ok(!readsAsCode(code), `${label}: the text of the element is text`);+ assert.strictEqual(readPage(code).rewritten.length, 1, `${label}: the call after it is rewritten`);+ }+ }+ }+ }+ assert.ok(valid >= 1500, `${valid} pages are valid to TypeScript`);+ t.diagnostic(`${valid} pages valid to TypeScript`);+});++test('the operator `new` of an element of a heritage list, with line breaks around it and after the keyword or the comma, is no field: the braces after its call hold members, in a class too, where a member begins after the keyword that a line break follows', (t) => {+ const ts = loadTypescriptOracle();+ if (!ts) return t.skip(SKIP);+ const heritages = CLASS_HERITAGES.filter((heritage) => /\bnew\b/.test(heritage));+ assert.ok(heritages.length >= 20, `${heritages.length} heritages with a new`);+ let valid = 0;+ for (const heritage of heritages) {+ // The braces of a class around the head are where a field named `new` stands, and after `implements` and a line break a member may begin as far as the line break is concerned; the keyword and the comma are what the field's reading must look at.+ for (const [place, wrap] of [['no wrap', (c) => c], ['a field\'s initializer', (c) => `class H { a = ${c} }`], ['a field\'s initializer after a field', (c) => `class H { b = 1\n a = ${c} }`], ['a static field\'s initializer', (c) => `class H { static a = ${c} }`],+ ['the value of a property in a class', (c) => `class H { make() { return { a: ${c}, b: 1 }; } }`], ['a function', (c) => `function f() { ${c} }`]]) {+ for (const member of ['delete<T>(x: MARK): void {}', 'void<T>(x: MARK): void {}', 'a = 1;\n delete<T>(x: MARK): void {}']) {+ const code = pageOf(wrap(`${heritage} { ${member} }`), 'T');+ if (!cleanSourceFile(ts, code)) continue;+ valid += 1;+ assertRead(code, 'exact', `${place} / ${visible(heritage)} / ${visible(member)}`);+ assert.ok(readsAsCode(code), `${place} / ${visible(heritage)} / ${visible(member)}: the method is code`);+ }+ }+ }+ assert.ok(valid >= 200, `${valid} pages are valid to TypeScript`);+ t.diagnostic(`${valid} pages valid to TypeScript`);+});diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.jsindex 5a997148b..b01fbc485 100644--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js@@ -5,10 +5,13 @@ const os = require('node:os');const fs = require('node:fs');const path = require('node:path');const vm = require('node:vm');+const { spawnSync } = require('node:child_process');const { readerFor, appIdFor } = require('../verify-model-app.js');const { verifySpec } = require('../lib/verify-spec.js');const { validateFlagsFromParsed } = require('./helpers/fake-auth.js');const { appSpec, column, nameColumn } = require('./helpers/column-gate-specs.js');+const dashboardReads = require('./helpers/dashboard-two-language-reads.js');+const { workbookXml, exportZip, exportAnswer } = require('./helpers/translation-export.js');const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';@@ -334,7 +337,7 @@ function loadVerifyCli({ parseResult, validateResult = { ok: true }, verifyResulevents.push({ type: 'readJsonArg', arg });return specObject || { app: { name: 'Support Desk' }, solution: { publisherPrefix: 'new' } };},- emitResult: (ok, payload) => events.push({ type: 'emitResult', ok, payload }),+ emitResult: (ok, payload, options) => events.push({ type: 'emitResult', ok, payload, options }),// Pure, so the real one — the CLI uses it to identify the environment's baseline.dataverseOrigin: require('../lib/dataverse-auth.js').dataverseOrigin,// Pure as well: the `--language-code` flag, read the way the build reads it.@@ -342,8 +345,9 @@ function loadVerifyCli({ parseResult, validateResult = { ok: true }, verifyResul};}if (id === './lib/sdk-http-client.js') {- // One client is made for the run; the page backend must be given that same one (its token is shared), so each is recorded.- return { createAzHttpClient: (env) => { const client = { env }; events.push({ type: 'createAzHttpClient', client }); return client; } };+ // One client is made for the run; the page backend must be given that same one (its token is shared), so each is recorded — with what it was made with, which is how a test+ // can tell the one request the run sends only once (the translation export).+ return { createAzHttpClient: (env, deps) => { const client = { env }; events.push({ type: 'createAzHttpClient', client, deps }); return client; } };}if (!realGates && id === './lib/verify-spec.js') {return {@@ -576,12 +580,13 @@ const spanishFormSpec = (over = {}) => ({tabs: [{ name: 'tab_main', label: 'Resumen', sections: [{ name: 'sec_main', label: 'Detalles', columns: 1, fields: ['new_name'] }] }] }],...over,});-// The published form as a read returns it, with the captions `tab` and `section` (each `<label …/>` markup).-const spanishFormXml = ({ tab, section }) => `<form><tabs><tab id="{1}" name="tab_main" expanded="true" visible="true"><labels>${tab}</labels><columns><column width="100%"><sections>`- + `<section id="{2}" name="sec_main" showlabel="true" visible="true" columns="1"><labels>${section}</labels><rows><row><cell id="{3}"><control id="new_name" classid="{4273EDBD-AC1D-40D3-9FB2-095C621B552D}" datafieldname="new_name" /></cell></row></rows></section>`+// The published form as a read returns it, with the captions `tab` and `section` (each `<label …/>` markup), and the ids the tab and the section have in the FormXML.+const spanishFormXml = ({ tab, section, ids = { tab: '{1}', section: '{2}' } }) => `<form><tabs><tab id="${ids.tab}" name="tab_main" expanded="true" visible="true"><labels>${tab}</labels><columns><column width="100%"><sections>`+ + `<section id="${ids.section}" name="sec_main" showlabel="true" visible="true" columns="1"><labels>${section}</labels><rows><row><cell id="{3}"><control id="new_name" classid="{4273EDBD-AC1D-40D3-9FB2-095C621B552D}" datafieldname="new_name" /></cell></row></rows></section>`+ '</sections></column></columns></tab></tabs><DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions></form>';const englishLabels = { tab: '<label description="Overview" languagecode="1033" />', section: '<label description="Basics" languagecode="1033" />' };-const formSdk = (formxml) => () => ({+// `post` is the SDK's Dataverse client's `post`, which a translation export is asked for through: with none, the SDK has no client that can ask.+const formSdk = (formxml, { post } = {}) => () => ({initWorkspace: async () => {},findTables: async () => [{ logicalName: 'new_ticket' }],findColumns: async () => [{ logicalName: 'new_name' }],@@ -595,20 +600,21 @@ const formSdk = (formxml) => () => ({if (/RetrieveFilteredForms/.test(String(p))) return { status: 200, body: { value: [{ formid: SPANISH_FORM_ID }] } };return { status: 200, body: { value: [] } };},+ ...(post ? { post } : {}),},});-const runSpanishVerify = async (flags, { spec = spanishFormSpec(), labels = englishLabels } = {}) => {+const runSpanishVerify = async (flags, { spec = spanishFormSpec(), labels = englishLabels, ids, post } = {}) => {const harness = loadVerifyCli({parseResult: { positional: [], flags: { ...SPEC_FLAGS, ...flags } },realGates: true,specObject: spec,- sdkFactory: formSdk(spanishFormXml(labels)),+ sdkFactory: formSdk(spanishFormXml({ ...labels, ...(ids ? { ids } : {}) }), { post }),});await harness.main();return { harness, emitted: harness.events.find((e) => e.type === 'emitResult') };};-test('verify CLI over a form read that carries only English — --language-code 3082, --languageCode 3082 and a spec pin — lists the Spanish captions unverified and exits clean', async () => {+test('verify CLI over a form read that carries only English — --language-code 3082, --languageCode 3082 and a spec pin — lists the Spanish captions unverified and exits clean, whose translation export cannot be asked for', async () => {for (const [what, flags, spec] of [['--language-code 3082', { 'language-code': '3082' }, spanishFormSpec()],['--languageCode 3082', { languageCode: '3082' }, spanishFormSpec()],@@ -621,13 +627,90 @@ test('verify CLI over a form read that carries only English — --language-codeassert.deepStrictEqual(emitted.payload.missing, [], `${what}: no caption is reported missing`);assert.strictEqual(emitted.payload.present, emitted.payload.total, what);assert.strictEqual(emitted.payload.unverified.length, 1, `${what}: ${JSON.stringify(emitted.payload.unverified)}`);- assert.match(emitted.payload.unverified[0], /^form-labels:new_ticket\.Main \(the labels of tab 'tab_main', section 'sec_main' in language 3082 were not compared: the environment's form read returns labels only in 1033, so labels written in 3082 cannot be read back from it\. Check them in Power Apps with that language, or verify in a language the read carries\)$/, what);+ assert.match(emitted.payload.unverified[0], /^form-labels:new_ticket\.Main \(the labels of tab 'tab_main', section 'sec_main' in language 3082 were not compared: the environment's form read returns labels only in 1033, so labels written in 3082 cannot be read back from it\. A translation export of solution 'FormProbe' could not be read \(the SDK has no Dataverse client that can post a translation export request\)\. Check them in Power Apps with that language, or verify in a language the read carries\)$/, what);assert.match(stderr, /✓ verify PASS/, what);assert.match(stderr, /⊘ 1 check could not be verified — it is neither passed nor failed/, what);assert.ok(stderr.includes(`⊘ ${emitted.payload.unverified[0]}`), `${what}: the entry is named, with its reason`);}});+// The form's tab and section as the platform keeps them: GUIDs, in braces and capitals as a classic form writes them, and the export that has the Spanish captions of both.+const SPANISH_IDS = { tab: '{0A0A0A0A-0000-4000-8000-000000000001}', section: '{0A0A0A0A-0000-4000-8000-000000000002}' };+const spanishExport = (over = {}) => exportAnswer(exportZip(workbookXml({ captions: [+ { entity: 'new_ticket', id: SPANISH_IDS.tab.slice(1, -1).toLowerCase(), texts: { 1033: 'Overview', 3082: 'Resumen', ...(over.tab || {}) } },+ { entity: 'new_ticket', id: SPANISH_IDS.section.slice(1, -1).toLowerCase(), texts: { 1033: 'Basics', 3082: 'Detalles', ...(over.section || {}) } },+] })));++test('verify CLI settles the Spanish captions from ONE translation export asked for through the SDK\'s Dataverse client — the run passes with nothing left unverified', async () => {+ for (const [what, flags, spec] of [+ ['--language-code 3082', { 'language-code': '3082' }, spanishFormSpec()],+ ['languageCode pinned in the spec', {}, spanishFormSpec({ languageCode: 3082 })],+ ]) {+ const asked = [];+ const { harness, emitted } = await runSpanishVerify(flags, { spec, ids: SPANISH_IDS, post: async (p, body) => { asked.push({ p, body }); return spanishExport(); } });+ assert.strictEqual(emitted.ok, true, `${what}: ${JSON.stringify(emitted.payload)}`);+ assert.deepStrictEqual(emitted.payload.missing, [], what);+ assert.ok(!('unverified' in emitted.payload), `${what}: the export settled both captions`);+ assert.deepStrictEqual(asked, [{ p: '/solutions/Microsoft.Dynamics.CRM.ExportTranslation', body: { SolutionName: 'FormProbe' } }], `${what}: one request, to the bound action`);+ assert.doesNotMatch(harness.stderr.join(''), /⊘/, what);+ }+ // A caption the export shows differently fails the run, by name.+ const stale = await runSpanishVerify({ 'language-code': '3082' }, { ids: SPANISH_IDS, post: async () => spanishExport({ tab: { 3082: 'Antiguo' } }) });+ assert.strictEqual(stale.emitted.ok, false);+ assert.match(stale.emitted.payload.missing[0], /^form-topology:new_ticket\.Main \(deployed layout does not match the authored one — tab 'tab_main' is deployed with label "Antiguo" in language 3082 \(the translation export of solution 'FormProbe' shows it; the form read does not carry language 3082\), the spec declares label: "Resumen" in language 3082\)$/);+ assert.match(stale.harness.stderr.join(''), /✗ verify FAIL — 1 missing/);+ assert.ok(!('unverified' in stale.emitted.payload));+});++test('verify CLI lists the captions unverified, and exits clean, when the translation export fails — the reason is in the entry', async () => {+ const refused = await runSpanishVerify({ 'language-code': '3082' }, { ids: SPANISH_IDS, post: async () => ({ status: 403, headers: {}, body: { error: { message: 'Principal user is missing prvExportTranslation privilege' } } }) });+ assert.strictEqual(refused.emitted.ok, true, JSON.stringify(refused.emitted.payload));+ assert.strictEqual(refused.emitted.payload.unverified.length, 1);+ assert.match(refused.emitted.payload.unverified[0], /A translation export of solution 'FormProbe' could not be read \(HTTP 403: Principal user is missing prvExportTranslation privilege\)\. Check them in Power Apps/);+ assert.match(refused.harness.stderr.join(''), /✓ verify PASS/);+ const thrown = await runSpanishVerify({ 'language-code': '3082' }, { ids: SPANISH_IDS, post: async () => { throw new Error('socket hang up'); } });+ assert.strictEqual(thrown.emitted.ok, true);+ assert.match(thrown.emitted.payload.unverified[0], /could not be read \(the request failed: socket hang up\)/);+ // A form read that carries the language asks for no export.+ let asked = 0;+ const carries = await runSpanishVerify({ 'language-code': '3082' }, { ids: SPANISH_IDS, post: async () => { asked += 1; return spanishExport(); }, labels: { tab: '<label description="Overview" languagecode="1033" /><label description="Resumen" languagecode="3082" />', section: '<label description="Basics" languagecode="1033" /><label description="Detalles" languagecode="3082" />' } });+ assert.strictEqual(carries.emitted.ok, true);+ assert.strictEqual(asked, 0);+});++test('verify CLI makes its HTTP client send the translation export once — and nothing else differently', async () => {+ const { harness } = await runSpanishVerify({ 'language-code': '3082' });+ const clients = harness.events.filter((e) => e.type === 'createAzHttpClient');+ assert.strictEqual(clients.length, 1, 'one client for the run');+ const { sendOnce } = clients[0].deps;+ assert.strictEqual(typeof sendOnce, 'function');+ const base = 'https://org.example/api/data/v9.2';+ assert.strictEqual(sendOnce('POST', `${base}/solutions/Microsoft.Dynamics.CRM.ExportTranslation`), true, 'a long action: a re-send would run it twice');+ for (const [method, url] of [['GET', `${base}/systemforms`], ['POST', `${base}/$batch`], ['POST', `${base}/ExportSolution`], ['PATCH', `${base}/systemforms(1)`]]) {+ assert.strictEqual(sendOnce(method, url), false, `${method} ${url} keeps the client's usual retry`);+ }+});++test('readerFor.translationLabels asks the SDK\'s Dataverse client for ONE export of the named solution, and answers { ok, languages, lookup } — or why it cannot', async () => {+ const calls = [];+ const sdk = {+ queryRecords: async () => [],+ dataverse: { post: async (p, body, options) => { calls.push({ p, body, options }); return spanishExport(); } },+ };+ const read = readerFor(sdk, 'contoso_app', {});+ const answer = await read.translationLabels('Contoso_Tickets');+ assert.strictEqual(answer.ok, true, JSON.stringify(answer));+ assert.deepStrictEqual(answer.languages, [1033, 3082]);+ assert.strictEqual(answer.lookup('new_ticket', SPANISH_IDS.tab).texts.get(3082), 'Resumen');+ assert.deepStrictEqual(calls.map(({ p, body }) => ({ p, body })), [{ p: '/solutions/Microsoft.Dynamics.CRM.ExportTranslation', body: { SolutionName: 'Contoso_Tickets' } }]);+ // Not kept between asks: the export is the published layer, and a later verify must see it change.+ await read.translationLabels('Contoso_Tickets');+ assert.strictEqual(calls.length, 2);+ assert.deepStrictEqual(await readerFor({ queryRecords: async () => [] }, 'contoso_app', {}).translationLabels('Contoso_Tickets'), { ok: false, reason: 'the SDK has no Dataverse client that can post a translation export request' });+ const refused = await readerFor({ queryRecords: async () => [], dataverse: { post: async () => ({ status: 404, headers: {}, body: { error: { message: 'Resource not found for the segment \'ExportTranslation\'.' } } }) } }, 'contoso_app', {}).translationLabels('Contoso_Tickets');+ assert.deepStrictEqual(refused, { ok: false, reason: 'HTTP 404: Resource not found for the segment \'ExportTranslation\'.' });+});+test('verify CLI compares the Spanish captions strictly when the read carries them — a stale one still fails the run', async () => {const spanishToo = (tab) => ({tab: `<label description="Overview" languagecode="1033" /><label description="${tab}" languagecode="3082" />`,@@ -732,9 +815,9 @@ test('verify CLI accepts a positional spec, leaves the default workspace alone,assert.ok(!harness.events.some((e) => e.type === 'mkdirSync' && e.dir === defaultWorkspace), 'the default workspace is not created');});-test('verify CLI still verifies an older colliding spec and names the holder', async () => {- // Dropping relationshipCollisions: 'warn' makes validateAppSpec refuse this spec before any- // read. The relationship line is the proof verification actually ran.+// An older spec whose 1:N and N:N relationships share a schema name, over an environment that holds the 1:N: what verify must still read (the collision+// is a warning for it, an error everywhere else) and then fail on, naming the holder.+async function verifyCollidingSpec() {const specObject = {solution: { uniqueName: 'Contoso', publisherPrefix: 'contoso' },app: { name: 'Projects', uniqueName: 'contoso_projects' },@@ -774,8 +857,13 @@ test('verify CLI still verifies an older colliding spec and names the holder', a});await harness.main();- const stderr = harness.stderr.join('');- const emitted = harness.events.find((e) => e.type === 'emitResult');+ return { stderr: harness.stderr.join(''), emitted: harness.events.find((e) => e.type === 'emitResult') };+}++test('verify CLI still verifies an older colliding spec and names the holder', async () => {+ // Dropping relationshipCollisions: 'warn' makes validateAppSpec refuse this spec before any+ // read. The relationship line is the proof verification actually ran.+ const { stderr, emitted } = await verifyCollidingSpec();assert.match(stderr, /WARNING:.*both use the schema name 'contoso_project_contoso_task'/);assert.match(stderr, /exists as 1:N contoso_project -> contoso_task \(lookup contoso_projectid\), not as the declared N:N/);assert.ok(emitted && Array.isArray(emitted.payload.missing), 'a validation refusal returns errors and never a missing list');@@ -787,12 +875,13 @@ test('verify CLI still verifies an older colliding spec and names the holder', a// "recommended". Verification creates and updates nothing and only reads whether each column exists, so the spec of an app an earlier release built — an// AutoNumber column made as plain text, a `required: "true"` made not required — must still reach the deployment. The CLI passes columnValues: 'warn', as it// passes relationshipCollisions: 'warn': the findings are warnings that name the column and the fix, and the verdict is the deployment's.-async function verifyOlderSpec(specObject) {+async function verifyOlderSpec(specObject, harnessOptions = {}) {const reads = [];const harness = loadVerifyCli({parseResult: { positional: [], flags: { env: 'https://contoso.crm.dynamics.com', spec: '@app-spec.json', workspace: 'D:\\Projects\\_temp\\verify-older-spec' } },realGates: true,specObject,+ ...harnessOptions,sdkFactory: () => ({initWorkspace: async () => {},findTables: async () => { reads.push('tables'); return [{ logicalName: 'new_ticket' }]; },@@ -870,6 +959,248 @@ test('verify CLI still refuses a spec that is invalid for another reason — befassert.deepStrictEqual(reads, [], 'nothing was read');});+// --- the result JSON carries what stderr warns -----------------------------------------------------------------------------------------+// A person reads the `WARNING:` lines verify prints, but a caller that reads only the JSON result — a skill, a pipeline — lost them. The result's optional+// `warnings` array holds the same messages, without the prefix and in the order they were printed, and is left out when there is none, as `unverified` is.+// The result is compared as the process prints it (a JSON round trip): the CLI runs in a context of its own, whose arrays are not this one's.+const printedWarnings = (stderr) => stderr.split('\n').filter((line) => line.startsWith('WARNING: ')).map((line) => line.slice('WARNING: '.length));+const resultOf = (emitted) => JSON.parse(JSON.stringify(emitted.payload));+const AUTONUMBER_WARNING = 'entity new_ticket: column new_ref is an AutoNumber column but its autoNumberFormat is missing — give it a format such as "C-{SEQNUM:5}", or use type "Text" for a plain text column';++test('verify CLI puts the warning it prints for an older spec into the result JSON, and moves no other field', async () => {+ for (const [label, parts, finding] of OLDER_SPECS) {+ const { emitted, stderr } = await verifyOlderSpec(appSpec(parts));+ const result = resultOf(emitted);+ assert.strictEqual(emitted.ok, true, `${label}: ${JSON.stringify(result)}`);+ assert.deepStrictEqual(result.warnings, [`entity new_ticket: ${finding}`], `${label}: the result carries the warning, naming the column and the fix`);+ assert.deepStrictEqual(result.warnings, printedWarnings(stderr), `${label}: it is the very line stderr printed`);+ assert.ok(stderr.includes(`WARNING: entity new_ticket: ${finding}\n`), `${label}: and stderr keeps its line`);+ assert.deepStrictEqual(result, { ok: true, present: result.total, total: result.total, missing: [], errors: [], warnings: result.warnings }, `${label}: no other field moved`);+ }+});++test('verify CLI lists every warning of an older spec in the result, in the order of the lines on stderr', async () => {+ const spec = appSpec({+ columns: [column({ type: 'AutoNumber', required: 'true' }), column({ schemaName: 'new_status', type: 'Text', required: null })],+ primaryAttribute: nameColumn({ required: 'ApplicationRequired' }),+ });+ const { emitted, stderr } = await verifyOlderSpec(spec);+ const printed = printedWarnings(stderr);+ assert.strictEqual(printed.length, 4, stderr);+ assert.deepStrictEqual(resultOf(emitted).warnings, printed);+});++test('verify CLI leaves `warnings` out of the result when it warned of nothing — the result is what it always was', async () => {+ const spec = appSpec({ columns: [column({ type: 'AutoNumber', autoNumberFormat: 'C-{SEQNUM:5}', required: 'recommended' })], primaryAttribute: nameColumn({ required: false }) });+ const { emitted, stderr } = await verifyOlderSpec(spec);+ const result = resultOf(emitted);+ assert.ok(!/WARNING:/.test(stderr), stderr);+ assert.ok(!('warnings' in result), JSON.stringify(result));+ assert.deepStrictEqual(result, { ok: true, present: result.total, total: result.total, missing: [], errors: [] });+});++test('verify CLI that fails for another reason still carries its warnings — the colliding spec names the holder in `missing` and the collision in `warnings`', async () => {+ const { stderr, emitted } = await verifyCollidingSpec();+ const result = resultOf(emitted);+ assert.strictEqual(emitted.ok, false);+ assert.ok(result.missing.some((m) => /not as the declared N:N/.test(m)), JSON.stringify(result));+ assert.deepStrictEqual(result.errors, result.missing, '`errors` is still the alias of `missing`');+ assert.strictEqual(result.warnings.length, 1, JSON.stringify(result.warnings));+ assert.match(result.warnings[0], /both use the schema name 'contoso_project_contoso_task'/);+ assert.deepStrictEqual(result.warnings, printedWarnings(stderr));+});++test('a failing verdict carries the warnings beside the fields it always had', async () => {+ const missing = { kind: 'view', name: 'new_ticket.Open Tickets', present: false };+ const harness = loadVerifyCli({+ parseResult: { positional: [], flags: SPEC_FLAGS },+ validateResult: { ok: true, warnings: ['first warning', 'second warning'] },+ verifyResult: { ok: false, checks: [{ kind: 'entity', name: 'new_ticket', present: true }, missing], missing: [missing] },+ });+ await harness.main();+ const emitted = harness.events.find((e) => e.type === 'emitResult');+ assert.strictEqual(emitted.ok, false);+ assert.deepStrictEqual(resultOf(emitted), {+ ok: false, present: 1, total: 2, missing: ['view:new_ticket.Open Tickets'], errors: ['view:new_ticket.Open Tickets'], warnings: ['first warning', 'second warning'],+ });+ assert.ok(harness.stderr.join('').includes('WARNING: first warning\nWARNING: second warning\n'), 'stderr keeps its lines');+});++test('verify CLI reports `warnings` and `unverified` independently — each only when it has something to say', async () => {+ const unverified = ["form-labels:new_ticket.Ticket Main (the label of tab 'tab_overview' was not compared)"];+ const warnings = ['column new_ref needs a format'];+ const run = async (specWarnings, notDecided) => {+ const harness = loadVerifyCli({+ parseResult: { positional: [], flags: SPEC_FLAGS },+ validateResult: { ok: true, warnings: specWarnings },+ verifyResult: { ok: true, checks: [{ kind: 'entity', name: 'new_ticket', present: true }], missing: [], ...(notDecided ? { unverified: notDecided } : {}) },+ });+ await harness.main();+ return resultOf(harness.events.find((e) => e.type === 'emitResult'));+ };+ const base = { ok: true, present: 1, total: 1, missing: [], errors: [] };+ assert.deepStrictEqual(await run(warnings, unverified), { ...base, unverified, warnings });+ assert.deepStrictEqual(await run(warnings, null), { ...base, warnings });+ assert.deepStrictEqual(await run([], unverified), { ...base, unverified });+ assert.deepStrictEqual(await run(undefined, null), base, 'a validation that reports no list of warnings at all is no warning');+});++test('verify CLI puts the page workspace warning into the result JSON, after the spec\'s own', async () => {+ const left = 'C:\\temp\\genpage-x1y2z3';+ const stuck = `the page workspace could not be removed, so page source may be left on disk: ${left} — delete the folder by hand`;+ const disposeOutcome = { left: [left] };++ const alone = await verifyOlderSpec(appSpec({ columns: [column({ type: 'Text' })] }), { disposeOutcome });+ const aloneResult = resultOf(alone.emitted);+ assert.deepStrictEqual(aloneResult.warnings, [stuck], 'the run succeeded, with a page workspace left on disk');+ assert.strictEqual(alone.emitted.ok, true, 'it does not fail the run');+ assert.deepStrictEqual(printedWarnings(alone.stderr), [stuck], 'stderr says the same');+ assert.deepStrictEqual(aloneResult, { ok: true, present: aloneResult.total, total: aloneResult.total, missing: [], errors: [], warnings: [stuck] });++ const both = await verifyOlderSpec(appSpec({ columns: [column({ type: 'AutoNumber' })] }), { disposeOutcome });+ assert.deepStrictEqual(resultOf(both.emitted).warnings, [AUTONUMBER_WARNING, stuck], 'the spec\'s warning was found first, and the workspace is known last');+ assert.deepStrictEqual(printedWarnings(both.stderr), [AUTONUMBER_WARNING, stuck], 'in the order stderr printed them');++ const clean = await verifyOlderSpec(appSpec({ columns: [column({ type: 'Text' })] }), { disposeOutcome: { left: [] } });+ assert.ok(!('warnings' in resultOf(clean.emitted)), 'nothing left on disk, nothing to warn of');+});++test('verify CLI refuses an invalid spec with the warnings it found beside the errors, and prints them too', async () => {+ const spec = appSpec({ columns: [column({ type: 'AutoNumber' }), column({ schemaName: 'new_bad', type: 'Nope' })] });+ const { reads, emitted, stderr } = await verifyOlderSpec(spec);+ assert.strictEqual(emitted.ok, false);+ assert.deepStrictEqual(resultOf(emitted), { ok: false, errors: ["entity new_ticket: column new_bad has unknown type 'Nope'"], warnings: [AUTONUMBER_WARNING] });+ assert.deepStrictEqual(printedWarnings(stderr), [AUTONUMBER_WARNING], 'the refusal prints what the result carries');+ assert.deepStrictEqual(reads, [], 'nothing was read');+});++test('verify CLI refuses an invalid spec that has nothing to warn of with the result it always had, and prints no warning', async () => {+ const spec = appSpec({ columns: [column({ schemaName: 'new_bad', type: 'Nope' })] });+ const { reads, emitted, stderr } = await verifyOlderSpec(spec);+ assert.strictEqual(emitted.ok, false);+ assert.deepStrictEqual(resultOf(emitted), { ok: false, errors: ["entity new_ticket: column new_bad has unknown type 'Nope'"] });+ assert.ok(!/WARNING:/.test(stderr), stderr);+ assert.deepStrictEqual(reads, []);+});++test('verify CLI that stops on an unexpected error still prints its warnings on stderr, and prints no JSON — as before', async () => {+ const harness = loadVerifyCli({+ parseResult: { positional: [], flags: SPEC_FLAGS },+ validateResult: { ok: true, warnings: ['a spec warning'] },+ sdkThrows: new Error('SDK unavailable'),+ invokeAsMain: true,+ });+ await harness.settle();+ const emitted = harness.events.find((e) => e.type === 'emitResult');+ assert.strictEqual(emitted.ok, false);+ assert.match(emitted.payload.message, /SDK unavailable/);+ assert.ok(!('warnings' in emitted.payload), 'the failure is the error itself: there is no JSON result to add the field to');+ assert.ok(harness.stderr.join('').includes('WARNING: a spec warning\n'), 'the line a person reads is still printed');+});++// --- the script as a process: what a caller that reads only stdout gets, what a person reads on stderr, and the exit status ---------------------------------------+// stdout comes back as the bytes the process wrote, because the console that captures it decodes them with a code page of its own (Windows PowerShell 5.1 reads a child's stdout as+// OEM text); stderr as text. The spec is a file the run makes and removes. A refused spec needs no environment; `fake` (FAKE_VERIFY, helpers/fake-verify-preload.js) lets a+// verification complete without one — the real script, validation, throwaway workspace and printer over a fake verification.+const FAKE_VERIFY_PRELOAD = path.join(__dirname, 'helpers', 'fake-verify-preload.js');+function runVerifyProcess(spec, fake) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-process-'));+ try {+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec));+ const run = spawnSync(process.execPath, [+ ...(fake ? ['--require', FAKE_VERIFY_PRELOAD] : []),+ path.join(__dirname, '..', 'verify-model-app.js'), '--env', 'https://contoso.crm.dynamics.com', '--spec', `@${specPath}`,+ ], {+ timeout: 60000,+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1', ...(fake ? { FAKE_VERIFY: JSON.stringify(fake) } : {}) },+ });+ if (run.error) throw run.error;+ return { status: run.status, stdout: run.stdout, stderr: run.stderr.toString('utf8') };+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+}++test('verify-model-app as a process prints the warnings in the JSON of a refused spec, the same lines on stderr, and exits 1', () => {+ const run = runVerifyProcess(appSpec({ columns: [column({ type: 'AutoNumber' }), column({ schemaName: 'new_bad', type: 'Nope' })] }));+ assert.strictEqual(run.status, 1, run.stderr);+ assert.deepStrictEqual(JSON.parse(run.stdout.toString('utf8')), {+ ok: false,+ errors: ["entity new_ticket: column new_bad has unknown type 'Nope'"],+ warnings: [AUTONUMBER_WARNING],+ });+ assert.deepStrictEqual(printedWarnings(run.stderr), [AUTONUMBER_WARNING]);+});++// --- the JSON result is pure ASCII ------------------------------------------------------------------------------------------------------------------------------------+// An agent reads verify's stdout off a console, and Windows PowerShell 5.1 decodes a child's stdout with the OEM code page: the UTF-8 bytes of an em dash arrive as three other+// characters, and a Japanese form name or a Spanish label as others still — in a warning that names them, in a `missing` entry, anywhere. Every character above U+007E is a+// `\uXXXX` escape instead (`emitResult`'s `ascii` option, as in the scripts an agent already reads off a console): the same JSON to any parser, and nothing a code page can garble.+// stderr is for people and is not escaped.+const JAPANESE_FORM = '\u65e5\u5831';+const FORM_WARNING = `form '${JAPANESE_FORM}': prune: false has no effect on an auto layout \u2014 an auto layout is already additive and never removes a field`;+// An AutoNumber column with no format (an em dash in its warning) and a form with a Japanese name that asks for an effect an auto layout cannot have (the name in its warning).+const nonAsciiSpec = (moreColumns = []) => ({+ ...appSpec({ columns: [column({ type: 'AutoNumber' }), ...moreColumns] }),+ forms: [{ entity: 'new_ticket', name: JAPANESE_FORM, layout: 'auto', prune: false, notes: false }],+});+const isAscii = (bytes) => bytes.every((byte) => byte < 0x80);++test('verify CLI asks emitResult for pure ASCII on every JSON result it prints — a passed verdict, a failed one and a refused spec', async () => {+ const missing = { kind: 'view', name: 'new_ticket.Open Tickets', present: false };+ const run = async (options) => {+ const harness = loadVerifyCli({ parseResult: { positional: [], flags: SPEC_FLAGS }, ...options });+ await harness.main();+ return harness.events.find((e) => e.type === 'emitResult');+ };+ const passed = await run({});+ assert.strictEqual(passed.ok, true);+ assert.ok(passed.options && passed.options.ascii === true, 'a passed verdict');+ const failed = await run({ verifyResult: { ok: false, checks: [{ kind: 'entity', name: 'new_ticket', present: true }, missing], missing: [missing] } });+ assert.strictEqual(failed.ok, false);+ assert.ok(failed.options && failed.options.ascii === true, 'a failed verdict');+ const refused = await run({ validateResult: { ok: false, errors: ['entities must be a non-empty array'] } });+ assert.strictEqual(refused.ok, false);+ assert.ok(refused.options && refused.options.ascii === true, 'a refused spec');+});++test('verify-model-app as a process prints the JSON of a refused spec as pure ASCII that reads back as the original text, and leaves stderr as it was written', () => {+ const run = runVerifyProcess(nonAsciiSpec([column({ schemaName: 'new_bad', type: 'Nop\u00e9' })]));+ assert.strictEqual(run.status, 1, run.stderr);+ assert.ok(isAscii(run.stdout), `every byte of stdout is ASCII: ${run.stdout.toString('utf8')}`);+ const asText = run.stdout.toString('latin1');+ assert.strictEqual(asText, run.stdout.toString('utf8'), 'so the code page that decodes it does not matter');+ assert.ok(asText.includes('\\u2014') && asText.includes('\\u65e5\\u5831') && asText.includes('\\u00e9'), 'a character beyond ASCII is an escape, not itself');+ assert.deepStrictEqual(JSON.parse(asText), {+ ok: false,+ errors: ["entity new_ticket: column new_bad has unknown type 'Nop\u00e9'"],+ warnings: [AUTONUMBER_WARNING, FORM_WARNING],+ });+ assert.deepStrictEqual(printedWarnings(run.stderr), [AUTONUMBER_WARNING, FORM_WARNING], 'the lines a person reads carry the characters themselves');+});++test('verify-model-app as a process prints the JSON of a completed verification as pure ASCII — a warning, a missing check, an unverified one and a page workspace with Spanish, Japanese and em-dash text read back as themselves', () => {+ const left = 'C:\\Users\\Jos\u00e9\\AppData\\Local\\Temp\\genpage-x1y2z3';+ const absent = { kind: 'form-labels', name: 'new_ticket.Principal', detail: 'la etiqueta de la pesta\u00f1a "Descripci\u00f3n" no est\u00e1 \u2014 \u65e5\u5831' };+ const unverified = ['form-labels:new_ticket.Ventas (la etiqueta "Cr\u00e9dito" no se compar\u00f3)'];+ const warnings = [AUTONUMBER_WARNING, FORM_WARNING, `the page workspace could not be removed, so page source may be left on disk: ${left} \u2014 delete the folder by hand`];+ for (const ok of [true, false]) {+ const checks = [{ kind: 'entity', name: 'new_ticket', present: true }, ...(ok ? [] : [{ ...absent, present: false }])];+ const run = runVerifyProcess(nonAsciiSpec(), { result: { ok, checks, missing: ok ? [] : [absent], unverified }, left: [left] });+ assert.strictEqual(run.status, ok ? 0 : 1, `ok=${ok}: ${run.stderr}`);+ assert.ok(isAscii(run.stdout), `ok=${ok}: every byte of stdout is ASCII: ${run.stdout.toString('utf8')}`);+ const asText = run.stdout.toString('latin1');+ assert.strictEqual(asText, run.stdout.toString('utf8'), `ok=${ok}: so the code page that decodes it does not matter`);+ const escapes = ['\\u2014', '\\u65e5\\u5831', '\\u00e9', ...(ok ? [] : ['\\u00f1'])];+ assert.ok(escapes.every((escape) => asText.includes(escape)), `ok=${ok}: a character beyond ASCII is an escape, not itself: ${asText}`);+ const missing = ok ? [] : ['form-labels:new_ticket.Principal (la etiqueta de la pesta\u00f1a "Descripci\u00f3n" no est\u00e1 \u2014 \u65e5\u5831)'];+ assert.deepStrictEqual(JSON.parse(asText), { ok, present: 1, total: ok ? 1 : 2, missing, errors: missing, unverified, warnings }, `ok=${ok}: the same document, decoded`);+ assert.deepStrictEqual(printedWarnings(run.stderr), warnings, `ok=${ok}: stderr carries the characters themselves`);+ assert.ok(run.stderr.includes(` \u2298 ${unverified[0]}\n`), `ok=${ok}: and so does the unverified line`);+ }+});+test('verify CLI entrypoint converts SDK startup errors into emitResult failures', async () => {const harness = loadVerifyCli({parseResult: {@@ -1272,8 +1603,10 @@ const DASH_SPEC = { solution: { publisherPrefix: 'new' }, app: { name: 'Field Oppersonas: [{ persona: 'Dispatcher', jobs: [{ name: 'Watch the field', surfaces: ['Field Ops Overview'] }] }] };// An SDK whose published read of the dashboard answers `published` and whose saved read answers `draft` — or, from the third read on// (the bracket's second pair), `laterPublished` / `laterDraft` / `laterVersion` when given. `chartOwner` is the table a tile's chart-// belongs to. `owners` records each read of a tile's chart and view, which is the tile check running.-function dashboardLayers({ published, draft, laterPublished, laterDraft, laterVersion, chartOwner = 'new_workorder' }) {+// belongs to. `owners` records each read of a tile's chart and view, which is the tile check running. `version` is the saved read's+// `@odata.etag`, and `publishedVersion` the published row's (a row that carries none, as in the reads above, when it is not given);+// `laterPublishedVersion` is the row's from the third read on.+function dashboardLayers({ published, draft, laterPublished, laterDraft, laterVersion, version = 'W/"1"', publishedVersion, laterPublishedVersion, chartOwner = 'new_workorder' }) {let reads = 0;const owners = [];const fetches = [];@@ -1285,7 +1618,8 @@ function dashboardLayers({ published, draft, laterPublished, laterDraft, laterVequeryRecords: async (set, o) => {if (set === 'systemform' && o && o.select && o.select.includes('formxml')) {reads += 1;- return [{ formid: 'dash-1', formxml: laterPublished !== undefined && reads > 2 ? laterPublished : published }];+ const token = reads > 2 && laterPublishedVersion !== undefined ? laterPublishedVersion : publishedVersion;+ return [{ formid: 'dash-1', formxml: laterPublished !== undefined && reads > 2 ? laterPublished : published, ...(token === undefined ? {} : { '@odata.etag': token }) }];}if (set === 'systemform') return [{ formid: 'dash-1', name: 'Field Ops Overview' }];if (set === 'savedqueryvisualization') { owners.push(set); return [{ primaryentitytypecode: chartOwner }]; }@@ -1297,7 +1631,7 @@ function dashboardLayers({ published, draft, laterPublished, laterDraft, laterVeassert.strictEqual(url, '/systemforms(dash-1)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml');reads += 1;const later = reads > 2;- return { status: 200, body: { formxml: later && laterDraft !== undefined ? laterDraft : draft, '@odata.etag': later && laterVersion ? laterVersion : 'W/"1"' } };+ return { status: 200, body: { formxml: later && laterDraft !== undefined ? laterDraft : draft, '@odata.etag': later && laterVersion ? laterVersion : version } };} },fetchArtifact: async (type, id) => { fetches.push([type, id]); },getArtifact: async () => ({ components: DASH_TILES }),@@ -1403,43 +1737,47 @@ test('readerFor + verifySpec: on two layers in two languages, a dashboard that c});// The same two reads through the REAL bundle: the reader's own reads and the SDK's deserializer, over a stub of the HTTP client. What-// the reader hands verify is the tiles the SDK reads out of the saved layer — here the live shape, a 3082 caption in every cell.-test('readerFor REAL BUNDLE: the tiles of a published dashboard whose saved read carries a second language are read, and a real change is refused', async (t) => {+// the reader hands verify is the tiles the SDK reads out of the saved layer. `publishedVersion` is the published row's `@odata.etag`+// when given (the row answers none otherwise) and `version` the saved layer's; `reads` is the order the stub was asked in.+async function readDashboardThroughRealBundle(t, id, published, draft, { publishedVersion, version = 'W/"7"' } = {}) {const { createMakerSdk, createNodeWorkspaceStorage } = require(path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs'));- const id = '33333333-0000-4000-8000-000000000001';- const run = async (published, draft) => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-dash-layers-'));- t.after(() => fs.rmSync(dir, { recursive: true, force: true }));- const reads = [];- const ok = (body) => ({ status: 200, headers: {}, body });- const httpClient = {- get: async (url) => {- const u = decodeURIComponent(url);- if (/EntityDefinitions\(LogicalName='systemform'\)/.test(u)) return ok({ EntitySetName: 'systemforms' });- if (u.includes(`/systemforms(${id})/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml`) && !u.includes(',')) {- reads.push('saved formxml');- return ok({ formxml: draft, '@odata.etag': 'W/"7"' });- }- if (u.includes(`/systemforms(${id})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`)) {- reads.push('the SDK\u2019s fetch');- return ok({ formid: id, name: 'Field Ops Overview', description: null, formxml: draft, type: 0, objecttypecode: 'none', componentstate: 1, '@odata.etag': 'W/"7"' });- }- if (/\/systemforms\?/.test(u) && u.includes(`formid eq ${id}`)) {- reads.push('published formxml');- return ok({ value: [{ formid: id, formxml: published }] });- }- assert.fail(`unexpected GET ${u}`);- },- post: async (url) => assert.fail(`unexpected POST ${url}`),- patch: async (url) => assert.fail(`unexpected PATCH ${url}`),- put: async (url) => assert.fail(`unexpected PUT ${url}`),- delete: async (url) => assert.fail(`unexpected DELETE ${url}`),- };- const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });- await sdk.initWorkspace();- const settled = await readerFor(sdk, 'new_fieldops', {}).dashboardComponents(id).then((tiles) => ({ tiles }), (error) => ({ error }));- return { ...settled, reads };+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-dash-layers-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const reads = [];+ const ok = (body) => ({ status: 200, headers: {}, body });+ const httpClient = {+ get: async (url) => {+ const u = decodeURIComponent(url);+ if (/EntityDefinitions\(LogicalName='systemform'\)/.test(u)) return ok({ EntitySetName: 'systemforms' });+ if (u.includes(`/systemforms(${id})/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml`) && !u.includes(',')) {+ reads.push('saved formxml');+ return ok({ formxml: draft, '@odata.etag': version });+ }+ if (u.includes(`/systemforms(${id})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`)) {+ reads.push('the SDK\u2019s fetch');+ return ok({ formid: id, name: 'Field Ops Overview', description: null, formxml: draft, type: 0, objecttypecode: 'none', componentstate: 1, '@odata.etag': version });+ }+ if (/\/systemforms\?/.test(u) && u.includes(`formid eq ${id}`)) {+ reads.push('published formxml');+ return ok({ value: [{ ...(publishedVersion === undefined ? {} : { '@odata.etag': publishedVersion }), formid: id, formxml: published }] });+ }+ assert.fail(`unexpected GET ${u}`);+ },+ post: async (url) => assert.fail(`unexpected POST ${url}`),+ patch: async (url) => assert.fail(`unexpected PATCH ${url}`),+ put: async (url) => assert.fail(`unexpected PUT ${url}`),+ delete: async (url) => assert.fail(`unexpected DELETE ${url}`),};+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await sdk.initWorkspace();+ const settled = await readerFor(sdk, 'new_fieldops', {}).dashboardComponents(id).then((tiles) => ({ tiles }), (error) => ({ error }));+ return { ...settled, reads };+}++// Here the live shape of the first language pair: a 3082 caption in every cell of the saved read.+test('readerFor REAL BUNDLE: the tiles of a published dashboard whose saved read carries a second language are read, and a real change is refused', async (t) => {+ const id = '33333333-0000-4000-8000-000000000001';+ const run = (published, draft) => readDashboardThroughRealBundle(t, id, published, draft);const live = await run(PUBLISHED_DASHBOARD, withCellCaptionsIn(PUBLISHED_DASHBOARD));assert.ifError(live.error);assert.deepStrictEqual(live.tiles.map((c) => [c.type, c.name, c.parameters.TargetEntityType, c.parameters.ViewId, c.parameters.VisualizationId]), [@@ -1455,6 +1793,147 @@ test('readerFor REAL BUNDLE: the tiles of a published dashboard whose saved readassert.deepStrictEqual(moved.reads, ['published formxml', 'saved formxml']);});+// ── A dashboard read by a user whose own language is the organization's second one ───────────────────────────────────────────────+// Live, the published read of such a user carries both languages, the user's own first, and words one caption another way than the saved+// layer does — while the published row and the saved layer are at the very same version (`@odata.etag`) and nothing has written either.+// A read is the platform's projection for its reader, so the two texts cannot say whether the saved layer is the published row; the version+// can, and verify takes it for that (lib/formxml-layers.js) — for the captions alone: the tiles must still be the same. The reads are the live+// ones (helpers/dashboard-two-language-reads.js), the published row's version and the saved layer's the same token, or not.+const { BASE_LANGUAGE_USER, SECOND_LANGUAGE_USER, ROW_VERSION, MOVED_VERSION, cellOf, swapFirstTwoCells } = dashboardReads;+const AT_ROW_VERSION = { publishedVersion: ROW_VERSION, version: ROW_VERSION };+const AFTER_A_SAVE = { publishedVersion: ROW_VERSION, version: MOVED_VERSION };++test('readerFor + verifySpec: a published dashboard read by a user whose own language is the second one verifies — its tiles are checked, and its job passes with it', async () => {+ const { published, saved } = SECOND_LANGUAGE_USER;+ const sdk = dashboardLayers({ published, draft: saved, ...AT_ROW_VERSION });+ const r = await verifySpec(DASH_SPEC, readerFor(sdk, 'new_fieldops', {}));+ const check = r.checks.find((c) => c.kind === 'dashboard');+ assert.deepStrictEqual([check.present, check.detail], [true, '']);+ assert.deepStrictEqual(sdk.fetches, [['dashboard', 'dash-1']], 'the tiles were read');+ assert.deepStrictEqual(sdk.owners, ['savedqueryvisualization', 'savedquery', 'savedqueryvisualization', 'savedquery'], 'and each chart tile\u2019s chart and view were checked');+ assert.deepStrictEqual(r.checks.filter((c) => c.kind === 'job-surface'), [], 'the job whose surface the dashboard is passes with it');+ // It is still the tiles that decide: a chart tile cross-wired to another table fails over the same two reads.+ const crossed = await dashboardVerify({ published, draft: saved, ...AT_ROW_VERSION, chartOwner: 'new_customer' });+ assert.strictEqual(crossed.check.present, false);+ assert.match(crossed.check.detail, /chart tile 'By Priority' shows new_workorder, but its chart belongs to new_customer/);+ assert.match(crossed.jobs[0] && crossed.jobs[0].detail, /surface "Field Ops Overview" is not deployed \(Field Ops Overview\)/);+ // A published row that answers no version has no word to give: the two reads are compared by their text alone, as they were, and differ.+ const noVersion = await dashboardVerify({ published, draft: saved, version: ROW_VERSION });+ assert.strictEqual(noVersion.check.present, false);+ assert.match(noVersion.check.detail, NOT_PUBLISHED);+});++test('readerFor + verifySpec: a dashboard saved and not published after its publish is not published, for a user of either language', async () => {+ for (const [user, { published, saved }] of [['a base-language user', BASE_LANGUAGE_USER], ['a second-language user', SECOND_LANGUAGE_USER]]) {+ for (const [what, draft] of [+ ['a tile moved', swapFirstTwoCells(saved)],+ ['a tile\u2019s view changed', saved.replace(`<ViewId>${DASH_VIEW_CRITICAL}</ViewId>`, `<ViewId>${DASH_VIEW_GOLD}</ViewId>`)],+ ['a tile\u2019s table changed', saved.replace('<TargetEntityType>new_customer</TargetEntityType>', '<TargetEntityType>new_workorder</TargetEntityType>')],+ ['a 1033 caption changed', saved.replace('description="By Priority" languagecode="1033"', 'description="By Owner" languagecode="1033"')],+ ['a 1033 caption removed', saved.replace('<label description="By Status" languagecode="1033" />', '')],+ ]) {+ assert.notStrictEqual(draft, saved, `${user}: ${what}`);+ const sdk = dashboardLayers({ published, draft, ...AFTER_A_SAVE });+ const r = await verifySpec(DASH_SPEC, readerFor(sdk, 'new_fieldops', {}));+ const check = r.checks.find((c) => c.kind === 'dashboard');+ assert.strictEqual(check.present, false, `${user}: ${what}`);+ assert.match(check.detail, NOT_PUBLISHED, `${user}: ${what}`);+ assert.deepStrictEqual(sdk.fetches, [], `${user}: ${what}: no tile is read`);+ assert.strictEqual(r.checks.filter((c) => c.kind === 'job-surface').length, 1, `${user}: ${what}: the job fails with its dashboard`);+ }+ }+ // A second-language caption alone: the base-language user's published read carries none, so it is not seen (the documented limit, as since the+ // first fix); the second-language user's read carries them, so it is a change.+ const pedidos = (xml) => xml.replace('description="Work Orders" languagecode="3082"', 'description="Pedidos" languagecode="3082"');+ const base = await dashboardVerify({ published: BASE_LANGUAGE_USER.published, draft: pedidos(BASE_LANGUAGE_USER.saved), ...AFTER_A_SAVE });+ assert.deepStrictEqual([base.check.present, base.check.detail], [true, '']);+ const second = await dashboardVerify({ published: SECOND_LANGUAGE_USER.published, draft: pedidos(SECOND_LANGUAGE_USER.saved), ...AFTER_A_SAVE });+ assert.strictEqual(second.check.present, false);+ assert.match(second.check.detail, NOT_PUBLISHED);+});++test('readerFor + verifySpec: for a user of the base language the dashboard check is as it was, whatever versions the two reads carry', async () => {+ const { published, saved } = BASE_LANGUAGE_USER;+ for (const [what, versions] of [+ ['a published row that answers no version', {}],+ ['one version on both layers', AT_ROW_VERSION],+ ['a saved layer written since the publish, a second language\u2019s captions alone differing', AFTER_A_SAVE],+ ]) {+ const sdk = dashboardLayers({ published, draft: saved, ...versions });+ const r = await verifySpec(DASH_SPEC, readerFor(sdk, 'new_fieldops', {}));+ const check = r.checks.find((c) => c.kind === 'dashboard');+ assert.deepStrictEqual([check.present, check.detail], [true, ''], what);+ assert.deepStrictEqual(sdk.fetches, [['dashboard', 'dash-1']], `${what}: the tiles were read`);+ }+ // The published read of this user carries one language, so its caption in that language is the text rule's alone: a 1033 caption saved and not+ // published is a change whatever the two versions say.+ const renamed = saved.replace('description="By Priority" languagecode="1033"', 'description="By Owner" languagecode="1033"');+ for (const [what, versions] of [['no version', {}], ['one version on both layers', AT_ROW_VERSION], ['a saved layer written since the publish', AFTER_A_SAVE]]) {+ const { check } = await dashboardVerify({ published, draft: renamed, ...versions });+ assert.strictEqual(check.present, false, what);+ assert.match(check.detail, NOT_PUBLISHED, what);+ }+});++test('readerFor + verifySpec: the same version excuses captions only — a tile that differs between the two reads is not published, and no tile is read', async () => {+ const { published, saved } = SECOND_LANGUAGE_USER;+ for (const [what, draft] of [+ ['a tile moved', swapFirstTwoCells(saved)],+ ['a tile\u2019s view changed', saved.replace(`<ViewId>${DASH_VIEW_GOLD}</ViewId>`, `<ViewId>${DASH_VIEW_OPEN}</ViewId>`)],+ ['a cell removed', saved.replace(cellOf(saved, 4), '')],+ ]) {+ assert.notStrictEqual(draft, saved, what);+ const sdk = dashboardLayers({ published, draft, ...AT_ROW_VERSION });+ const check = (await verifySpec(DASH_SPEC, readerFor(sdk, 'new_fieldops', {}))).checks.find((c) => c.kind === 'dashboard');+ assert.strictEqual(check.present, false, what);+ assert.match(check.detail, NOT_PUBLISHED, what);+ assert.deepStrictEqual(sdk.fetches, [], `${what}: no tile is read`);+ }+});++test('readerFor + verifySpec: for a user of the second language, a dashboard that changes while its tiles are read is still caught', async () => {+ const { published, saved } = SECOND_LANGUAGE_USER;+ for (const [what, later, detail] of [+ // Moved and published again: both layers are at the new version, so the second check passes, and the published FormXML is not the first one.+ ['published again with a tile moved', { laterPublished: swapFirstTwoCells(published), laterDraft: swapFirstTwoCells(saved), laterPublishedVersion: MOVED_VERSION, laterVersion: MOVED_VERSION },+ /dashboard dash-1 changed while it was being read — verify again/],+ // A draft saved while the tiles were read moves the saved layer's version off the published row's: the second check no longer has its word.+ ['a draft saved while it was read', { laterVersion: MOVED_VERSION }, /dashboard dash-1 has changes that are not published — publish it, then verify/],+ ]) {+ const { check } = await dashboardVerify({ published, draft: saved, ...AT_ROW_VERSION, ...later });+ assert.strictEqual(check.present, false, what);+ assert.match(check.detail, detail, what);+ }+});++test('readerFor REAL BUNDLE: the tiles of a published dashboard are read for a user of the second language, and a saved change is refused', async (t) => {+ const id = '33333333-0000-4000-8000-000000000001';+ const { published, saved } = SECOND_LANGUAGE_USER;+ const live = await readDashboardThroughRealBundle(t, id, published, saved, { publishedVersion: ROW_VERSION, version: ROW_VERSION });+ assert.ifError(live.error);+ // The SDK reads the same tiles, with the same names, out of this saved read as out of the base-language user's.+ assert.deepStrictEqual(live.tiles.map((c) => [c.type, c.name, c.parameters.TargetEntityType, c.parameters.ViewId, c.parameters.VisualizationId]), [+ ['chart', 'By Priority', 'new_workorder', DASH_VIEW_OPEN, DASH_CHART_PRIORITY],+ ['chart', 'By Status', 'new_workorder', DASH_VIEW_OPEN, DASH_CHART_STATUS],+ ['list', 'Critical Queue', 'new_workorder', DASH_VIEW_CRITICAL, undefined],+ ['list', 'Gold Customers', 'new_customer', DASH_VIEW_GOLD, undefined],+ ]);+ assert.deepStrictEqual(live.reads, ['published formxml', 'saved formxml', 'the SDK\u2019s fetch', 'published formxml', 'saved formxml'], 'the tiles are read between the two checks');+ // A saved layer written since the publish — its version moved — is not the published row: refused before the SDK reads anything.+ const written = await readDashboardThroughRealBundle(t, id, published, saved, { publishedVersion: ROW_VERSION, version: MOVED_VERSION });+ assert.match(written.error && written.error.message, /^dashboard 33333333-0000-4000-8000-000000000001 has changes that are not published — publish it, then verify$/);+ assert.deepStrictEqual(written.reads, ['published formxml', 'saved formxml']);+ // So is one whose published row answers no version, as before: the two texts alone cannot say.+ const unversioned = await readDashboardThroughRealBundle(t, id, published, saved);+ assert.match(unversioned.error && unversioned.error.message, /^dashboard 33333333-0000-4000-8000-000000000001 has changes that are not published — publish it, then verify$/);+ // The base-language user's reads are read whether or not the row answers a version.+ for (const options of [{}, { publishedVersion: ROW_VERSION, version: ROW_VERSION }]) {+ const base = await readDashboardThroughRealBundle(t, id, BASE_LANGUAGE_USER.published, BASE_LANGUAGE_USER.saved, options);+ assert.ifError(base.error);+ assert.deepStrictEqual(base.tiles.map((c) => c.name), ['By Priority', 'By Status', 'Critical Queue', 'Gold Customers']);+ }+});+// A client per isolated read ran `az account get-access-token` once per dashboard. One client serves every read of a// run — the run's own when it is given — while each read still gets a fresh SDK in its own throwaway workspace.test('isolatedReaderFor shares one HTTP client across reads, each with a fresh SDK', async () => {diff --git a/plugins/model-apps/scripts/tests/verify-page-code-batch.test.js b/plugins/model-apps/scripts/tests/verify-page-code-batch.test.jsindex df78a96be..8bfce1ffc 100644--- a/plugins/model-apps/scripts/tests/verify-page-code-batch.test.js+++ b/plugins/model-apps/scripts/tests/verify-page-code-batch.test.js@@ -27,7 +27,8 @@ const stubSdk = () => ({// Stands in for the page backend (lib/genpage-sdk.js): `read(id)` answers the page's source, throws what the backend throws for a page it// cannot read, and records every read and how many were in flight at once.-function fakeGenpage({ failIds = new Set(), rawIds = new Set(), delayMs = 0 } = {}) {+// `hold`, a promise, keeps every read open until it settles — for a test that must prove an order without a clock.+function fakeGenpage({ failIds = new Set(), rawIds = new Set(), delayMs = 0, hold } = {}) {const reads = [];const state = { inFlight: 0, peak: 0 };return {@@ -40,6 +41,7 @@ function fakeGenpage({ failIds = new Set(), rawIds = new Set(), delayMs = 0 } =state.peak = Math.max(state.peak, state.inFlight);try {if (delayMs) await new Promise((resolve) => setTimeout(resolve, delayMs));+ if (hold) await hold;if (failIds.has(String(id).toLowerCase())) throw Object.assign(new Error(`page ${id} does not exist in this environment`), { code: 'GENPAGE_NOT_FOUND' });if (rawIds.has(String(id).toLowerCase())) throw Object.assign(new Error(`page ${id} has no source this tool can read`), { code: 'GENPAGE_NO_SOURCE' });return { id, name: 'Page', source: source(id) };@@ -136,13 +138,25 @@ test('once a pass ends its page reads none starts until the next pass begins —assert.deepStrictEqual(await reader.pageCode(pid(1)), source(pid(1)), 'the next pass reads again');});+// The read is held open until the test lets it go, so "endPageReads did not wait for it" is proven by order, not by a clock: the+// earlier form (a 20 ms read, endPageReads back within 15 ms) failed on a loaded machine. The 5 s race only turns a regression —+// endPageReads waiting for the read, which never ends while it is held — into a failure instead of a hang.test('ending the reads never waits for, or cancels, a read in flight — it is a request, and finishes by itself', async () => {- const genpage = fakeGenpage({ delayMs: 20 });+ let release;+ const genpage = fakeGenpage({ hold: new Promise((resolve) => { release = resolve; }) });const reader = readerWith(genpage);const reading = reader.pageCode(pid(1));- const started = Date.now();- await reader.endPageReads();- assert.ok(Date.now() - started < 15, 'endPageReads does not wait for the read');+ let readSettled = false;+ reading.then(() => { readSettled = true; }, () => { readSettled = true; });+ let timer;+ const stillWaiting = new Promise((resolve) => { timer = setTimeout(() => resolve('still waiting'), 5000); });+ try {+ assert.strictEqual(await Promise.race([reader.endPageReads().then(() => 'ended'), stillWaiting]), 'ended', 'endPageReads does not wait for the read');+ } finally {+ clearTimeout(timer);+ }+ assert.strictEqual(readSettled, false, 'the read was still in flight when the reads were ended');+ release();assert.strictEqual(await reading, source(pid(1)), 'the read in flight finishes');});diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.jsindex cccea9204..c11c886b5 100644--- a/plugins/model-apps/scripts/tests/verify-spec.test.js+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js@@ -4,6 +4,8 @@ const assert = require('node:assert');const { verifySpec, hasElement, parseFetchXml, liveNavEntries, subareaDashboardHasLauncher } = require('../lib/verify-spec.js');const { sitemapXmlFor } = require('../verify-model-app.js');const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');+const { parseTranslationWorkbook, readTranslationLabels } = require('../lib/translation-labels.js');+const { workbookXml, exportZip, exportAnswer } = require('./helpers/translation-export.js');const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, TEMPLATE_LINE_PAGE, JSX_TEXT_PAGE, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, ELEMENT_PAGE_TOKEN_LINE, FUNCTION_TYPE_PAGES } = require('./helpers/misread-page.js');const idFor = (set) => ({ savedquery: 'savedqueryid', savedqueryvisualization: 'savedqueryvisualizationid', systemform: 'formid' }[set] || 'id');@@ -3268,7 +3270,7 @@ test('verifySpec: a plain-string relationship list stays name-only', async () =>test('verifySpec: a 1:N passes only when the name and both endpoints match', async () => {const spec = { solution: { publisherPrefix: 'contoso' }, entities: [], views: [], charts: [], forms: [], appShell: { areas: [] },relationships: [{ type: 'OneToMany', referenced: 'contoso_project', referencing: 'contoso_task', lookup: { schemaName: 'contoso_ProjectId' } }] };- const row = { schemaName: 'CONTOSO_PROJECT_CONTOSO_TASK', type: 'OneToMany', referencedEntity: 'contoso_project', referencingAttribute: 'contoso_projectid' };+ const row = { schemaName: 'CONTOSO_PROJECT_CONTOSO_TASK', type: 'OneToMany', referencedEntity: 'contoso_project', referencingEntity: 'contoso_task', referencingAttribute: 'contoso_projectid' };const read = {findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '',entityRelationships: async () => [row],@@ -3288,7 +3290,10 @@ test('verifySpec: an N:N passes on an unordered pair and fails when the name isrelationships: [{ type: 'ManyToMany', entity1: 'contoso_task', entity2: 'contoso_project' }] };const read = {findTable: async () => null, findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '',- entityRelationships: async () => [{ schemaName: 'contoso_project_contoso_task', type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_task' }],+ entityRelationships: async () => [{+ schemaName: 'contoso_project_contoso_task', type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_task',+ intersectEntityName: 'contoso_project_contoso_task', entity1IntersectAttribute: 'contoso_projectid', entity2IntersectAttribute: 'contoso_taskid',+ }],};const ok = await verifySpec(spec, read);assert.strictEqual(ok.checks.find((c) => c.kind === 'relationship').present, true);@@ -3319,3 +3324,269 @@ test('verifySpec: when the typed read cannot see the holder, relationshipHolderassert.strictEqual(rc.present, false);assert.match(rc.detail, /contoso_project_contoso_task exists as 1:N contoso_project -> contoso_task \(lookup contoso_projectid\), not as the declared N:N/);});++// --- A language the form READ does not carry is read from ONE translation export of the app's solution ---------------------------------------------+//+// The form reads cannot show a caption in a language their FormXML does not carry, and a translation export can: it holds every provisioned language,+// the published layer, one row per tab or section keyed by the `id` the element has in the FormXML. So the captions compared in such a language are+// compared there — by the id of the tab or section the form's read matched — and are reported like any other: a right one passes, a stale or an+// empty one is a mismatch. An export that cannot be used, or that cannot say, leaves them UNVERIFIED as they were: never a pass. The export is one+// request, made when some caption needs it and not otherwise, and shared by every form of the pass.+const TAB_ID = '0a0a0a0a-0000-4000-8000-000000000001';+const LEFT_ID = '0a0a0a0a-0000-4000-8000-000000000002';+const RIGHT_ID = '0a0a0a0a-0000-4000-8000-000000000003';+// The form as the live read shows it — every caption in English, none in Spanish — with the ids a platform form's tabs and sections have.+const readsEnglishWithIds = (over = {}) => layoutXml([overview({ tab: { id: TAB_ID }, left: { id: LEFT_ID }, right: { id: RIGHT_ID }, ...over })]);+// What the export holds for TOPO_SPEC's three containers: the English captions the form read shows and the Spanish ones `inSpanish` asks for. `over` replaces+// the texts of a row by its id, and drops the row when it is `null`.+const spanishRows = (over = {}) => [+ { entity: 'new_ticket', id: TAB_ID, texts: { 1033: 'Overview', 3082: 'Resumen' } },+ { entity: 'new_ticket', id: LEFT_ID, texts: { 1033: 'L', 3082: 'Izquierda' } },+ { entity: 'new_ticket', id: RIGHT_ID, texts: { 1033: 'R', 3082: 'Derecha' } },+].filter((row) => over[row.id] !== null).map((row) => (over[row.id] ? { ...row, texts: over[row.id] } : row));+const exportOf = (captions = spanishRows(), languages = [1033, 3082]) => {+ const read = parseTranslationWorkbook(workbookXml({ languages, captions }));+ assert.strictEqual(read.ok, true, JSON.stringify(read));+ return read;+};+// A reader that can ask for the export: it answers `answer` (or what a function of the solution's name answers) a moment later, and records the solution asked for.+const asking = (answer, seen = []) => ({ translationLabels: async (solution) => {+ seen.push(solution);+ await new Promise((resolve) => setImmediate(resolve));+ return typeof answer === 'function' ? answer(solution) : answer;+} });+const inOrgAsking = (answer, seen, languagecode = 1033) => ({ ...inOrg(languagecode), ...asking(answer, seen) });+const SOLUTION_EXPORT = 'the translation export of solution \'s\'';++test('verify compares the captions a form read does not carry with ONE translation export of the app\'s solution — the right ones pass and nothing is left unverified', async () => {+ // The English build, compared in 1033, is what the fixture reports by itself (it publishes no form order): the export neither adds to it nor takes from it.+ const baseline = await checkWith(readsOnlyEnglish(), () => {}, inOrg(1033));+ for (const [what, mutate, opts] of [+ ['the --language-code the build was given', inSpanish, { languageCode: 3082 }],+ ['the language the build\'s SDK was made for', inSpanish, { preResolvedLanguageCode: 3082 }],+ ['both, as the build\'s own verify is handed them', inSpanish, { languageCode: 3082, preResolvedLanguageCode: 3082 }],+ ['a languageCode the spec pins', (spec) => { inSpanish(spec); spec.languageCode = 3082; }, undefined],+ ]) {+ const seen = [];+ const { res, chk } = await checkWith(readsEnglishWithIds(), mutate, inOrgAsking(exportOf(), seen), opts);+ assert.strictEqual(chk.present, true, `${what}: ${chk.detail}`);+ assert.strictEqual(res.unverified, undefined, `${what}: the export settled all three captions`);+ assert.deepStrictEqual(res.missing, baseline.res.missing, `${what}: nothing is added to the failures the fixture has by itself`);+ assert.strictEqual(res.ok, baseline.res.ok, what);+ assert.deepStrictEqual(seen, ['s'], `${what}: one export, of the spec's solution`);+ assert.ok(!res.checks.some((c) => /label/i.test(c.kind)), `${what}: no label check of its own is recorded`);+ }+});++test('verify reports a caption the translation export shows differently, or not at all — by the id of its tab or section, and only that one', async () => {+ const opts = { languageCode: 3082 };+ const baseline = await checkWith(readsEnglishWithIds(), () => {}, inOrg(1033));+ assert.strictEqual(baseline.chk.present, true, 'the English build of the same form is right');+ // A stale caption in the tab: the section captions are right, and are not mentioned.+ const stale = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows({ [TAB_ID]: { 1033: 'Overview', 3082: 'Antiguo' } }))), opts);+ assert.strictEqual(stale.chk.present, false);+ assert.match(stale.chk.detail, new RegExp(`tab 'tab_overview' is deployed with label "Antiguo" in language 3082 \\(${SOLUTION_EXPORT} shows it; the form read does not carry language 3082\\), the spec declares label: "Resumen" in language 3082`));+ assert.doesNotMatch(stale.chk.detail, /sec_left|sec_right/);+ assert.strictEqual(stale.res.unverified, undefined, 'a caption the export settled is no longer unverified, right or wrong');+ assert.ok(stale.res.missing.some((m) => m.kind === 'form-topology'), 'it is a failure of the form, as any wrong caption is');+ // An empty cell is a caption that is not there; what the row holds in other languages is said.+ const empty = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows({ [LEFT_ID]: { 1033: 'L' } }))), opts);+ assert.strictEqual(empty.chk.present, false);+ assert.match(empty.chk.detail, new RegExp(`section 'sec_left' is deployed with no label in language 3082 \\(${SOLUTION_EXPORT} has none, only "L" in 1033; the form read does not carry language 3082\\), the spec declares label: "Izquierda" in language 3082`));+ assert.doesNotMatch(empty.chk.detail, /tab 'tab_overview'|sec_right/);+ const bare = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows({ [RIGHT_ID]: {} }))), opts);+ assert.match(bare.chk.detail, new RegExp(`section 'sec_right' is deployed with no label in language 3082 \\(${SOLUTION_EXPORT} has none; the form read does not carry language 3082\\), the spec declares label: "Derecha" in language 3082`));+ // Every wrong caption is reported, each once.+ const all = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows({ [TAB_ID]: { 3082: 'a' }, [LEFT_ID]: { 3082: 'b' }, [RIGHT_ID]: { 3082: 'c' } }))), opts);+ assert.strictEqual((all.chk.detail.match(/in language 3082 \(/g) || []).length, 3, all.chk.detail);+ // Text is compared exactly: the case of a letter is a different caption.+ const cased = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows({ [TAB_ID]: { 1033: 'Overview', 3082: 'resumen' } }))), opts);+ assert.strictEqual(cased.chk.present, false);+});++test('verify makes ONE translation export for every form and every caption — forms that ask at the same moment share it', async () => {+ const spec = TOPO_SPEC();+ inSpanish(spec);+ spec.forms.push({ ...JSON.parse(JSON.stringify(spec.forms[0])), name: 'Ticket Second' });+ const SECOND = { tab: 'a1b2c3d4-0000-4000-8000-000000000001', left: 'a1b2c3d4-0000-4000-8000-000000000002', right: 'a1b2c3d4-0000-4000-8000-000000000003' };+ const secondRows = (tabText) => [+ { entity: 'new_ticket', id: SECOND.tab, texts: { 1033: 'Overview', 3082: tabText } },+ { entity: 'new_ticket', id: SECOND.left, texts: { 1033: 'L', 3082: 'Izquierda' } },+ { entity: 'new_ticket', id: SECOND.right, texts: { 1033: 'R', 3082: 'Derecha' } },+ ];+ const reads = (answer, seen) => topoRead(null, {+ ...asking(answer, seen),+ queryRecords: async (set, o) => {+ if (set === 'organization') return [{ languagecode: 1033 }];+ if (set !== 'systemform') return [];+ const asked = /name eq '([^']*)'/.exec((o && o.filter) || '');+ const name = asked ? asked[1] : 'Ticket Main';+ return [{ formid: name === 'Ticket Main' ? 'f1' : 'f2', name, objecttypecode: 'new_ticket', type: 2, isdefault: false }];+ },+ formTopology: async (_entity, id) => (id === 'f1' ? readsEnglishWithIds() : readsEnglishWithIds({ tab: { id: SECOND.tab }, left: { id: SECOND.left }, right: { id: SECOND.right } })),+ });+ const topologies = (res) => res.checks.filter((c) => c.kind === 'form-topology').map((c) => [c.name, c.present]);+ const seen = [];+ const passing = await verifySpec(spec, reads(exportOf([...spanishRows(), ...secondRows('Resumen')]), seen), { languageCode: 3082 });+ assert.deepStrictEqual(topologies(passing), [['new_ticket.Ticket Main', true], ['new_ticket.Ticket Second', true]]);+ assert.strictEqual(passing.unverified, undefined);+ assert.deepStrictEqual(seen, ['s'], 'six captions of two forms, one export');+ // Each form is judged by its own rows: the second form\'s stale caption fails it, and the first stays right.+ const again = [];+ const failing = await verifySpec(spec, reads(exportOf([...spanishRows(), ...secondRows('Antiguo')]), again), { languageCode: 3082 });+ assert.deepStrictEqual(topologies(failing), [['new_ticket.Ticket Main', true], ['new_ticket.Ticket Second', false]]);+ assert.strictEqual(again.length, 1);+ // …and an export of another pass is another export: the answer is kept for ONE pass, as a form read is.+ const passes = [];+ const reader = reads(exportOf([...spanishRows(), ...secondRows('Resumen')]), passes);+ await verifySpec(spec, reader, { languageCode: 3082 });+ await verifySpec(spec, reader, { languageCode: 3082 });+ assert.strictEqual(passes.length, 2);+});++test('verify asks for no translation export when every caption can be compared from the form read, or none can be compared at all', async () => {+ const seen = [];+ const reader = inOrgAsking(exportOf(), seen);+ // The read carries the Spanish captions: they are compared there, as before — a wrong one fails, with no export.+ const carried = await checkWith(readsSpanishToo(), inSpanish, reader, { languageCode: 3082 });+ assert.strictEqual(carried.chk.present, true, carried.chk.detail);+ const wrong = await checkWith(readsSpanishToo({ tabLabel: [{ text: 'Overview', lcid: 1033 }, { text: 'Antiguo', lcid: 3082 }] }), inSpanish, reader, { languageCode: 3082 });+ assert.strictEqual(wrong.chk.present, false);+ assert.doesNotMatch(wrong.chk.detail, /translation export/);+ // The English build: the language is one the read carries.+ assert.strictEqual((await checkWith(readsEnglishWithIds(), () => {}, reader)).chk.present, true);+ // A layout that authors no caption has nothing to look up.+ assert.strictEqual((await checkWith(readsEnglishWithIds(), unlabelled, reader)).chk.present, true);+ // A form that publishes no label at all names no language that is missing from the read: what it lacks is a caption, and a mismatch as ever.+ const none = layoutXml([overview({ tabLabel: null, leftLabel: null, rightLabel: null, tab: { id: TAB_ID }, left: { id: LEFT_ID }, right: { id: RIGHT_ID } })]);+ const bare = await checkWith(none, inSpanish, reader, { languageCode: 3082 });+ assert.strictEqual(bare.chk.present, false);+ assert.match(bare.chk.detail, /tab 'tab_overview' is deployed with no label, the spec declares label: "Resumen" in language 3082/);+ // A string caption whose language cannot be established is not compared in any: there is nothing to look up.+ const unreadable = { ...asking(exportOf(), seen), queryRecords: async (set) => { if (set === 'organization') throw new Error('503'); return set === 'systemform' ? FORM_ROW : []; } };+ const unknown = await checkWith(readsEnglishWithIds(), () => {}, unreadable);+ assert.strictEqual(unknown.res.unverified.length, 1);+ assert.match(unknown.res.unverified[0], /the language the build wrote them in could not be established/);+ assert.deepStrictEqual(seen, [], 'no export was asked for');+});++test('verify compares a label MAP language by language — the languages the read carries in the read, the others in the export', async () => {+ const declared = (spec) => { unlabelled(spec); spec.forms[0].tabs[0].label = { 1033: 'Overview', 3082: 'Resumen' }; };+ const seen = [];+ const right = await checkWith(readsEnglishWithIds(), declared, inOrgAsking(exportOf(), seen));+ assert.strictEqual(right.chk.present, true, right.chk.detail);+ assert.strictEqual(right.res.unverified, undefined);+ assert.deepStrictEqual(seen, ['s']);+ // The English caption is held strictly by the read, the Spanish one by the export, and each is reported by itself.+ const both = await checkWith(readsEnglishWithIds({ tabLabel: { text: 'Old', lcid: 1033 } }), declared, inOrgAsking(exportOf(spanishRows({ [TAB_ID]: { 1033: 'Overview', 3082: 'Antiguo' } }))));+ assert.strictEqual(both.chk.present, false);+ assert.match(both.chk.detail, /tab 'tab_overview' is deployed with label "Old" in language 1033, the spec declares label: "Overview" in language 1033/);+ assert.match(both.chk.detail, /tab 'tab_overview' is deployed with label "Antiguo" in language 3082 \(the translation export of solution 's' shows it; /);+ // Only the language the read lacks goes to the export: an English-only map has none, and asks for none.+ const englishOnly = (spec) => { unlabelled(spec); spec.forms[0].tabs[0].label = { 1033: 'Overview' }; };+ const before = [];+ assert.strictEqual((await checkWith(readsEnglishWithIds(), englishOnly, inOrgAsking(exportOf(), before))).chk.present, true);+ assert.deepStrictEqual(before, []);+});++test('verify leaves the captions UNVERIFIED — as before, with the reason — when the translation export cannot be used, and never passes them', async () => {+ const baseline = await checkWith(readsOnlyEnglish(), () => {}, inOrg(1033));+ const opts = { languageCode: 3082 };+ const entry = (why) => SPANISH_STRINGS_ENTRY.replace('from it. Check', `from it. A translation export of solution 's' could not be read (${why}). Check`);+ for (const [what, answer, why] of [+ ['an export the platform refused', { ok: false, reason: 'HTTP 403: Principal user is missing prvExportTranslation privilege' }, 'HTTP 403: Principal user is missing prvExportTranslation privilege'],+ ['a reader that throws', () => { throw new Error('socket hang up'); }, 'socket hang up'],+ ['a reader that answers nothing', undefined, 'the reader gave no answer'],+ ['an answer that is neither a failure nor an export', { ok: true }, 'the reader\'s answer is not an export'],+ ['a failure with no reason', { ok: false }, 'no reason was given'],+ ]) {+ const { res, chk } = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(answer), opts);+ assert.strictEqual(chk.present, true, `${what}: nothing says a caption is wrong: ${chk.detail}`);+ assert.deepStrictEqual(res.missing, baseline.res.missing, `${what}: unverified is not a failure`);+ assert.strictEqual(res.ok, baseline.res.ok, what);+ assert.deepStrictEqual(res.unverified, [entry(why)], what);+ assert.ok(!res.checks.some((c) => /label/i.test(c.kind)), `${what}: no label check was recorded as passed`);+ }+});++// The workbook is read whole or not at all: a reader that picked rows out by name passed over a conflicting caption row written `<ss:Row>` (the+// spreadsheet's own Row, under the root's prefix for its namespace), and over a sheet that declares another namespace, and settled the caption from+// what was left. Through the real reader of the export, each of these now leaves the captions unverified, with the reason — never a pass.+test('verify never settles a caption from a translation workbook it cannot read whole — a conflicting row written with a prefix, a sheet of another namespace, a Number caption', async () => {+ const baseline = await checkWith(readsOnlyEnglish(), () => {}, inOrg(1033));+ const opts = { languageCode: 3082 };+ const good = workbookXml({ captions: spanishRows() });+ const conflicting = `<ss:Row>${['new_ticket', TAB_ID, 'displayname', 'Overview', 'Antiguo'].map((text) => `<ss:Cell><ss:Data ss:Type="String">${text}</ss:Data></ss:Cell>`).join('')}</ss:Row>`;+ const readerOf = async (xml) => readTranslationLabels({ post: async () => exportAnswer(exportZip(xml)) }, 's');+ // The control: the workbook as the platform writes it settles all three captions.+ const control = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(await readerOf(good)), opts);+ assert.strictEqual(control.chk.present, true, control.chk.detail);+ assert.strictEqual(control.res.unverified, undefined);+ for (const [what, xml, why] of [+ ['a conflicting caption row written <ss:Row>', good.replace(/(<Worksheet ss:Name="Localized Labels"[\s\S]*?)(<\/Table>)/, `$1${conflicting}$2`), /has an element <ss:Row>/],+ ['the sheet declared in another namespace', good.replace('<Worksheet ss:Name="Localized Labels"', '<Worksheet xmlns="urn:example:not-spreadsheet" ss:Name="Localized Labels"'), /worksheet with the attribute xmlns,/],+ ['a caption typed as a Number', good.replace('<Data ss:Type="String">Resumen</Data>', '<Data ss:Type="Number">Resumen</Data>'), /has a Number cell/],+ ]) {+ const { res, chk } = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(await readerOf(xml)), opts);+ assert.strictEqual(chk.present, true, `${what}: nothing says a caption is wrong: ${chk.detail}`);+ assert.deepStrictEqual(res.missing, baseline.res.missing, `${what}: unverified is not a failure`);+ assert.strictEqual(res.ok, baseline.res.ok, what);+ assert.strictEqual((res.unverified || []).length, 1, `${what}: the captions stay unverified`);+ assert.match(res.unverified[0], /A translation export of solution 's' could not be read \(the workbook of the export is not readable: /, what);+ assert.match(res.unverified[0], why, what);+ }+});++test('verify leaves a caption unverified, and says why, when the export cannot settle it — no id, no row, a row twice, no column — and settles the others', async () => {+ const opts = { languageCode: 3082 };+ const settles = (res) => (res.unverified || []).join(' | ');+ // The FormXML gives its tab and sections no id: nothing to look them up by.+ const noIds = await checkWith(readsOnlyEnglish(), inSpanish, inOrgAsking(exportOf()), opts);+ assert.strictEqual(noIds.chk.present, true, noIds.chk.detail);+ assert.strictEqual(noIds.res.unverified.length, 1);+ assert.match(noIds.res.unverified[0], /^form-labels:new_ticket\.Ticket Main \(the labels of tab 'tab_overview', section 'sec_left', section 'sec_right' in language 3082 were not compared: the environment's form read returns labels only in 1033, so labels written in 3082 cannot be read back from it\. A translation export of solution 's' was read, but it cannot settle them: the form's FormXML gives a tab or section no id to look it up by\. Check them in Power Apps with that language, or verify in a language the read carries\)$/);+ // The export has no row for the tab: it stays unverified, and the sections are compared — a right one passes, a stale one fails.+ const noTab = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows({ [TAB_ID]: null }))), opts);+ assert.strictEqual(noTab.chk.present, true, noTab.chk.detail);+ assert.strictEqual(noTab.res.unverified.length, 1);+ assert.match(noTab.res.unverified[0], new RegExp(`the label of tab 'tab_overview' in language 3082 was not compared: .*it cannot settle it: the export has no caption row for tab 'tab_overview' \\(id ${TAB_ID}, table new_ticket\\)\\. Check it in Power Apps`));+ assert.doesNotMatch(noTab.res.unverified[0], /sec_left|sec_right/);+ const noTabStale = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows({ [TAB_ID]: null, [LEFT_ID]: { 1033: 'L', 3082: 'Viejo' } }))), opts);+ assert.strictEqual(noTabStale.chk.present, false);+ assert.match(noTabStale.chk.detail, /section 'sec_left' is deployed with label "Viejo" in language 3082/);+ assert.strictEqual(noTabStale.res.unverified.length, 1, 'the tab is still unverified');+ // The id of another table\'s form is not this form\'s.+ const otherTable = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows().map((row) => ({ ...row, entity: 'new_other' })))), opts);+ assert.strictEqual(otherTable.res.unverified.length, 1);+ assert.match(otherTable.res.unverified[0], /the export has no caption row for tab 'tab_overview' \(id [0-9a-f-]+, table new_ticket\)/);+ // Two rows for one id: the export cannot say which is the form\'s.+ const twice = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf([...spanishRows(), { entity: 'new_ticket', id: TAB_ID, texts: { 1033: 'Overview', 3082: 'Otro' } }])), opts);+ assert.strictEqual(twice.chk.present, true, twice.chk.detail);+ assert.match(settles(twice.res), new RegExp(`the export has more than one caption row for tab 'tab_overview' \\(id ${TAB_ID}, table new_ticket\\)`));+ // The export has no column for the language: it cannot show it either.+ const noColumn = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(spanishRows(), [1033])), opts);+ assert.strictEqual(noColumn.chk.present, true, noColumn.chk.detail);+ assert.match(settles(noColumn.res), /it cannot settle them: the export has no column for language 3082\. Check them/);+});++test('verify tells a maker what the flag is for when a string caption is compared in the ORGANIZATION\'s language and the export shows others', async () => {+ // A French build in a Spanish-language organization, verified with no flag: the captions are held to the organization's Spanish, which the read does not+ // carry, and the export has no Spanish caption — the French ones are in 1036. The detail carries the advice a read-carried mismatch carries.+ const french = exportOf([+ { entity: 'new_ticket', id: TAB_ID, texts: { 1033: 'Overview', 1036: 'Apercu' } },+ { entity: 'new_ticket', id: LEFT_ID, texts: { 1033: 'L', 1036: 'Gauche' } },+ { entity: 'new_ticket', id: RIGHT_ID, texts: { 1033: 'R', 1036: 'Droite' } },+ ], [1033, 1036, 3082]);+ const told = await checkWith(readsEnglishWithIds(), inFrench, inOrgAsking(french, undefined, 3082));+ assert.strictEqual(told.chk.present, false);+ assert.match(told.chk.detail, /tab 'tab_overview' is deployed with no label in language 3082 \(the translation export of solution 's' has none, only "Overview" in 1033, "Apercu" in 1036; the form read does not carry language 3082\), the spec declares label: "Apercu" in language 3082/);+ assert.match(told.chk.detail, /the labels were compared in the organization's base language \(3082\), because verify was told no other: if the build was run with --language-code, give verify the same flag \(or pin "languageCode" in the spec\)/);+ // Told the language the build was run in, the export settles them.+ const given = await checkWith(readsEnglishWithIds(), inFrench, inOrgAsking(french, undefined, 3082), { languageCode: 1036 });+ assert.strictEqual(given.chk.present, true, given.chk.detail);+ assert.strictEqual(given.res.unverified, undefined);+ // A right caption in the organization\'s language is not blamed on a guess.+ const spanish = await checkWith(readsEnglishWithIds(), inSpanish, inOrgAsking(exportOf(), undefined, 3082));+ assert.strictEqual(spanish.chk.present, true, spanish.chk.detail);+ assert.strictEqual(spanish.res.unverified, undefined);+});diff --git a/plugins/model-apps/scripts/tests/write-app-spec-doc-env.test.js b/plugins/model-apps/scripts/tests/write-app-spec-doc-env.test.jsnew file mode 100644index 000000000..c079ed68a--- /dev/null+++ b/plugins/model-apps/scripts/tests/write-app-spec-doc-env.test.js@@ -0,0 +1,248 @@+'use strict';+// scripts/write-app-spec-doc.js with --env, end to end through its main(): what it reads of the environment (the app, and the roles associated with it —+// nothing else, and nothing written), what the document and the warnings say of it, and that a read that cannot be made never costs the document.+// The SDK and the HTTP client are stubs here; the real bundle is driven in app-roles.test.js.+const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { loadCli } = require('./helpers/cli-harness.js');+const realAuth = require('../lib/dataverse-auth.js');+const { withThrowawaySdk } = require('../lib/throwaway-sdk.js');+const { extensionSpec, grant } = require('./helpers/app-access-specs.js');++const SCRIPT = path.resolve(__dirname, '..', 'write-app-spec-doc.js');+const ENV = 'https://contoso.crm.dynamics.com';+const APP_ID = '22222222-2222-4222-8222-222222222222';+const ROLE_PM = '00000000-0000-4000-8000-000000000001';+const ROLE_VIEWER = '00000000-0000-4000-8000-000000000002';+const ADMIN_ONLY = /only for (system )?admin|opens only|administrator-only|admin-only|only administrators/i;++// Runs main() over a folder holding `spec`. `sdk` is what the throwaway SDK is: { resolveArtifact, dataverse: { get } } — a method the command may not+// call is simply not there, so a stray call is a TypeError. The stubbed emitResult ends the run as the real one does.+async function run({ spec = extensionSpec(), argv = ['--env', ENV], sdk, clientError } = {}) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'appdoc-env-'));+ const events = [];+ const emitted = [];+ try {+ const specPath = path.join(dir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec), 'utf8');+ const requires = {+ './lib/dataverse-auth.js': {+ ...realAuth,+ emitResult: (ok, payload) => {+ emitted.push({ ok, payload });+ const exit = new Error(`process.exit(${ok ? 0 : 1})`);+ exit.exitCode = ok ? 0 : 1;+ throw exit;+ },+ },+ // The throwaway-workspace lifecycle is the real one (lib/throwaway-sdk.js); only the SDK and the client it makes are stubs.+ './lib/throwaway-sdk.js': {+ withThrowawaySdk: (options, runWith) => withThrowawaySdk({+ ...options,+ deps: {+ createAzHttpClient: (env) => {+ events.push({ type: 'client', env });+ if (clientError) throw clientError;+ return { marker: 'az-client', env };+ },+ makerSdk: {+ createNodeWorkspaceStorage: (workspace) => ({ workspace }),+ createMakerSdk: (cfg) => { events.push({ type: 'sdk', cfg }); return sdk(events); },+ },+ },+ }, runWith),+ },+ };+ const cli = loadCli(SCRIPT, { requires, argv: ['--spec', `@${specPath}`, ...argv] });+ let exitCode = 0;+ try {+ await cli.main();+ } catch (err) {+ if (typeof err.exitCode !== 'number') throw err;+ exitCode = err.exitCode;+ }+ const payload = emitted.length ? emitted[0].payload : undefined;+ const docPath = payload && payload.docPath;+ const sdkEvent = events.find((e) => e.type === 'sdk');+ return {+ events,+ exitCode,+ payload,+ stderr: cli.stderrText(),+ doc: docPath && fs.existsSync(docPath) ? fs.readFileSync(docPath, 'utf8') : null,+ workspaceKept: sdkEvent ? fs.existsSync(sdkEvent.cfg.workspaceStorage.workspace) : null,+ };+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+}++// The SDK of an environment where the app exists with these roles. Every call is recorded. `resolve` answers the SDK's lookup of the app in the saved layer (what a+// draft is found by): the rows it answers, [] for no app. `body` is the whole body of the association answer, when a test needs one that is no list.+const sdkWith = ({ appId = APP_ID, rows = [{ roleid: ROLE_PM, name: 'Contoso PM - Project Manager', ismanaged: true }, { roleid: ROLE_VIEWER, name: 'Contoso PM - Viewer', ismanaged: false }], body, status = 200, resolve, get } = {}) => (events) => ({+ resolveArtifact: async (type, query) => {+ events.push({ type: 'resolveArtifact', kind: type, query });+ return resolve ? resolve(type, query) : [{ id: appId, name: 'Contoso PM', appModuleIdUnique: '33333333-3333-4333-8333-333333333333' }];+ },+ dataverse: {+ get: async (url) => {+ events.push({ type: 'get', url });+ if (get) return get(url);+ return { status, headers: {}, body: status >= 300 ? { error: { message: 'denied' } } : (body !== undefined ? body : { value: rows }) };+ },+ },+});+const reads = (r) => r.events.filter((e) => e.type === 'resolveArtifact' || e.type === 'get');++test('with --env it finds the app in the saved layer, reads the roles associated with it, and reads nothing else', async () => {+ const r = await run({ sdk: sdkWith() });+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.deepStrictEqual(reads(r), [+ { type: 'resolveArtifact', kind: 'app', query: { uniqueName: 'contoso_pm' } },+ { type: 'get', url: `/appmodules(${APP_ID})/appmoduleroles_association?$select=roleid,name,ismanaged` },+ ]);+ assert.strictEqual(r.events.find((e) => e.type === 'client').env, ENV);+ assert.match(r.doc, /The app `contoso_pm` already exists in https:\/\/contoso\.crm\.dynamics\.com and these roles are associated with it/);+ assert.match(r.doc, /\| Contoso PM - Project Manager \| not touched by this spec \|/);+ assert.match(r.doc, /\| Contoso PM - Viewer \| not touched by this spec \|/);+ assert.doesNotMatch(r.doc, ADMIN_ONLY);+});++test('the roles come out in a fixed order, whichever order the platform answers', async () => {+ const rows = [{ roleid: ROLE_VIEWER, name: 'Contoso PM - Viewer' }, { roleid: ROLE_PM, name: 'Contoso PM - Project Manager' }, { roleid: '00000000-0000-4000-8000-000000000003', name: 'contoso auditor' }];+ const a = await run({ sdk: sdkWith({ rows }) });+ const b = await run({ sdk: sdkWith({ rows: [...rows].reverse() }) });+ assert.strictEqual(a.doc, b.doc);+ assert.ok(a.doc.indexOf('| contoso auditor |') < a.doc.indexOf('| Contoso PM - Project Manager |'));+});++test('the warnings carry what the environment said: a role grant to a role the app does not have, and a new table nothing grants', async () => {+ const spec = extensionSpec();+ spec.roleGrants = [grant('Contoso PM - Auditor', 'contoso_baseline')];+ const r = await run({ spec, sdk: sdkWith() });+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.ok(r.payload.warnings.some((w) => /roleGrants\[\] role "Contoso PM - Auditor" is not among the roles associated with app 'contoso_pm'/.test(w)), JSON.stringify(r.payload.warnings));+ assert.ok(!r.payload.warnings.some((w) => /no access declared/.test(w)), 'the grant covers the table');+});++test('the output of a successful run is still { ok, docPath, bytes, warnings }', async () => {+ const r = await run({ sdk: sdkWith() });+ assert.deepStrictEqual(Object.keys(r.payload), ['ok', 'docPath', 'bytes', 'warnings']);+ assert.strictEqual(r.payload.ok, true);+});++test('an app neither layer has is a new app: nothing more is read, and the document says so', async () => {+ const r = await run({ sdk: sdkWith({ resolve: async () => [] }) });+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.deepStrictEqual(reads(r).map((e) => e.type), ['resolveArtifact'], 'no app, no association to read');+ assert.match(r.doc, /The app `contoso_pm` does not exist in https:\/\/contoso\.crm\.dynamics\.com yet/);+ assert.ok(r.payload.warnings.some((w) => /does not exist in https:\/\/contoso\.crm\.dynamics\.com yet/.test(w)), JSON.stringify(r.payload.warnings));+});++test('an app that was saved and never published exists: its roles are read if the platform answers, and the access is "not checked" if it does not — never "does not exist"', async () => {+ // The saved layer holds the draft; the platform answers a read of its roles with 404 while it has no published row.+ const refused = await run({ sdk: sdkWith({ status: 404 }) });+ assert.strictEqual(refused.exitCode, 0, refused.stderr);+ assert.doesNotMatch(refused.doc, /does not exist/);+ assert.match(refused.doc, /could not be read from https:\/\/contoso\.crm\.dynamics\.com \(HTTP 404\), so who can open it was not checked/);+ assert.ok(refused.payload.warnings.some((w) => /\(HTTP 404\) — who can open it was not checked/.test(w)), JSON.stringify(refused.payload.warnings));+ assert.ok(!refused.payload.warnings.some((w) => /does not exist|opens only for administrators/.test(w)), JSON.stringify(refused.payload.warnings));+ const answered = await run({ sdk: sdkWith() });+ assert.match(answered.doc, /already exists in https:\/\/contoso\.crm\.dynamics\.com and these roles are associated with it/);+});++test('an answer that carries no list of roles is "not checked": the document and the warnings say no role is associated only when the platform said so', async () => {+ for (const body of [{}, { value: 'malformed' }, { value: [{}] }, null]) {+ const r = await run({ sdk: sdkWith({ get: async () => ({ status: 200, headers: {}, body }) }) });+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.match(r.doc, /could not be read from https:\/\/contoso\.crm\.dynamics\.com \(.+\), so who can open it was not checked/, JSON.stringify(body));+ assert.doesNotMatch(r.doc, /no role is associated with it/, JSON.stringify(body));+ assert.ok(!r.payload.warnings.some((w) => /with no role associated with it/.test(w)), JSON.stringify(r.payload.warnings));+ }+ const none = await run({ sdk: sdkWith({ rows: [] }) });+ assert.match(none.doc, /no role is associated with it, so only administrators and other makers/);+});++test('an app with no role associated with it is reported, with the evidence the read gave', async () => {+ const r = await run({ sdk: sdkWith({ rows: [] }) });+ assert.match(r.doc, /no role is associated with it, so only administrators and other makers/);+ assert.ok(r.payload.warnings.some((w) => /with no role associated with it/.test(w)), JSON.stringify(r.payload.warnings));+});++test('a read the platform refuses does not fail the document: it says the access was not checked, and why', async () => {+ const r = await run({ sdk: sdkWith({ status: 403 }) });+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.ok(r.doc, 'the document was written');+ assert.match(r.doc, /could not be read from https:\/\/contoso\.crm\.dynamics\.com \(HTTP 403\), so who can open it was not checked/);+ assert.ok(r.payload.warnings.some((w) => /could not be read from .*\(HTTP 403\) — who can open it was not checked/.test(w)), JSON.stringify(r.payload.warnings));+ assert.doesNotMatch(r.doc, ADMIN_ONLY);+});++test('a read that throws — in the SDK, the lookup of the app, or the token — does not fail the document either', async () => {+ const cases = {+ 'the lookup of the app': { sdk: sdkWith({ resolve: async () => { throw new Error('the lookup was refused'); } }), reason: /the lookup was refused/ },+ 'the roles read': { sdk: sdkWith({ get: async () => { throw new Error('socket hang up'); } }), reason: /socket hang up/ },+ 'the HTTP client': { sdk: sdkWith(), clientError: new Error('az is not signed in'), reason: /az is not signed in/ },+ };+ for (const [what, { reason, ...options }] of Object.entries(cases)) {+ const r = await run(options);+ assert.strictEqual(r.exitCode, 0, `${what}: ${r.stderr}`);+ assert.ok(r.doc, `${what}: the document was written`);+ assert.match(r.doc, /could not be read from/, what);+ assert.match(r.doc, reason, what);+ assert.ok(r.payload.warnings.some((w) => /who can open it was not checked/.test(w)), `${what}: ${JSON.stringify(r.payload.warnings)}`);+ }+});++test('an --env that is not a Dataverse origin reads nothing, and the document is written with the reason', async () => {+ for (const env of ['https://example.com', 'contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com/api/data/v9.2']) {+ const r = await run({ argv: ['--env', env], sdk: sdkWith() });+ assert.strictEqual(r.exitCode, 0, `${env}: ${r.stderr}`);+ assert.deepStrictEqual(r.events, [], `${env}: no client, no SDK`);+ assert.match(r.doc, /could not be read from/, env);+ assert.match(r.doc, /is not a Dataverse environment URL/, env);+ assert.match(r.doc, new RegExp(`\\| Environment \\| ${env.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')} \\|`), 'the Environment row is what it always was');+ }+});++test('a spec that does not identify its app cannot be looked up, and says so', async () => {+ const spec = extensionSpec();+ delete spec.app.uniqueName;+ delete spec.solution;+ const r = await run({ spec, sdk: sdkWith() });+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.deepStrictEqual(r.events, [], 'nothing to look up, so no client and no SDK');+ assert.match(r.doc, /could not be read from/);+ assert.match(r.doc, /does not name the app/);+});++test('without --env nothing is made: no client, no SDK, no read', async () => {+ const r = await run({ argv: [], sdk: sdkWith() });+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.deepStrictEqual(r.events, []);+ assert.match(r.doc, /not by this spec/);+ assert.match(r.doc, /--env/);+});++test('the throwaway workspace the SDK was made over is removed whichever way the read ended', async () => {+ for (const sdk of [sdkWith(), sdkWith({ status: 500 }), sdkWith({ get: async () => { throw new Error('boom'); } })]) {+ const r = await run({ sdk });+ assert.strictEqual(r.workspaceKept, false);+ }+});++test('--env adds the Environment row and the access section to the document, and changes nothing else in it', async () => {+ const spec = extensionSpec();+ spec.personas = [{ persona: 'Planner', jobs: [{ name: 'Plan', privileges: [{ entity: 'contoso_baseline', access: ['read'] }], surfaces: ['Baselines'] }] }];+ const offline = await run({ spec, argv: [], sdk: sdkWith() });+ const online = await run({ spec, sdk: sdkWith() });+ assert.ok(online.doc.includes('### Access to the app'));+ assert.ok(!offline.doc.includes('### Access to the app'));+ const withoutWhatEnvAdds = online.doc+ .replace(/\| Environment \| [^\n]* \|\n/, '')+ .replace(/\n### Access to the app\n[\s\S]*?(?=\n## |\n### |$)/, '');+ assert.strictEqual(withoutWhatEnvAdds.replace(/\n{3,}/g, '\n\n').trimEnd(), offline.doc.replace(/\n{3,}/g, '\n\n').trimEnd());+});diff --git a/plugins/model-apps/scripts/tests/zip-read.test.js b/plugins/model-apps/scripts/tests/zip-read.test.jsnew file mode 100644index 000000000..ebb0d4325--- /dev/null+++ b/plugins/model-apps/scripts/tests/zip-read.test.js@@ -0,0 +1,294 @@+'use strict';+// lib/zip-read.js: the strict reader of one entry of a ZIP archive that `--verify` uses on a translation export.+//+// The export is read by a program that decides, from what it reads, whether a form's captions are right. A reader that guesses — takes the data's+// place from a header that disagrees with another, inflates past the size the archive declares, skips a checksum, reads a payload that is longer+// than the data it holds, believes a data descriptor that is not there — can turn a damaged answer into a pass. So an archive is read when every+// number in it agrees with every other, and its entries are every byte before the central directory, one after the other; and it is refused, with+// the reason, in every other case. The first test reads the archive the way the platform was measured to write it (see+// helpers/translation-export.js); the others each break one rule.+const test = require('node:test');+const assert = require('node:assert');+const { readZipEntry, ZipReadError } = require('../lib/zip-read.js');+const { zipOf, exportZip, crc32 } = require('./helpers/translation-export.js');++const XML = '<?xml version="1.0"?><Workbook>caf\u00e9 \u2014 Pesta\u00f1a Uno</Workbook>';+const archiveOf = (options) => zipOf([{ name: 'CrmTranslations.xml', data: XML }, { name: '[Content_Types].xml', data: '<Types/>' }], options);++// The offsets of the first entry's headers in an archive made by zipOf: its local header is at 0, the central directory follows the data.+const endOf = (archive) => archive.length - 22;+const centralAt = (archive) => archive.readUInt32LE(endOf(archive) + 16);+// Where each entry of an archive made by zipOf is, read from its central directory: the central header, the local header, the data and the end of it (a data descriptor starts there).+function layoutOf(archive) {+ const end = endOf(archive);+ let at = archive.readUInt32LE(end + 16);+ const entries = [];+ for (let i = 0; i < archive.readUInt16LE(end + 10); i += 1) {+ const local = archive.readUInt32LE(at + 42);+ const dataStart = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);+ const compressed = archive.readUInt32LE(at + 20);+ entries.push({ central: at, local, dataStart, dataEnd: dataStart + compressed, compressed });+ at += 46 + archive.readUInt16LE(at + 28) + archive.readUInt16LE(at + 30) + archive.readUInt16LE(at + 32);+ }+ return entries;+}+// An archive with `bytes` inserted at `at`, a place in its own bytes: the places that say where things are — the central directory's offset in the end record, and the local header offset of+// every entry that starts at or after `at` — are moved to match, so that the archive says what it says of the entries and nothing of what was put between them.+function withBytesAt(archive, at, bytes) {+ const moved = layoutOf(archive).map((entry, index) => ({ index, local: entry.local })).filter((entry) => entry.local >= at).map((entry) => entry.index);+ const grown = Buffer.concat([archive.subarray(0, at), bytes, archive.subarray(at)]);+ const end = endOf(grown);+ grown.writeUInt32LE(grown.readUInt32LE(end + 16) + bytes.length, end + 16);+ for (const index of moved) {+ const central = layoutOf(grown)[index].central;+ grown.writeUInt32LE(grown.readUInt32LE(central + 42) + bytes.length, central + 42);+ }+ return grown;+}++test('zip-read: reads an entry of the archive as the platform writes it — deflated, an extra field on the local header only, flags 0x0002', () => {+ const archive = exportZip(XML);+ assert.strictEqual(readZipEntry(archive, 'CrmTranslations.xml').toString('utf8'), XML);+ assert.strictEqual(readZipEntry(archive, '[Content_Types].xml').length > 0, true, 'the other entry is read as well, by its own headers');+ const local = archive.readUInt16LE(28);+ assert.strictEqual(local, 28, 'the fixture has what the live archive has: an extra field the central directory does not');+});++test('zip-read: reads a stored entry, an archive with a comment, and a name written as UTF-8', () => {+ assert.strictEqual(readZipEntry(archiveOf({ method: 0 }), 'CrmTranslations.xml').toString('utf8'), XML);+ assert.strictEqual(readZipEntry(archiveOf({ comment: 'made by a test' }), 'CrmTranslations.xml').toString('utf8'), XML);+ assert.strictEqual(readZipEntry(archiveOf({ localExtra: 0, flags: 0x0800 }), 'CrmTranslations.xml').toString('utf8'), XML);+ const named = zipOf([{ name: 'Traducci\u00f3n.xml', data: '<a/>' }], { flags: 0x0800 });+ assert.strictEqual(readZipEntry(named, 'Traducci\u00f3n.xml').toString('utf8'), '<a/>');+});++test('zip-read: an entry that is followed by its data descriptor — with the signature or without — is read by the central directory, whose sizes and checksum it trusts', () => {+ for (const descriptor of ['signed', 'unsigned']) {+ const archive = archiveOf({ descriptor });+ // With bit 3 set the local header carries zeros: the real values are in the descriptor after the data and in the central directory.+ assert.strictEqual(archive.readUInt16LE(6) & 0x0008, 0x0008, descriptor);+ assert.deepStrictEqual([archive.readUInt32LE(14), archive.readUInt32LE(18), archive.readUInt32LE(22)], [0, 0, 0], descriptor);+ assert.strictEqual(readZipEntry(archive, 'CrmTranslations.xml').toString('utf8'), XML, descriptor);+ assert.strictEqual(readZipEntry(archive, '[Content_Types].xml').toString('utf8'), '<Types/>', `${descriptor}: the entry after the first one starts where the descriptor ends`);+ assert.strictEqual(readZipEntry(archiveOf({ descriptor, method: 0 }), 'CrmTranslations.xml').toString('utf8'), XML, `${descriptor}: a stored entry as well`);+ }+ // A writer that fills the local header in as well as the descriptor is read the same.+ const filled = archiveOf({ descriptor: 'signed' });+ const [first] = layoutOf(filled);+ for (const [local, central] of [[14, 16], [18, 20], [22, 24]]) filled.writeUInt32LE(filled.readUInt32LE(first.central + central), local);+ assert.strictEqual(readZipEntry(filled, 'CrmTranslations.xml').toString('utf8'), XML);+});++test('zip-read: refuses an entry whose flags say a data descriptor follows its data when none does', () => {+ const archive = archiveOf({ descriptor: 'missing' });+ assert.strictEqual(archive.readUInt16LE(6) & 0x0008, 0x0008);+ assert.throws(() => readZipEntry(archive, 'CrmTranslations.xml'), (e) => e instanceof ZipReadError && /'CrmTranslations\.xml' says a data descriptor follows its data .*none/.test(e.message));+ // The second entry has none either — and the archive is as damaged to a reader that asks for the other one.+ assert.throws(() => readZipEntry(archive, '[Content_Types].xml'), /data descriptor/);+});++test('zip-read: refuses a data descriptor that is not the central directory\u2019s — another checksum, size or signature', () => {+ const base = archiveOf({ descriptor: 'signed' });+ const [first] = layoutOf(base);+ const at = first.dataEnd;+ const mutate = (change) => { const copy = Buffer.from(base); change(copy); return copy; };+ for (const [what, offset] of [['checksum', 4], ['compressed size', 8], ['uncompressed size', 12]]) {+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt32LE(b.readUInt32LE(at + offset) ^ 1, at + offset)), 'CrmTranslations.xml'), /data descriptor/, what);+ }+ // Neither a signature followed by the values nor the values alone.+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt32LE(0x12345678, at)), 'CrmTranslations.xml'), /data descriptor/, 'a signature that is not the format\u2019s');+ assert.throws(() => readZipEntry(mutate((b) => b.fill(0, at, at + 16)), 'CrmTranslations.xml'), /data descriptor/, 'zeros');+ // The unsigned form has the three values alone: a signed one read as unsigned (and the reverse) has the wrong ones.+ const unsigned = archiveOf({ descriptor: 'unsigned' });+ const [second] = layoutOf(unsigned);+ const damaged = Buffer.from(unsigned);+ damaged.writeUInt32LE(damaged.readUInt32LE(second.dataEnd + 8) + 1, second.dataEnd + 8);+ assert.throws(() => readZipEntry(damaged, 'CrmTranslations.xml'), /data descriptor/);+ // The descriptor is the one of its own entry: the first entry\u2019s numbers after the second entry\u2019s data are not the second\u2019s.+ const swapped = Buffer.from(base);+ const entries = layoutOf(base);+ base.copy(swapped, entries[1].dataEnd, entries[0].dataEnd, entries[0].dataEnd + 16);+ assert.throws(() => readZipEntry(swapped, '[Content_Types].xml'), /data descriptor/);+});++test('zip-read: with a data descriptor the local header holds zeros or the central directory\u2019s numbers — no others', () => {+ const base = archiveOf({ descriptor: 'signed' });+ for (const [what, offset] of [['checksum', 14], ['compressed size', 18], ['uncompressed size', 22]]) {+ const damaged = Buffer.from(base);+ damaged.writeUInt32LE(0x01020304, offset);+ assert.throws(() => readZipEntry(damaged, 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' does not agree with the central directory/, what);+ }+});++test('zip-read: refuses data that is longer than the deflate stream it holds — into the next entry\u2019s header, or into bytes that are no entry\u2019s', () => {+ // The entry declares four bytes more than its stream: the archive\u2019s own numbers (the next entry\u2019s offset) put those bytes in the next entry\u2019s local header.+ const into = archiveOf();+ const [first, second] = layoutOf(into);+ into.writeUInt32LE(first.compressed + 4, 18);+ into.writeUInt32LE(first.compressed + 4, first.central + 20);+ assert.ok(second.local < first.dataEnd + 4, 'the fixture\u2019s payload now overlaps the next local header');+ assert.throws(() => readZipEntry(into, 'CrmTranslations.xml'), /starts inside the data of the entry before it/);+ assert.throws(() => readZipEntry(into, '[Content_Types].xml'), /starts inside the data of the entry before it/);+ // The one entry of an archive, with four bytes after its stream that both headers count in its size: nothing overlaps, and the stream still ends four bytes short of what is declared.+ const single = zipOf([{ name: 'CrmTranslations.xml', data: XML }]);+ const [only] = layoutOf(single);+ const padded = withBytesAt(single, only.dataEnd, Buffer.alloc(4, 0x50));+ padded.writeUInt32LE(only.compressed + 4, 18);+ padded.writeUInt32LE(only.compressed + 4, layoutOf(padded)[0].central + 20);+ assert.throws(() => readZipEntry(padded, 'CrmTranslations.xml'), /deflate data of 'CrmTranslations\.xml' ends 4 bytes before the end of the data the archive gives it/);+ // A stream that ends exactly where the archive says is what it always was.+ assert.strictEqual(readZipEntry(single, 'CrmTranslations.xml').toString('utf8'), XML);+});++test('zip-read: refuses an archive whose entries are not, one after the other, every byte before the central directory', () => {+ const base = archiveOf();+ const [first, second] = layoutOf(base);+ assert.strictEqual(first.local, 0);+ assert.strictEqual(second.local, first.dataEnd, 'the fixture lays its entries end to end, as the platform does');+ assert.strictEqual(second.dataEnd, centralAt(base));+ // Bytes before the first entry.+ assert.throws(() => readZipEntry(withBytesAt(base, 0, Buffer.from('PADDING!')), 'CrmTranslations.xml'), /8 bytes of the archive before the entry 'CrmTranslations\.xml' belong to no entry/);+ // Bytes between two entries, a hidden entry that the central directory does not list among them.+ assert.throws(() => readZipEntry(withBytesAt(base, second.local, Buffer.from('PK\u0003\u0004 hidden')), 'CrmTranslations.xml'), /belong to no entry/);+ // Bytes between the last entry and the central directory.+ assert.throws(() => readZipEntry(withBytesAt(base, second.dataEnd, Buffer.from('trailing')), 'CrmTranslations.xml'), /8 bytes between the last entry and the central directory belong to no entry/);+ // The central directory lists the second entry where the first one is: they are not two entries.+ const alias = Buffer.from(base);+ alias.writeUInt32LE(first.local, second.central + 42);+ assert.throws(() => readZipEntry(alias, 'CrmTranslations.xml'), /does not agree with the central directory|starts inside/);+ // The central directory lists the entries in another order than they are in: a layout, not a list, is what is checked.+ const reordered = zipOf([{ name: 'CrmTranslations.xml', data: XML }, { name: '[Content_Types].xml', data: '<Types/>' }]);+ const swapped = Buffer.from(reordered);+ const [a, b] = layoutOf(reordered);+ reordered.copy(swapped, a.central, b.central, b.central + 46 + 19);+ reordered.copy(swapped, b.central, a.central, a.central + 46 + 19);+ assert.strictEqual(readZipEntry(swapped, 'CrmTranslations.xml').toString('utf8'), XML);+ assert.strictEqual(readZipEntry(swapped, '[Content_Types].xml').toString('utf8'), '<Types/>');+});++test('zip-read: refuses bytes between the central directory and the end record — the end record follows the directory at once, as the platform writes it', () => {+ const base = archiveOf();+ const end = endOf(base);+ assert.strictEqual(centralAt(base) + base.readUInt32LE(end + 12), end, 'the fixture ends its directory where the end record starts');+ const gap = Buffer.concat([base.subarray(0, end), Buffer.from('gap!'), base.subarray(end)]);+ assert.throws(() => readZipEntry(gap, 'CrmTranslations.xml'), /4 bytes between the central directory and the end record belong to neither/);+});++test('zip-read: refuses what is not a Buffer holding an archive', () => {+ for (const [what, value] of [['a string', 'PK'], ['nothing', undefined], ['an empty buffer', Buffer.alloc(0)], ['a short buffer', Buffer.from('PK\u0005\u0006')], ['text', Buffer.from('not a zip file at all, only text that goes on for a while')]]) {+ assert.throws(() => readZipEntry(value, 'CrmTranslations.xml'), (e) => e instanceof ZipReadError, what);+ }+ assert.throws(() => readZipEntry(Buffer.from('not a zip file at all, only text that goes on for a while'), 'x'), /no end-of-central-directory record/);+});++test('zip-read: refuses an archive that is longer than the limit — and an entry whose size is', () => {+ const archive = exportZip(XML);+ assert.throws(() => readZipEntry(archive, 'CrmTranslations.xml', { maxArchiveBytes: archive.length - 1 }), /archive is larger than/);+ assert.strictEqual(readZipEntry(archive, 'CrmTranslations.xml', { maxArchiveBytes: archive.length }).length > 0, true);+ const size = Buffer.byteLength(XML);+ assert.throws(() => readZipEntry(archive, 'CrmTranslations.xml', { maxEntryBytes: size - 1 }), /'CrmTranslations\.xml' is larger than/);+ assert.strictEqual(readZipEntry(archive, 'CrmTranslations.xml', { maxEntryBytes: size }).length, size);+});++test('zip-read: refuses an entry that is missing, and a name that is in the archive twice', () => {+ assert.throws(() => readZipEntry(exportZip(XML), 'Other.xml'), /no entry named 'Other\.xml'/);+ const twice = zipOf([{ name: 'CrmTranslations.xml', data: XML }, { name: 'CrmTranslations.xml', data: '<other/>' }]);+ assert.throws(() => readZipEntry(twice, 'CrmTranslations.xml'), /'CrmTranslations\.xml' is in the archive twice/);+});++test('zip-read: refuses an end record that does not end the archive, ZIP64 and an archive in parts', () => {+ const archive = exportZip(XML);+ assert.throws(() => readZipEntry(Buffer.concat([archive, Buffer.from('trailing bytes')]), 'CrmTranslations.xml'), /no end-of-central-directory record/);+ const end = endOf(archive);+ const zip64 = Buffer.from(archive);+ zip64.writeUInt16LE(0xffff, end + 10);+ zip64.writeUInt16LE(0xffff, end + 8);+ assert.throws(() => readZipEntry(zip64, 'CrmTranslations.xml'), /ZIP64/);+ const sizeMarker = Buffer.from(archive);+ sizeMarker.writeUInt32LE(0xffffffff, end + 16);+ assert.throws(() => readZipEntry(sizeMarker, 'CrmTranslations.xml'), /ZIP64/);+ const parts = Buffer.from(archive);+ parts.writeUInt16LE(1, end + 4);+ assert.throws(() => readZipEntry(parts, 'CrmTranslations.xml'), /more than one disk/);+ const locator = Buffer.concat([archive.subarray(0, end), Buffer.from([0x50, 0x4b, 0x06, 0x07, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), archive.subarray(end)]);+ assert.throws(() => readZipEntry(locator, 'CrmTranslations.xml'), /ZIP64/);+});++test('zip-read: refuses a central directory that is outside the archive, cut short, mis-signed or of another size than its entries', () => {+ const archive = exportZip(XML);+ const end = endOf(archive);+ const outside = Buffer.from(archive);+ outside.writeUInt32LE(archive.length, end + 16);+ assert.throws(() => readZipEntry(outside, 'CrmTranslations.xml'), /central directory lies outside/);+ const longer = Buffer.from(archive);+ longer.writeUInt32LE(longer.readUInt32LE(end + 12) + 1, end + 12);+ assert.throws(() => readZipEntry(longer, 'CrmTranslations.xml'), /central directory/);+ const signature = Buffer.from(archive);+ signature.writeUInt32LE(0x12345678, centralAt(archive));+ assert.throws(() => readZipEntry(signature, 'CrmTranslations.xml'), /entry of the central directory has a signature that is not/);+ const more = Buffer.from(archive);+ more.writeUInt16LE(3, end + 8);+ more.writeUInt16LE(3, end + 10);+ assert.throws(() => readZipEntry(more, 'CrmTranslations.xml'), /central directory/);+ const fewer = Buffer.from(archive);+ fewer.writeUInt16LE(1, end + 8);+ fewer.writeUInt16LE(1, end + 10);+ assert.throws(() => readZipEntry(fewer, 'CrmTranslations.xml'), /central directory/);+ const nameRuns = Buffer.from(archive);+ nameRuns.writeUInt16LE(0xfff0, centralAt(archive) + 28);+ assert.throws(() => readZipEntry(nameRuns, 'CrmTranslations.xml'), /runs past the central directory/);+});++test('zip-read: refuses an encrypted entry and a compression it does not read', () => {+ const encrypted = archiveOf();+ encrypted.writeUInt16LE(encrypted.readUInt16LE(centralAt(encrypted) + 8) | 0x0001, centralAt(encrypted) + 8);+ assert.throws(() => readZipEntry(encrypted, 'CrmTranslations.xml'), /is encrypted/);+ const strong = archiveOf();+ strong.writeUInt16LE(0x0040, centralAt(strong) + 8);+ assert.throws(() => readZipEntry(strong, 'CrmTranslations.xml'), /is encrypted/);+ const method = archiveOf();+ method.writeUInt16LE(12, centralAt(method) + 10);+ assert.throws(() => readZipEntry(method, 'CrmTranslations.xml'), /uses compression method 12, and only stored and deflated entries are read/);+});++test('zip-read: refuses a local header that is missing, mis-signed, truncated, or that says something else than the central directory', () => {+ const base = archiveOf();+ const mutate = (change) => { const copy = Buffer.from(base); change(copy); return copy; };+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt32LE(0, 0)), 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' has a signature that is not/);+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt32LE(b.length, centralAt(b) + 42)), 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' (?:is missing|lies outside)/);+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt16LE(0x0000, 6)), 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' does not agree with the central directory/);+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt16LE(0, 8)), 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' does not agree with the central directory/);+ assert.throws(() => readZipEntry(mutate((b) => { b[30] = 0x58; }), 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' does not agree with the central directory/);+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt32LE(b.readUInt32LE(18) + 1, 18)), 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' does not agree with the central directory/);+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt32LE(b.readUInt32LE(14) ^ 1, 14)), 'CrmTranslations.xml'), /local header of 'CrmTranslations\.xml' does not agree with the central directory/);+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt16LE(0xff00, 28)), 'CrmTranslations.xml'), /data of 'CrmTranslations\.xml' runs past the central directory/);+ assert.throws(() => readZipEntry(mutate((b) => b.writeUInt32LE(b.readUInt32LE(centralAt(b) + 20) + 50, centralAt(b) + 20)), 'CrmTranslations.xml'), /does not agree with the central directory|runs past the central directory/);+});++test('zip-read: refuses data that does not inflate, that inflates to another size than the archive says, or that fails its checksum', () => {+ const base = archiveOf();+ const dataAt = 30 + 'CrmTranslations.xml'.length + 28;+ const damaged = Buffer.from(base);+ damaged.fill(0xff, dataAt, dataAt + 8);+ assert.throws(() => readZipEntry(damaged, 'CrmTranslations.xml'), /'CrmTranslations\.xml' (?:did not inflate|failed its CRC-32 check|is not the size)/);+ // A stored entry with one byte changed inflates fine and has the right size: only the checksum says so.+ const stored = archiveOf({ method: 0 });+ stored[30 + 'CrmTranslations.xml'.length + 28 + 3] ^= 0x01;+ assert.throws(() => readZipEntry(stored, 'CrmTranslations.xml'), /'CrmTranslations\.xml' failed its CRC-32 check/);+ // A size smaller than the data inflates to — what a decompression bomb declares — is refused without inflating past it.+ const bomb = Buffer.from(base);+ bomb.writeUInt32LE(8, centralAt(bomb) + 24);+ bomb.writeUInt32LE(8, 22);+ assert.throws(() => readZipEntry(bomb, 'CrmTranslations.xml'), /'CrmTranslations\.xml' inflates to more than the 8 bytes the archive says/);+ // A size larger than the data is no better.+ const larger = Buffer.from(base);+ larger.writeUInt32LE(larger.readUInt32LE(centralAt(larger) + 24) + 5, centralAt(larger) + 24);+ larger.writeUInt32LE(larger.readUInt32LE(22) + 5, 22);+ assert.throws(() => readZipEntry(larger, 'CrmTranslations.xml'), /'CrmTranslations\.xml' is not the size the archive says/);+});++test('zip-read: the checksum is the one of the ZIP format (the table CRC-32, as the zlib that ships with newer Node has it)', () => {+ assert.strictEqual(crc32(Buffer.from('123456789')), 0xcbf43926, 'the standard check value of CRC-32');+ const zlib = require('node:zlib');+ if (typeof zlib.crc32 === 'function') assert.strictEqual(crc32(Buffer.from(XML)), zlib.crc32(Buffer.from(XML)));+});diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.jsonindex 707ba670b..8f172d545 100644--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json@@ -1,13 +1,13 @@{- "commit": "ccf2c1a11a829fe261199936493aa12f3e2bd0ed",+ "commit": "d603c7996f7918da669b3ef16c6fa63f5b9fb7a0","dirtySdkPackage": 0,- "libBuiltAt": "2026-10-19T15:37:01.994Z",- "newestSrcAt": "2026-10-18T02:54:15.290Z",+ "libBuiltAt": "2026-10-20T01:32:45.044Z",+ "newestSrcAt": "2026-10-20T01:31:52.361Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v20.20.2",- "builtAt": "2026-10-19T15:38:54.180Z",- "bundleSha256": "b8497fbc98f732df23b83d4002818612a9f41c1b94bff7bbeefc5cc60e910f36",- "bundleBytes": 1057824+ "builtAt": "2026-10-20T01:34:40.388Z",+ "bundleSha256": "16246ee08fe653de994989f08fbf4a8e243f4d3cbe961a7c89c40be37bef1a88",+ "bundleBytes": 1020302}diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjsindex f359733cc..c8ac6679b 100644--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs@@ -25,33 +25,33 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-var eq=Object.create;var qc=Object.defineProperty;var tq=Object.getOwnPropertyDescriptor;var rq=Object.getOwnPropertyNames;var nq=Object.getPrototypeOf,iq=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},nn=(e,t)=>{for(var r in t)qc(e,r,{get:t[r],enumerable:!0})},Bc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rq(t))!iq.call(e,i)&&i!==r&&qc(e,i,{get:()=>t[i],enumerable:!(n=tq(t,i))||n.enumerable});return e},so=(e,t,r)=>(Bc(e,t,"default"),r&&Bc(r,t,"default")),Ce=(e,t,r)=>(r=e!=null?eq(nq(e)):{},Bc(t||!e||!e.__esModule?qc(r,"default",{value:e,enumerable:!0}):r,e)),zr=e=>Bc(qc({},"__esModule",{value:!0}),e);var lo=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var qw;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(qw||(T.OwnershipTypes=qw={}));var Vw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Vw||(T.PrincipalType=Vw={}));var Gw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Gw||(T.ActivityTypeMask=Gw={}));var Ww;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Ww||(T.TableTypes=Ww={}));var zw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(zw||(T.TableTypeCode=zw={}));var jw;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(jw||(T.FormType=jw={}));var Hw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Hw||(T.FormPresentation=Hw={}));var Kw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Kw||(T.ActivationState=Kw={}));var Jw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Jw||(T.AttributeType=Jw={}));var Yw;(function(e){e[e.Public=0]="Public",e[e.AdvancedFind=1]="AdvancedFind",e[e.Associated=2]="Associated",e[e.QuickFind=4]="QuickFind",e[e.Lookup=64]="Lookup"})(Yw||(T.ViewType=Yw={}));var Qw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Qw||(T.ChartsType=Qw={}));var Xw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(Xw||(T.ChartType=Xw={}));var Zw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Zw||(T.ComponentState=Zw={}));var eC;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(eC||(T.PluginIsolationMode=eC={}));var tC;(function(e){e[e.BasicAuth=0]="BasicAuth"})(tC||(T.AuthType=tC={}));var rC;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(rC||(T.PluginSourceType=rC={}));var nC;(function(e){e.Boolean="Boolean",e.Customer="Customer",e.Date="Date",e.DateTime="DateTime",e.DateTimeNoTimeZone="DateTimeNoTimeZone",e.Decimal="Decimal",e.Double="Double",e.Integer="Integer",e.Lookup="Lookup",e.Memo="Memo",e.Money="Money",e.Owner="Owner",e.PartyList="PartyList",e.Picklist="Picklist",e.State="State",e.Status="Status",e.String="String",e.Uniqueidentifier="Uniqueidentifier",e.CalendarRules="CalendarRules",e.Virtual="Virtual",e.BigInt="BigInt",e.ManagedProperty="ManagedProperty",e.EntityName="EntityName"})(nC||(T.AttributeTypeCode=nC={}));var iC;(function(e){e.DateTimeType="DateTimeType",e.ImageType="ImageType",e.IntegerType="IntegerType",e.FileType="FileType",e.BooleanType="BooleanType",e.CustomerType="CustomerType",e.MemoType="MemoType",e.MultiSelectPicklistType="MultiSelectPicklistType",e.MoneyType="MoneyType",e.DecimalType="DecimalType",e.DoubleType="DoubleType",e.LookupType="LookupType",e.BigIntType="BigIntType",e.UniqueidentifierType="UniqueidentifierType",e.StringType="StringType",e.OwnerType="OwnerType",e.PicklistType="PicklistType",e.StateType="StateType",e.StatusType="StatusType",e.EntityNameType="EntityNameType"})(iC||(T.AttributeTypeName=iC={}));var oC;(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(oC||(T.AttributeFormatCode=oC={}));var aC;(function(e){e.Text="Text",e.TextArea="TextArea",e.Email="Email",e.Url="Url",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(aC||(T.AttributeFormatName=aC={}));var sC;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(sC||(T.AttributeTypeCodeNum=sC={}));var lC;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(lC||(T.OptionSetType=lC={}));var uC;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(uC||(T.StateCode=uC={}));var cC;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(cC||(T.StatusCode=cC={}));var dC;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(dC||(T.StateCodeEnabledDisabled=dC={}));var fC;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(fC||(T.StatusCodeEnabledDisabled=fC={}));var pC;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(pC||(T.WorkflowTypeCode=pC={}));var mC;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(mC||(T.WorkflowScope=mC={}));var hC;(function(e){e[e.Workflow=0]="Workflow",e[e.Dialog=1]="Dialog",e[e.BusinessRule=2]="BusinessRule",e[e.Action=3]="Action",e[e.BusinessProcessFlow=4]="BusinessProcessFlow",e[e.Flow=5]="Flow",e[e.UIFlow=6]="UIFlow"})(hC||(T.WorkflowCategory=hC={}));var gC;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(gC||(T.BusinessProcessType=gC={}));var yC;(function(e){e[e.CanvasApp=0]="CanvasApp",e[e.ComponentLibrary=1]="ComponentLibrary",e[e.CustomCanvasPage=2]="CustomCanvasPage",e[e.UnifiedApp=3]="UnifiedApp",e[e.CodeApp=4]="CodeApp",e[e.MobileApp=5]="MobileApp"})(yC||(T.AppSubType=yC={}));var bC;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(bC||(T.RelationshipType=bC={}));var vC;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(vC||(T.RelationshipTypeExt=vC={}));var wC;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(wC||(T.CascadeType=wC={}));var CC;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(CC||(T.RelationshipSecurityTypes=CC={}));var EC;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(EC||(T.ViewStatusCode=EC={}));var AC;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(AC||(T.ViewStateCode=AC={}));var SC;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(SC||(T.EntityKeyIndexStatus=SC={}));var NC;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.Tour=10061]="Tour"})(NC||(T.SolutionComponentTypeCode=NC={}));var _C;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(_C||(T.RootComponentBehavior=_C={}));var Vc;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(Vc||(T.SolutionComponentTypeCodeExt=Vc={}));var Gc;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(Gc||(T.EntityTypeCode=Gc={}));var TC;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(TC||(T.SolutionComponentVirtualAttributeSubtype=TC={}));function oq(e){let t=Vc[e];return Gc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=oq;function aq(e){let t=Gc[e];return Vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=aq;var DC;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(DC||(T.ImeMode=DC={}));var IC;(function(e){e[e.Simple=0]="Simple",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup",e[e.Formula=3]="Formula",e[e.Prompt=4]="Prompt"})(IC||(T.SourceType=IC={}));var OC;(function(e){e.Email="Email",e.Phone="Phone",e.PhoneticGuide="PhoneticGuide",e.Text="Text",e.TextArea="TextArea",e.TickerSymbol="TickerSymbol",e.Url="Url",e.VersionNumber="VersionNumber"})(OC||(T.StringFormatName=OC={}));var PC;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(PC||(T.PrecisionSource=PC={}));var RC;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(RC||(T.DateTimeBehavior=RC={}));var LC;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(LC||(T.DateTimeFormat=LC={}));var kC;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(kC||(T.IntegerFormat=kC={}));var $C;(function(e){e[e.HTML=1]="HTML",e[e.CSS=2]="CSS",e[e.JScript=3]="JScript",e[e.XML=4]="XML",e[e.PNG=5]="PNG",e[e.JPG=6]="JPG",e[e.GIF=7]="GIF",e[e.Silverlight=8]="Silverlight",e[e.XSL=9]="XSL",e[e.ICO=10]="ICO",e[e.SVG=11]="SVG",e[e.RESX=12]="RESX"})($C||(T.WebResourceTypeCode=$C={}));var xC;(function(e){e[e.Initial=5]="Initial",e[e.PreValidation=10]="PreValidation",e[e.InternalPreOperationBeforeExternal=15]="InternalPreOperationBeforeExternal",e[e.PreOperation=20]="PreOperation",e[e.InternalPreOperationAfterExternal=25]="InternalPreOperationAfterExternal",e[e.MainOperation=30]="MainOperation",e[e.InternalPostOperationBeforeExternal=35]="InternalPostOperationBeforeExternal",e[e.PostOperation=40]="PostOperation",e[e.InternalPostOperationAfterExternal=45]="InternalPostOperationAfterExternal",e[e.PostOperationDeprecated=50]="PostOperationDeprecated",e[e.FinalPostOperation=55]="FinalPostOperation"})(xC||(T.SdkMessageProcessingStage=xC={}));var FC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(FC||(T.SupportedDeployment=FC={}));var MC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(MC||(T.SdkMessageProcessingMode=MC={}));var UC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(UC||(T.ReportTypeCode=UC={}));var BC;(function(e){e[e.Business=1]="Business",e[e.Family=2]="Family",e[e.Social=3]="Social",e[e.Sales=4]="Sales",e[e.Other=5]="Other",e[e.Stakeholder=1e3]="Stakeholder",e[e.SalesTeam=1001]="SalesTeam",e[e.Service=1002]="Service"})(BC||(T.ConnectionRoleCategory=BC={}));var qC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(qC||(T.ServiceNamespaceFormat=qC={}));var VC;(function(e){e[e.OneWay=1]="OneWay",e[e.Queue=2]="Queue",e[e.Rest=3]="Rest",e[e.TwoWay=4]="TwoWay",e[e.Topic=5]="Topic",e[e.PersistentQueue=6]="PersistentQueue",e[e.EventHub=7]="EventHub",e[e.WebHook=8]="WebHook"})(VC||(T.ServiceEndpointContract=VC={}));var GC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(GC||(T.ServiceEndpointConnectionMode=GC={}));var WC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(WC||(T.DeleteDependencyErrorCode=WC={}));var zC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(zC||(T.DefaultRoleTemplates=zC={}));var jC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(jC||(T.RoleInheritance=jC={}));var HC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(HC||(T.ConnectorTypeEnum=HC={}));var KC;(function(e){e[e.String=1e8]="String",e[e.Number=100000001]="Number",e[e.Boolean=100000002]="Boolean",e[e.JSON=100000003]="JSON",e[e.ConnectionReference=100000004]="ConnectionReference",e[e.Secret=100000005]="Secret"})(KC||(T.EnvironmentVariableDefinitionTypeEnum=KC={}));var JC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(JC||(T.TeamTypeEnum=JC={}));var YC;(function(e){e.Bots="bots"})(YC||(T.KnownCustomSolutionComponentEntitySetName=YC={}));var QC;(function(e){e[e.MainApplicationView=0]="MainApplicationView",e[e.AdvancedSearch=1]="AdvancedSearch",e[e.SubGrid=2]="SubGrid",e[e.QuickFindSearch=4]="QuickFindSearch",e[e.Reporting=8]="Reporting",e[e.OfflineFilters=16]="OfflineFilters",e[e.MASearch=32]="MASearch",e[e.LookupView=64]="LookupView",e[e.SMAppointmentBookView=128]="SMAppointmentBookView",e[e.OutlookFilters=256]="OutlookFilters",e[e.AddressBookFilters=512]="AddressBookFilters",e[e.SavedQueryTypeOther=2048]="SavedQueryTypeOther",e[e.InteractiveWorkflowView=4096]="InteractiveWorkflowView",e[e.OfflineTemplate=8192]="OfflineTemplate",e[e.OutlookTemplate=131072]="OutlookTemplate",e[e.CustomDefinedView=16384]="CustomDefinedView"})(QC||(T.QueryType=QC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readPcfRegistrationProgress=X.withPcfRegistrationProgress=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var _t=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=_t;var XC=Symbol.for("cds-maker-sdk.partialWriteTokens");function sq(e,t){return typeof e=="object"&&e!==null&&(e[XC]=t),e}X.withPartialTokens=sq;function lq(e){return Wc(e,XC)}X.readPartialTokens=lq;function Wc(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var ZC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function uq(e,t){return typeof e=="object"&&e!==null&&(e[ZC]=t),e}X.withPartialEnrichment=uq;function cq(e){return Wc(e,ZC)}X.readPartialEnrichment=cq;var qm=Symbol.for("cds-maker-sdk.cleanupWarnings");function dq(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[qm];r[qm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=dq;function fq(e){let t=Wc(e,qm);return t?[...t]:void 0}X.readCleanupWarnings=fq;var eE=Symbol.for("cds-maker-sdk.pcfRegistrationProgress");function tE(e){return{...e,written:[...e.written],unconfirmed:[...e.unconfirmed],published:[...e.published],publishedUnknown:[...e.publishedUnknown],temporaries:[...e.temporaries]}}function pq(e,t){return typeof e=="object"&&e!==null&&(e[eE]=tE(t)),e}X.withPcfRegistrationProgress=pq;function mq(e){let t=Wc(e,eE);return t?tE(t):void 0}X.readPcfRegistrationProgress=mq;var Vm=class extends _t{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=Vm;var Gm=class extends _t{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=Gm;var Wm=class extends _t{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:+var AU=Object.create;var bc=Object.defineProperty;var SU=Object.getOwnPropertyDescriptor;var NU=Object.getOwnPropertyNames;var _U=Object.getPrototypeOf,TU=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Hr=(e,t)=>{for(var r in t)bc(e,r,{get:t[r],enumerable:!0})},yc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of NU(t))!TU.call(e,i)&&i!==r&&bc(e,i,{get:()=>t[i],enumerable:!(n=SU(t,i))||n.enumerable});return e},Ji=(e,t,r)=>(yc(e,t,"default"),r&&yc(r,t,"default")),Ee=(e,t,r)=>(r=e!=null?AU(_U(e)):{},yc(t||!e||!e.__esModule?bc(r,"default",{value:e,enumerable:!0}):r,e)),Fr=e=>yc(bc({},"__esModule",{value:!0}),e);var Yi=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 Yv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(Yv||(T.OwnershipTypes=Yv={}));var Qv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Qv||(T.PrincipalType=Qv={}));var Xv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Xv||(T.ActivityTypeMask=Xv={}));var Zv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Zv||(T.TableTypes=Zv={}));var ew;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(ew||(T.TableTypeCode=ew={}));var tw;(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"})(tw||(T.FormType=tw={}));var rw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(rw||(T.FormPresentation=rw={}));var nw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(nw||(T.ActivationState=nw={}));var iw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(iw||(T.AttributeType=iw={}));var ow;(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"})(ow||(T.ViewType=ow={}));var aw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(aw||(T.ChartsType=aw={}));var sw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(sw||(T.ChartType=sw={}));var lw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(lw||(T.ComponentState=lw={}));var uw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(uw||(T.PluginIsolationMode=uw={}));var cw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(cw||(T.AuthType=cw={}));var dw;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(dw||(T.PluginSourceType=dw={}));var fw;(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"})(fw||(T.AttributeTypeCode=fw={}));var pw;(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"})(pw||(T.AttributeTypeName=pw={}));var mw;(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"})(mw||(T.AttributeFormatCode=mw={}));var hw;(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"})(hw||(T.AttributeFormatName=hw={}));var gw;(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"})(gw||(T.AttributeTypeCodeNum=gw={}));var yw;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(yw||(T.OptionSetType=yw={}));var bw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(bw||(T.StateCode=bw={}));var vw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(vw||(T.StatusCode=vw={}));var ww;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(ww||(T.StateCodeEnabledDisabled=ww={}));var Cw;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Cw||(T.StatusCodeEnabledDisabled=Cw={}));var Ew;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Ew||(T.WorkflowTypeCode=Ew={}));var Aw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Aw||(T.WorkflowScope=Aw={}));var Sw;(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"})(Sw||(T.WorkflowCategory=Sw={}));var Nw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Nw||(T.BusinessProcessType=Nw={}));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 Tw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Tw||(T.RelationshipType=Tw={}));var Dw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Dw||(T.RelationshipTypeExt=Dw={}));var Iw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Iw||(T.CascadeType=Iw={}));var Ow;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Ow||(T.RelationshipSecurityTypes=Ow={}));var Pw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Pw||(T.ViewStatusCode=Pw={}));var Rw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Rw||(T.ViewStateCode=Rw={}));var Lw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Lw||(T.EntityKeyIndexStatus=Lw={}));var kw;(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"})(kw||(T.SolutionComponentTypeCode=kw={}));var $w;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})($w||(T.RootComponentBehavior=$w={}));var vc;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(vc||(T.SolutionComponentTypeCodeExt=vc={}));var wc;(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"})(wc||(T.EntityTypeCode=wc={}));var xw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(xw||(T.SolutionComponentVirtualAttributeSubtype=xw={}));function DU(e){let t=vc[e];return wc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=DU;function IU(e){let t=wc[e];return vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=IU;var Fw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Fw||(T.ImeMode=Fw={}));var Mw;(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"})(Mw||(T.SourceType=Mw={}));var Uw;(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"})(Uw||(T.StringFormatName=Uw={}));var Bw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Bw||(T.PrecisionSource=Bw={}));var qw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(qw||(T.DateTimeBehavior=qw={}));var Vw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Vw||(T.DateTimeFormat=Vw={}));var Gw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Gw||(T.IntegerFormat=Gw={}));var Ww;(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"})(Ww||(T.WebResourceTypeCode=Ww={}));var zw;(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"})(zw||(T.SdkMessageProcessingStage=zw={}));var jw;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(jw||(T.SupportedDeployment=jw={}));var Hw;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Hw||(T.SdkMessageProcessingMode=Hw={}));var Kw;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(Kw||(T.ReportTypeCode=Kw={}));var Jw;(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"})(Jw||(T.ConnectionRoleCategory=Jw={}));var Yw;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Yw||(T.ServiceNamespaceFormat=Yw={}));var Qw;(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"})(Qw||(T.ServiceEndpointContract=Qw={}));var Xw;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(Xw||(T.ServiceEndpointConnectionMode=Xw={}));var Zw;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(Zw||(T.DeleteDependencyErrorCode=Zw={}));var eC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(eC||(T.DefaultRoleTemplates=eC={}));var tC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(tC||(T.RoleInheritance=tC={}));var rC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(rC||(T.ConnectorTypeEnum=rC={}));var nC;(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"})(nC||(T.EnvironmentVariableDefinitionTypeEnum=nC={}));var iC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(iC||(T.TeamTypeEnum=iC={}));var oC;(function(e){e.Bots="bots"})(oC||(T.KnownCustomSolutionComponentEntitySetName=oC={}));var aC;(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"})(aC||(T.QueryType=aC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var wt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=wt;var sC=Symbol.for("cds-maker-sdk.partialWriteTokens");function OU(e,t){return typeof e=="object"&&e!==null&&(e[sC]=t),e}X.withPartialTokens=OU;function PU(e){return wm(e,sC)}X.readPartialTokens=PU;function wm(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 lC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function RU(e,t){return typeof e=="object"&&e!==null&&(e[lC]=t),e}X.withPartialEnrichment=RU;function LU(e){return wm(e,lC)}X.readPartialEnrichment=LU;var im=Symbol.for("cds-maker-sdk.cleanupWarnings");function kU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[im];r[im]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=kU;function $U(e){let t=wm(e,im);return t?[...t]:void 0}X.readCleanupWarnings=$U;var om=class extends wt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=om;var am=class extends wt{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=am;var sm=class extends wt{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=Wm;var zm=class extends _t{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=zm;var jm=class extends _t{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=jm;var Hm=class extends _t{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};X.LocalEditsWouldBeLostError=Hm;var Km=class extends _t{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=Km;var Jm=class extends _t{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=Jm;function hq(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=hq;var Ym=class extends _t{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Ym;var Qm=class extends _t{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=Qm;var Xm=class extends _t{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Xm;var Zm=class extends _t{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Zm;var eh=class extends _t{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};X.AmbiguousArtifactError=eh;var th=class extends _t{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};X.PathTraversalError=th;var rh=class extends _t{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};X.IncompatibleWorkspaceError=rh});var oe=v(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.odataQuery=at.normalizeGuid=at.createSafeXmlElement=at.assertNoControlChars=at.assertODataName=at.assertXmlName=at.xmlText=at.odataPathLiteral=at.odataLiteral=void 0;var zc=Q();function rE(e){return String(e??"").replace(/'/g,"''")}at.odataLiteral=rE;function gq(e){return encodeURIComponent(rE(e))}at.odataPathLiteral=gq;function yq(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}at.xmlText=yq;function nE(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new zc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}at.assertXmlName=nE;function bq(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new zc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}at.assertODataName=bq;function vq(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new zc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}at.assertNoControlChars=vq;function wq(e,t,r){return e.createElement(nE(t,r))}at.createSafeXmlElement=wq;var Cq=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function Eq(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!Cq.test(n))throw new zc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}at.normalizeGuid=Eq;function Aq(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}at.odataQuery=Aq});var fe=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Ka=Q(),Ja=oe();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function Sq(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=Sq;function iE(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=iE;function Nq(e,t,r){if(!iE(e))throw new Ka.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"no concurrency token is held for it"}, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}j.requireEtag=Nq;function oE(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}j.readEtag=oE;async function _q(e,t,r,n){let i=`/${t}(${n})${(0,Ja.odataQuery)([["$select",r]])}`;return oE(ih(await e.get(i),e.apiUrl(i)))}j.readRowEtag=_q;function nh(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ja.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ja.normalizeGuid)(a[1],t)}return null}j.readCreatedId=nh;function Tq(e,t,r){return r?{...e,[t]:(0,Ja.normalizeGuid)(r,t)}:e}j.withClientMintedId=Tq;function Dq(e,t,r){let n=nh(e,t);if(!n)throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=Dq;function Iq(e,t,r,n){let i=nh(e,t);if(i)return i;if(n)return(0,Ja.normalizeGuid)(n,t);throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=Iq;function ih(e,t){if(e.status===412)throw new Ka.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Ka.ConnectionError(t,e.status,$q(e.body),e.body);return e}j.ensureSuccess=ih;function aE(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=aE;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function Oq(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=Oq;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function Pq(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=Pq;var Rq=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function sE(e){return Rq.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=sE;function lE(e){return e.status!==400||e.body===void 0||e.body===null?!1:sE(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=lE;async function oh(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=oh;function Lq(e){return oh(aE,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=Lq;function kq(e){return oh(lE,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=kq;function $q(e){if(typeof e=="string"&&e.length>0)return e;if(e!==null&&typeof e=="object"){let t=e;if(t.error&&typeof t.error.message=="string")return t.error.message;if(typeof t.Message=="string")return t.Message;if(typeof t.message=="string")return t.message}return"request failed"}async function xq(e,t,r,n){let i=(0,Ja.normalizeGuid)(r,"id"),o=`/${t}(${i})`;ih(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=xq;function Fq(e){return e instanceof Ka.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=Fq;function Mq(){return new Date().toISOString()}j.nowIso=Mq});var Tt=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.describeMalformedValue=Ya.collectPages=void 0;var uE=fe(),ah=Q();async function Uq(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,uE.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${sh(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${sh(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new ah.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,uE.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}Ya.collectPages=Uq;function sh(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Ya.describeMalformedValue=sh});var lh=v(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.assertWorkflowKind=Ho.WORKFLOW_KIND_MISMATCH_CODE=void 0;var jo=lo(),Bq=Q(),cE=fe(),qq=oe();Ho.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var dE={[jo.WorkflowCategory.Workflow]:"classic workflow",[jo.WorkflowCategory.Dialog]:"dialog",[jo.WorkflowCategory.BusinessRule]:"business rule",[jo.WorkflowCategory.Action]:"custom action",[jo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[jo.WorkflowCategory.Flow]:"cloud flow",[jo.WorkflowCategory.UIFlow]:"desktop flow"};async function Vq(e,t,r){var n,i;let o=`/workflows(${t})${(0,qq.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,cE.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=dE[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new Bq.SdkError(Ho.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${dE[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,cE.readEtag)(a)}Ho.assertWorkflowKind=Vq});var ch=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.deleteWorkflowResending=on.isWorkflowDeleteUnsettled=on.failedAfterResend=on.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var $l=Q(),_i=fe(),pE=oe();on.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var mE=new WeakSet;function uh(e){return typeof e=="object"&&e!==null&&mE.add(e),e}function Gq(e){return typeof e=="object"&&e!==null&&mE.has(e)}on.failedAfterResend=Gq;function Wq(e){return e instanceof $l.SdkError&&e.code===on.WORKFLOW_DELETE_UNSETTLED_CODE}on.isWorkflowDeleteUnsettled=Wq;function zq(e,t){try{(0,_i.ensureSuccess)(e,t)}catch(r){return r}}function jq(e){return(0,_i.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${_i.TRANSACTION_NOT_STARTED_CODE})`}async function fE(e,t){try{return(await e.get(`/workflows(${t})${(0,pE.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function Hq(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,pE.normalizeGuid)(t,"id");if(a&&!r)throw new $l.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,_i.isTransactionNotStarted)(p)||o&&(0,_i.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,_i.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?_i.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof $l.ConnectionError&&p.statusCode===0&&r&&await fE(e,s))return;throw d>1?uh(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=jq(f),h=new $l.SdkError(on.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw uh((0,$l.attachCause)(h,zq(f,u)))}if(!(r&&_i.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await fE(e,s)))try{(0,_i.ensureSuccess)(m,u)}catch(p){throw d>1?uh(p):p}}}on.deleteWorkflowResending=Hq});var dh=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.businessRuleApi=Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Hn.WFOM_API_UNAVAILABLE_CODE=void 0;var jn=lo(),Kq=Tt(),Jq=lh(),Yq=ch(),Kt=fe(),Ti=oe(),Hc=Q();Hn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function hE(e,t,r,n){let i=`/workflows(${Zq})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Kt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Hc.SdkError(Hn.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function Qq(e,t){let r=`/workflows(${t})${(0,Ti.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let n=await e.get(r);if(n.status<200||n.status>=300)return null;let i=n.body;return{etag:(0,Kt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function Xq(e,t,r){let n=await Qq(e,t);if(n===null||n.etag===null)throw new Hc.SdkError(Kt.VERSION_CONFLICT_CODE,`Refusing to update business rule '${t}': its current version could not be read, so the write could not be verified as conditional. The supported update api does not enforce If-Match, so proceeding would risk silently overwriting a concurrent edit. Re-fetch the rule and try again.`);if(n.etag!==r)throw new Hc.SdkError(Kt.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${r}, server ${n.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:n.statecode,statuscode:n.statuscode}}var Zq="00000000-0000-0000-0000-000000000000",jc={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},e3="workflowid,name,description,primaryentity,statecode,category,type",t3="category eq 2 and type eq 1";async function gE(e,t,r){var n;if(r==="Draft")return null;let i=(0,Ti.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?jn.StateCode.Activated:jn.StateCode.Draft,statuscode:o?jn.StatusCode.Activated:jn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Kt.ensureSuccess)(await e.patch(s,a,{headers:jc}),e.apiUrl(s));return(n=(0,Kt.readEtag)(l))!==null&&n!==void 0?n:await xl(e,i)}async function xl(e,t){let r=`/workflows(${t})${(0,Ti.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Kt.readEtag)(n):null}catch{return null}}async function r3(e,t,r){let n=await xl(e,t),i=await r(),o=(0,Kt.readEtag)(i);if(o)return{response:i,etag:o};let a=await xl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Hn.businessRuleApi={async get(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await r3(e,r,async()=>(0,Kt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[t3];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Ti.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Ti.odataQuery)([["$select",e3],["$filter",r.join(" and ")]])}`;return(await(0,Kq.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Ti.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await hE(e,"CreateProcessWithWfomJson",n,jc),a=(0,Kt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await gE(e,a,n.status)}catch(l){try{await(0,Kt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Kt.readEtag)(o))!==null&&r!==void 0?r:await xl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,Ti.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...jc,"If-Match":(0,Kt.requireEtag)(n,"business rule",s)},c=await Xq(e,s,u["If-Match"]),d=c.statecode===jn.StateCode.Activated;d&&(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Draft,statuscode:jn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await hE(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:jn.StatusCode.Activated},{headers:jc}),e.apiUrl(l))}catch(h){throw new Hc.SdkError(Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await gE(e,s,a.status);return{id:s,etag:(o=m??(0,Kt.readEtag)(f))!==null&&o!==void 0?o:await xl(e,s)}},async delete(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=await(0,Jq.assertWorkflowKind)(e,r,jn.WorkflowCategory.BusinessRule);return(0,Yq.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var jr=v(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.publishBoundEntity=st.boundEntityPublishScope=st.publishGenPageById=st.publishDashboardById=st.publishWebResourceById=st.publishEntity=st.publishAppModule=st.publishAllXml=st.publishXml=void 0;var Kc=fe(),Fl=oe(),yE="/PublishXml";async function Qa(e,t){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(yE,{ParameterXml:t})),e.apiUrl(yE))}st.publishXml=Qa;var bE="/PublishAllXml";async function n3(e){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(bE,{})),e.apiUrl(bE))}st.publishAllXml=n3;function i3(e,t){return Qa(e,`<importexportxml><appmodules><appmodule>${(0,Fl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}st.publishAppModule=i3;function vE(e,t){return Qa(e,`<importexportxml><entities><entity>${(0,Fl.xmlText)(t)}</entity></entities></importexportxml>`)}st.publishEntity=vE;function o3(e,t){return Qa(e,`<importexportxml><webresources><webresource>${(0,Fl.xmlText)(t)}</webresource></webresources></importexportxml>`)}st.publishWebResourceById=o3;function a3(e,t){return Qa(e,`<importexportxml><dashboards><dashboard>${(0,Fl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}st.publishDashboardById=a3;function s3(e,t){return Qa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Fl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}st.publishGenPageById=s3;function l3(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}st.boundEntityPublishScope=l3;function u3(e,t){let r=t?.entityLogicalName;return r?vE(e,r):Promise.resolve()}st.publishBoundEntity=u3});var Xa=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.JsonPointer=void 0;var Hr=Q(),Jc=class e{static isReservedToken(t){return e.RESERVED_TOKENS.has(t)}static decodeToken(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}static encodeToken(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}static parse(t){if(t==="")return[];if(t[0]!=="/")throw new Hr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Hr.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Hr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Hr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Hr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Hr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Hr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Hr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Hr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Hr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Hr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Hr.JsonPointerError(r,`insert index ${s} is out of range`);a.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Hr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Yc.JsonPointer=Jc;Jc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var CE=v(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.findElements=void 0;var wE=Xa();function c3(e,t){let r=[];return fh(e,"",t,r),r}Qc.findElements=c3;function fh(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{fh(i,wE.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))fh(e[i],wE.JsonPointer.append(t,i),r,n)}});var ph=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assertMutationResult=Kn.assertExistsResult=Kn.assertReadResult=Kn.assertStorageContract=void 0;var d3=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],f3=["ensureContainer","exists"];function p3(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of d3)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of f3){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Kn.assertStorageContract=p3;function m3(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Kn.assertReadResult=m3;function h3(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Kn.assertExistsResult=h3;function g3(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Kn.assertMutationResult=g3});var mh=v(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.retryTransientIoAsync=Za.retryTransientIo=void 0;var y3=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),b3=5,EE=10;function v3(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!AE(r,t))throw r;C3(EE*t)}}Za.retryTransientIo=v3;async function w3(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!AE(r,t))throw r;await new Promise(n=>setTimeout(n,EE*t))}}Za.retryTransientIoAsync=w3;function AE(e,t){let r=e.code;return t<b3&&!!r&&y3.has(r)}function C3(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var DE=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.canonicalArtifactId=Kr.WorkspaceManager=Kr.WORKSPACE_SCHEMA_VERSION=Kr.retryTransientIo=void 0;var Jt=ph(),Jn=Q(),E3=mh();Object.defineProperty(Kr,"retryTransientIo",{enumerable:!0,get:function(){return E3.retryTransientIo}});function SE(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Kr.WORKSPACE_SCHEMA_VERSION=1;var uo={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},A3="manifest.json",es=".metadata",hh="entities";function NE(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function gh(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Kr.WORKSPACE_SCHEMA_VERSION)throw new Jn.IncompatibleWorkspaceError(e.schemaVersion,Kr.WORKSPACE_SCHEMA_VERSION)}function _E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var yh=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[uo[t],`${Ml(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[es,uo[t],`${Ml(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[es,hh,`${t.toLowerCase()}.json`]}fsStore(){let t=SE(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=SE(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([uo[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Jn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[A3]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Jn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[es,hh]];for(let i of Object.keys(uo))r.push([uo[i]],[es,uo[i]]);let n=await Promise.allSettled(r.map(i=>NE(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Jt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!_E(t))throw new Jn.WorkspaceOrgMismatchError("",this.instanceUrl);gh(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Xc(r);if(!n||n!==Xc(this.instanceUrl))throw new Jn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!_E(t.value))throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;gh(r);let n=Object.keys(uo).map(o=>[uo[o]]);n.push([es]);let i=await Promise.allSettled(n.map(o=>NE(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Jt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Jt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=TE(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Ml(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Jt.assertMutationResult)(await this.storage.deleteByPrefix([es,hh]),"deleteByPrefix");return}(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);return gh(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Kr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Xc(String(t.instanceUrl))!==Xc(r.instanceUrl))throw new Jn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Ml(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(t,TE(r)),"writeTextAtomic")}};Kr.WorkspaceManager=yh;function TE(e){return`${JSON.stringify(e,null,2)}-`}function Ml(e){let r=/^\{?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}Kr.canonicalArtifactId=Ml});var bh=v(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.deepEqual=ts.deepDiff=void 0;var S3=Xa();function N3(e,t){let r=[];return OE(e,t,"",r,0),r}ts.deepDiff=N3;var Zc=Symbol("missing"),ed=512;function OE(e,t,r,n,i){if(e===t)return;if(i>ed)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ed}`);let o=td(e),a=td(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=_3(e,t);for(let l of s){let u=IE(e,l),c=IE(t,l),d=S3.JsonPointer.append(r,l);u===Zc?n.push({pointer:d,type:"added",newValue:c}):c===Zc?n.push({pointer:d,type:"removed",oldValue:u}):OE(u,c,d,n,i+1)}return}PE(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function td(e){return e!==null&&typeof e=="object"}function _3(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function IE(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Zc}return t in e?e[t]:Zc}function PE(e,t){return RE(e,t,0)}ts.deepEqual=PE;function RE(e,t,r){if(e===t)return!0;if(r>ed)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ed}`);if(!td(e)||!td(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(o=>o in t&&RE(e[o],t[o],r+1))}});var kE=v(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.VersionManager=rs.PROJECTION_VERSION=void 0;var LE=bh(),T3=fe();rs.PROJECTION_VERSION=8;var vh=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,LE.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,LE.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,T3.isVersionToken)(i.etag)?!0:i.etag!==n}};rs.VersionManager=vh});var xE=v((wh,$E)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof wh=="object"?$E.exports=t():e.compareVersions=t()})(wh,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var qE=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.EnvironmentFlowHostingType=Je.EnvironmentDisableReasonCode=Je.EnvironmentMigrationConstants=Je.EnvironmentProvisioningStates=Je.EnvironmentLocations=Je.EnvironmentCreationTypeConstants=Je.EnvironmentType=Je.EnvironmentSkuConstants=Je.environmentPermissions=Je.DatabaseType=void 0;var FE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(FE||(Je.DatabaseType=FE={}));Je.environmentPermissions={CreatePowerApp:"CreatePowerApp",ReadEnvironment:"ReadEnvironment",GenerateResourceStorage:"GenerateResourceStorage",CreateGateway:"CreateGateway",CreateFlow:"CreateFlow",CreateCustomApi:"CreateCustomApi",AdminReadEnvironment:"AdminReadEnvironment",UpdateEnvironment:"UpdateEnvironment",DeleteEnvironment:"DeleteEnvironment",ExportEnvironmentPackage:"ExportEnvironmentPackage",SetDLPPolicy:"SetDLPPolicy",ListAnyPowerApp:"ListAnyPowerApp",ListAnyFlow:"ListAnyFlow",DeleteAnyPowerApp:"DeleteAnyPowerApp",DeleteAnyFlow:"DeleteAnyFlow",AddEnvironmentRoleAssignment:"AddEnvironmentRoleAssignment",ReadEnvironmentRoleInformation:"ReadEnvironmentRoleInformation",RemoveEnvironmentRoleAssignment:"RemoveEnvironmentRoleAssignment",ModifyDatabaseRoleAssignments:"ModifyDatabaseRoleAssignments",CreateDatabase:"CreateDatabase",ListDatabaseEntities:"ListDatabaseEntities",CreateDatabaseEntities:"CreateDatabaseEntities",UpdateDatabaseEntities:"UpdateDatabaseEntities",DeleteDatabaseEntities:"DeleteDatabaseEntities"};Je.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var ME;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(ME||(Je.EnvironmentType=ME={}));Je.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Je.EnvironmentLocations={global:"global",unitedStates:"unitedstates",southamerica:"southamerica",europe:"europe",canada:"canada",preview:"unitedstatesfirstrelease",asia:"asia",japan:"japan",australia:"australia",india:"india",unitedkingdom:"unitedkingdom",france:"france",germany:"germany",brazil:"brazil",usgov:"usgov",usgovhigh:"usgovhigh",uae:"unitedarabemirates",switzerland:"switzerland",mooncake:"china",korea:"korea",norway:"norway",southafrica:"southafrica",dod:"usdod",singapore:"singapore",sweden:"sweden",italy:"italy",poland:"poland"};Je.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Je.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var UE;(function(e){e.NotSpecified="NotSpecified",e.NoValidLicense="NoValidLicense",e.SuspendedLicense="SuspendedLicense",e.TrialExpiration="TrialExpiration",e.UserRequested="UserRequested",e.InstanceStateUpdate="InstanceStateUpdated",e.InactivityThreshold="InactivityThreshold",e.OperationsInitiated="OperationsInitiated",e.EnvironmentLifecycleOperation="EnvironmentLifecycleOperation",e.TenantPolicyEvaluation="TenantPolicyEvaluation"})(UE||(Je.EnvironmentDisableReasonCode=UE={}));var BE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(BE||(Je.EnvironmentFlowHostingType=BE={}))});var JE=v(_=>{"use strict";var D3=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var I3=D3(xE()),Oe=qE(),Ul=Eh();function O3(e){let t=Ii(e);return t&&t.version}_.getCrmVersion=O3;function Ii(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=Ii;function Di(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=Di;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Ko(e){return!!Ii(e)&&VE(e)}_.environmentHasCds2Database=Ko;function P3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=P3;function R3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=R3;function L3(e){if(e&&Ko(e)){let t=co(e);(0,Ul.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=L3;function k3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=k3;function $3(e){return e&&Ko(e)?co(e):""}_.getAllThemesUrl=$3;function VE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=VE;function x3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=x3;function F3(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=F3;function co(e){let t=Ii(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=co;function M3(e){let t=Ii(e);return t?t.uniqueName:""}_.getCrmInstanceName=M3;function U3(e){return Ii(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=U3;function B3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=B3;function q3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=q3;function V3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=V3;function Bl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Bl;function G3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=G3;var W3=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=W3;function z3(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=z3;function j3(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=j3;function H3(e){return e&&e.properties&&Di(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=H3;function K3(e){return!!(e&&e.properties&&e.properties.provisioningState&&KE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=K3;function J3(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=J3;function Y3(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=Y3;function Q3(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Q3;function X3(e){return!!e&&!!e.properties&&!!e.properties.linkedEnvironmentMetadata&&e.properties.linkedEnvironmentMetadata.platformSku==="Lite"&&!!e.properties.states&&!!e.properties.states.management&&e.properties.states.management.id==="Running"&&!!e.properties.ongoingOperation&&!!e.properties.ongoingOperation.type&&e.properties.ongoingOperation.type.id==="Promote"}_.isLiteEnvironmentUpgrading=X3;function Z3(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Z3;function e4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=e4;function t4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=t4;function r4(e){return e&&e.name||""}_.getEnvironmentName=r4;function n4(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=n4;var GE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function i4(e){return jE(e,GE)}_.doesCds2EnvironmentSupportApiVersion9_1=i4;function o4(e){return Ch(e,GE)}_.doesCds2VersionSupportApiVersion9_1=o4;function WE(e){let t=Ii(e);if(t)return t.securityGroupId}function zE(e){return e&&e.properties&&e.properties.connectedGroups}function a4(e,t){let r=zE(e);return!!r&&!!r.find(n=>n.id===t)||WE(e)===t}_.hasSecurityGroupId=a4;function s4(e){let t=zE(e);return t&&t.length>0&&t[0].id?t[0].id:WE(e)}_.getSecurityOrConnectedGroupId=s4;function jE(e,t){let r=e.version;return r?Ch(r,t):!1}_.isCds2EnvironmentVersionAtLeast=jE;function Ch(e,t){return t?e?(0,I3.default)(e,t)>=0:!1:!0}_.checkVersions=Ch;function l4(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=l4;function u4(e){let t=Ii(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=u4;function HE(e){let t=Ii(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=HE;function c4(e){let t=HE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=c4;function d4(e){let t=co(e);if(t==="")return"";let r=t.split("/");if(r.length!==4)return"";let n=r[2].split(".");return n[0]="globaldisco",r[2]=n.join("."),r.join("/")+"api/discovery/v2.0/Instances"}_.getEnvironmentDiscoveryUrl=d4;var f4=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=f4;var p4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=p4;var m4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=m4;var h4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=h4;var g4=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=g4;var y4=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Di((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=y4;var b4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=b4;function KE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=KE;var v4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=v4;var w4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=w4;var C4=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=C4;var E4=e=>{var t,r;return!Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&Di((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=E4});var Eh=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var YE=JE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Vl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Vl||(Vl={}));function A4(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=A4;function S4(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=S4;function N4(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=N4;function _4(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=_4;function T4(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=T4;function D4(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=D4;function Ah(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function I4(e){return Ah(e,Vl.AllSolutions)}A.getCrmAllSolutionsUrl=I4;function O4(e){return Ah(e,Vl.AllPublishers)}A.getCrmAllPublishersUrl=O4;function P4(e){return Ah(e,Vl.DevResources)}A.getCrmDevResourcesUrl=P4;function R4(e,t=YE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=R4;function L4(e){return`${e}apps`}A.getCrmMyAppsUrl=L4;function k4(e){return QE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=k4;function $4(e){return`${QE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=$4;function QE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function x4(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=x4;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function F4(e,t,r=YE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=F4;function M4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=M4;function U4(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=U4;function B4(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=B4;function q4(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=q4;function V4(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=V4;function G4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=G4;function W4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=W4;function z4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=z4;function j4(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=j4;function H4(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=H4;function K4(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=K4;function J4(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=J4;function Y4(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=Y4;function Q4(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=Q4;function X4(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=X4;function Z4(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=Z4;function eV(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=eV;function tV(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=tV;function rV(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=rV;function nV(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=nV;function iV(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=iV;function oV(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=oV;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function aV(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=aV;function sV(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=sV;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function lV(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=lV;function uV(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=uV;function cV(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=cV;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function dV(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns+`)),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=sm;var lm=class extends wt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=lm;var um=class extends wt{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=um;var cm=class extends wt{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=cm;var dm=class extends wt{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=dm;var fm=class extends wt{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=fm;function xU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=xU;var pm=class extends wt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=pm;var mm=class extends wt{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=mm;var hm=class extends wt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=hm;var gm=class extends wt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=gm;var ym=class extends wt{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=ym;var bm=class extends wt{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=bm;var vm=class extends wt{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=vm});var se=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.odataQuery=rt.normalizeGuid=rt.createSafeXmlElement=rt.assertNoControlChars=rt.assertODataName=rt.assertXmlName=rt.xmlText=rt.odataPathLiteral=rt.odataLiteral=void 0;var Cc=Q();function uC(e){return String(e??"").replace(/'/g,"''")}rt.odataLiteral=uC;function FU(e){return encodeURIComponent(uC(e))}rt.odataPathLiteral=FU;function MU(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}rt.xmlText=MU;function cC(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 Cc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}rt.assertXmlName=cC;function UU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Cc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}rt.assertODataName=UU;function BU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Cc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}rt.assertNoControlChars=BU;function qU(e,t,r){return e.createElement(cC(t,r))}rt.createSafeXmlElement=qU;var VU=/^[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 GU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!VU.test(n))throw new Cc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}rt.normalizeGuid=GU;function WU(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}rt.odataQuery=WU});var ye=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Pa=Q(),Ra=se();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function zU(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=zU;function dC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=dC;function jU(e,t,r){if(!dC(e))throw new Pa.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"no concurrency token is held for it"}, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}j.requireEtag=jU;function fC(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}j.readEtag=fC;async function HU(e,t,r,n){let i=`/${t}(${n})${(0,Ra.odataQuery)([["$select",r]])}`;return fC(Em(await e.get(i),e.apiUrl(i)))}j.readRowEtag=HU;function Cm(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ra.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ra.normalizeGuid)(a[1],t)}return null}j.readCreatedId=Cm;function KU(e,t,r){return r?{...e,[t]:(0,Ra.normalizeGuid)(r,t)}:e}j.withClientMintedId=KU;function JU(e,t,r){let n=Cm(e,t);if(!n)throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=JU;function YU(e,t,r,n){let i=Cm(e,t);if(i)return i;if(n)return(0,Ra.normalizeGuid)(n,t);throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=YU;function Em(e,t){if(e.status===412)throw new Pa.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Pa.ConnectionError(t,e.status,rB(e.body),e.body);return e}j.ensureSuccess=Em;function pC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=pC;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function QU(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=QU;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function XU(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=XU;var ZU=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function mC(e){return ZU.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=mC;function hC(e){return e.status!==400||e.body===void 0||e.body===null?!1:mC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=hC;async function Am(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=Am;function eB(e){return Am(pC,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=eB;function tB(e){return Am(hC,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=tB;function rB(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 nB(e,t,r,n){let i=(0,Ra.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Em(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=nB;function iB(e){return e instanceof Pa.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=iB;function oB(){return new Date().toISOString()}j.nowIso=oB});var Lt=v(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.describeMalformedValue=La.collectPages=void 0;var gC=ye(),Sm=Q();async function aB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,gC.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Nm(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 Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${Nm(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Sm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,gC.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}La.collectPages=aB;function Nm(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}La.describeMalformedValue=Nm});var _m=v(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.assertWorkflowKind=Lo.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Ro=Yi(),sB=Q(),yC=ye(),lB=se();Lo.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var bC={[Ro.WorkflowCategory.Workflow]:"classic workflow",[Ro.WorkflowCategory.Dialog]:"dialog",[Ro.WorkflowCategory.BusinessRule]:"business rule",[Ro.WorkflowCategory.Action]:"custom action",[Ro.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Ro.WorkflowCategory.Flow]:"cloud flow",[Ro.WorkflowCategory.UIFlow]:"desktop flow"};async function uB(e,t,r){var n,i;let o=`/workflows(${t})${(0,lB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,yC.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=bC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new sB.SdkError(Lo.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${bC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,yC.readEtag)(a)}Lo.assertWorkflowKind=uB});var Dm=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.deleteWorkflowResending=Kr.isWorkflowDeleteUnsettled=Kr.failedAfterResend=Kr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var ml=Q(),mi=ye(),wC=se();Kr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var CC=new WeakSet;function Tm(e){return typeof e=="object"&&e!==null&&CC.add(e),e}function cB(e){return typeof e=="object"&&e!==null&&CC.has(e)}Kr.failedAfterResend=cB;function dB(e){return e instanceof ml.SdkError&&e.code===Kr.WORKFLOW_DELETE_UNSETTLED_CODE}Kr.isWorkflowDeleteUnsettled=dB;function fB(e,t){try{(0,mi.ensureSuccess)(e,t)}catch(r){return r}}function pB(e){return(0,mi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${mi.TRANSACTION_NOT_STARTED_CODE})`}async function vC(e,t){try{return(await e.get(`/workflows(${t})${(0,wC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function mB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,wC.normalizeGuid)(t,"id");if(a&&!r)throw new ml.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,mi.isTransactionNotStarted)(p)||o&&(0,mi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,mi.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?mi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof ml.ConnectionError&&p.statusCode===0&&r&&await vC(e,s))return;throw d>1?Tm(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=pB(f),h=new ml.SdkError(Kr.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 Tm((0,ml.attachCause)(h,fB(f,u)))}if(!(r&&mi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await vC(e,s)))try{(0,mi.ensureSuccess)(m,u)}catch(p){throw d>1?Tm(p):p}}}Kr.deleteWorkflowResending=mB});var Im=v(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.businessRuleApi=Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Un.WFOM_API_UNAVAILABLE_CODE=void 0;var Mn=Yi(),hB=Lt(),gB=_m(),yB=Dm(),Vt=ye(),hi=se(),Ac=Q();Un.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function EC(e,t,r,n){let i=`/workflows(${wB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Vt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Ac.SdkError(Un.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 bB(e,t){let r=`/workflows(${t})${(0,hi.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,Vt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function vB(e,t,r){let n=await bB(e,t);if(n===null||n.etag===null)throw new Ac.SdkError(Vt.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 Ac.SdkError(Vt.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 wB="00000000-0000-0000-0000-000000000000",Ec={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},CB="workflowid,name,description,primaryentity,statecode,category,type",EB="category eq 2 and type eq 1";async function AC(e,t,r){var n;if(r==="Draft")return null;let i=(0,hi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Mn.StateCode.Activated:Mn.StateCode.Draft,statuscode:o?Mn.StatusCode.Activated:Mn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Vt.ensureSuccess)(await e.patch(s,a,{headers:Ec}),e.apiUrl(s));return(n=(0,Vt.readEtag)(l))!==null&&n!==void 0?n:await hl(e,i)}async function hl(e,t){let r=`/workflows(${t})${(0,hi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Vt.readEtag)(n):null}catch{return null}}async function AB(e,t,r){let n=await hl(e,t),i=await r(),o=(0,Vt.readEtag)(i);if(o)return{response:i,etag:o};let a=await hl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Un.businessRuleApi={async get(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await AB(e,r,async()=>(0,Vt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[EB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,hi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,hi.odataQuery)([["$select",CB],["$filter",r.join(" and ")]])}`;return(await(0,hB.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,hi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await EC(e,"CreateProcessWithWfomJson",n,Ec),a=(0,Vt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await AC(e,a,n.status)}catch(l){try{await(0,Vt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Vt.readEtag)(o))!==null&&r!==void 0?r:await hl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,hi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ec,"If-Match":(0,Vt.requireEtag)(n,"business rule",s)},c=await vB(e,s,u["If-Match"]),d=c.statecode===Mn.StateCode.Activated;d&&(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Draft,statuscode:Mn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await EC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Mn.StatusCode.Activated},{headers:Ec}),e.apiUrl(l))}catch(h){throw new Ac.SdkError(Un.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 AC(e,s,a.status);return{id:s,etag:(o=m??(0,Vt.readEtag)(f))!==null&&o!==void 0?o:await hl(e,s)}},async delete(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=await(0,gB.assertWorkflowKind)(e,r,Mn.WorkflowCategory.BusinessRule);return(0,yB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Jr=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.publishBoundEntity=Ct.boundEntityPublishScope=Ct.publishGenPageById=Ct.publishDashboardById=Ct.publishWebResourceById=Ct.publishEntity=Ct.publishAppModule=Ct.publishXml=void 0;var SC=ye(),gl=se(),NC="/PublishXml";async function ka(e,t){(0,SC.ensureSuccess)(await(0,SC.resendDeadlockVictim)(()=>e.post(NC,{ParameterXml:t})),e.apiUrl(NC))}Ct.publishXml=ka;function SB(e,t){return ka(e,`<importexportxml><appmodules><appmodule>${(0,gl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ct.publishAppModule=SB;function _C(e,t){return ka(e,`<importexportxml><entities><entity>${(0,gl.xmlText)(t)}</entity></entities></importexportxml>`)}Ct.publishEntity=_C;function NB(e,t){return ka(e,`<importexportxml><webresources><webresource>${(0,gl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ct.publishWebResourceById=NB;function _B(e,t){return ka(e,`<importexportxml><dashboards><dashboard>${(0,gl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ct.publishDashboardById=_B;function TB(e,t){return ka(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,gl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ct.publishGenPageById=TB;function DB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ct.boundEntityPublishScope=DB;function IB(e,t){let r=t?.entityLogicalName;return r?_C(e,r):Promise.resolve()}Ct.publishBoundEntity=IB});var $a=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.JsonPointer=void 0;var Mr=Q(),Sc=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 Mr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Mr.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 Mr.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 Mr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Mr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Mr.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 Mr.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 Mr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Mr.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 Mr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Mr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Mr.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 Mr.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)}};Nc.JsonPointer=Sc;Sc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var DC=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.findElements=void 0;var TC=$a();function OB(e,t){let r=[];return Om(e,"",t,r),r}_c.findElements=OB;function Om(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)=>{Om(i,TC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Om(e[i],TC.JsonPointer.append(t,i),r,n)}});var Pm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.assertMutationResult=Bn.assertExistsResult=Bn.assertReadResult=Bn.assertStorageContract=void 0;var PB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],RB=["ensureContainer","exists"];function LB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of PB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of RB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Bn.assertStorageContract=LB;function kB(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.`)}Bn.assertReadResult=kB;function $B(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.`)}Bn.assertExistsResult=$B;function xB(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.`)}Bn.assertMutationResult=xB});var Rm=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.retryTransientIoAsync=xa.retryTransientIo=void 0;var FB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),MB=5,IC=10;function UB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!OC(r,t))throw r;qB(IC*t)}}xa.retryTransientIo=UB;async function BB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!OC(r,t))throw r;await new Promise(n=>setTimeout(n,IC*t))}}xa.retryTransientIoAsync=BB;function OC(e,t){let r=e.code;return t<MB&&!!r&&FB.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 $C=v(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.canonicalArtifactId=Ur.WorkspaceManager=Ur.WORKSPACE_SCHEMA_VERSION=Ur.retryTransientIo=void 0;var Gt=Pm(),qn=Q(),VB=Rm();Object.defineProperty(Ur,"retryTransientIo",{enumerable:!0,get:function(){return VB.retryTransientIo}});function PC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Ur.WORKSPACE_SCHEMA_VERSION=1;var Qi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},GB="manifest.json",Fa=".metadata",Lm="entities";function RC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function km(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Ur.WORKSPACE_SCHEMA_VERSION)throw new qn.IncompatibleWorkspaceError(e.schemaVersion,Ur.WORKSPACE_SCHEMA_VERSION)}function LC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var $m=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),[Qi[t],`${yl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Fa,Qi[t],`${yl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Fa,Lm,`${t.toLowerCase()}.json`]}fsStore(){let t=PC(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=PC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Qi[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 qn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[GB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new qn.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,Gt.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=[[Fa,Lm]];for(let i of Object.keys(Qi))r.push([Qi[i]],[Fa,Qi[i]]);let n=await Promise.allSettled(r.map(i=>RC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Gt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Gt.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 qn.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 qn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!LC(t))throw new qn.WorkspaceOrgMismatchError("",this.instanceUrl);km(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Tc(r);if(!n||n!==Tc(this.instanceUrl))throw new qn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!LC(t.value))throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;km(r);let n=Object.keys(Qi).map(o=>[Qi[o]]);n.push([Fa]);let i=await Promise.allSettled(n.map(o=>RC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Gt.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,Gt.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=kC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Gt.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,Gt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=yl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Gt.assertMutationResult)(await this.storage.deleteByPrefix([Fa,Lm]),"deleteByPrefix");return}(0,Gt.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 qn.WorkspaceNotInitializedError(this.workspaceLabel);return km(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Ur.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Tc(String(t.instanceUrl))!==Tc(r.instanceUrl))throw new qn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=yl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Gt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Gt.assertMutationResult)(await this.storage.writeTextAtomic(t,kC(r)),"writeTextAtomic")}};Ur.WorkspaceManager=$m;function kC(e){return`${JSON.stringify(e,null,2)}+`}function yl(e){let r=/^\{?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}Ur.canonicalArtifactId=yl});var xm=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.deepEqual=Ma.deepDiff=void 0;var WB=$a();function zB(e,t){let r=[];return FC(e,t,"",r,0),r}Ma.deepDiff=zB;var Dc=Symbol("missing"),Ic=512;function FC(e,t,r,n,i){if(e===t)return;if(i>Ic)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Ic}`);let o=Oc(e),a=Oc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=jB(e,t);for(let l of s){let u=xC(e,l),c=xC(t,l),d=WB.JsonPointer.append(r,l);u===Dc?n.push({pointer:d,type:"added",newValue:c}):c===Dc?n.push({pointer:d,type:"removed",oldValue:u}):FC(u,c,d,n,i+1)}return}MC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Oc(e){return e!==null&&typeof e=="object"}function jB(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 xC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Dc}return t in e?e[t]:Dc}function MC(e,t){return UC(e,t,0)}Ma.deepEqual=MC;function UC(e,t,r){if(e===t)return!0;if(r>Ic)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Ic}`);if(!Oc(e)||!Oc(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&&UC(e[o],t[o],r+1))}});var qC=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.VersionManager=Ua.PROJECTION_VERSION=void 0;var BC=xm(),HB=ye();Ua.PROJECTION_VERSION=8;var Fm=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,BC.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,BC.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,HB.isVersionToken)(i.etag)?!0:i.etag!==n}};Ua.VersionManager=Fm});var GC=v((Mm,VC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Mm=="object"?VC.exports=t():e.compareVersions=t()})(Mm,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 KC=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.EnvironmentFlowHostingType=Ke.EnvironmentDisableReasonCode=Ke.EnvironmentMigrationConstants=Ke.EnvironmentProvisioningStates=Ke.EnvironmentLocations=Ke.EnvironmentCreationTypeConstants=Ke.EnvironmentType=Ke.EnvironmentSkuConstants=Ke.environmentPermissions=Ke.DatabaseType=void 0;var WC;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(WC||(Ke.DatabaseType=WC={}));Ke.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"};Ke.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var zC;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(zC||(Ke.EnvironmentType=zC={}));Ke.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ke.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"};Ke.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ke.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var jC;(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"})(jC||(Ke.EnvironmentDisableReasonCode=jC={}));var HC;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(HC||(Ke.EnvironmentFlowHostingType=HC={}))});var rE=v(_=>{"use strict";var KB=_&&_.__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 JB=KB(GC()),Oe=KC(),bl=Bm();function YB(e){let t=yi(e);return t&&t.version}_.getCrmVersion=YB;function yi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=yi;function gi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=gi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function ko(e){return!!yi(e)&&JC(e)}_.environmentHasCds2Database=ko;function QB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=QB;function XB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=XB;function ZB(e){if(e&&ko(e)){let t=Xi(e);(0,bl.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=ZB;function eq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=eq;function tq(e){return e&&ko(e)?Xi(e):""}_.getAllThemesUrl=tq;function JC(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=JC;function rq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=rq;function nq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=nq;function Xi(e){let t=yi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Xi;function iq(e){let t=yi(e);return t?t.uniqueName:""}_.getCrmInstanceName=iq;function oq(e){return yi(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=oq;function aq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=aq;function sq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=sq;function lq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=lq;function vl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=vl;function uq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=uq;var cq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=cq;function dq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=dq;function fq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=fq;function pq(e){return e&&e.properties&&gi(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=pq;function mq(e){return!!(e&&e.properties&&e.properties.provisioningState&&tE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=mq;function hq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=hq;function gq(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=gq;function yq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=yq;function bq(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=bq;function vq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=vq;function wq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=wq;function Cq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Cq;function Eq(e){return e&&e.name||""}_.getEnvironmentName=Eq;function Aq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=Aq;var YC="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Sq(e){return ZC(e,YC)}_.doesCds2EnvironmentSupportApiVersion9_1=Sq;function Nq(e){return Um(e,YC)}_.doesCds2VersionSupportApiVersion9_1=Nq;function QC(e){let t=yi(e);if(t)return t.securityGroupId}function XC(e){return e&&e.properties&&e.properties.connectedGroups}function _q(e,t){let r=XC(e);return!!r&&!!r.find(n=>n.id===t)||QC(e)===t}_.hasSecurityGroupId=_q;function Tq(e){let t=XC(e);return t&&t.length>0&&t[0].id?t[0].id:QC(e)}_.getSecurityOrConnectedGroupId=Tq;function ZC(e,t){let r=e.version;return r?Um(r,t):!1}_.isCds2EnvironmentVersionAtLeast=ZC;function Um(e,t){return t?e?(0,JB.default)(e,t)>=0:!1:!0}_.checkVersions=Um;function Dq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Dq;function Iq(e){let t=yi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Iq;function eE(e){let t=yi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=eE;function Oq(e){let t=eE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Oq;function Pq(e){let t=Xi(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=Pq;var Rq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Rq;var Lq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Lq;var kq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=kq;var $q=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=$q;var xq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=xq;var Fq=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return gi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Fq;var Mq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Mq;function tE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=tE;var Uq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Uq;var Bq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Bq;var qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=qq;var Vq=e=>{var t,r;return!gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&gi((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Vq});var Bm=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 nE=rE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Cl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Cl||(Cl={}));function Gq(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=Gq;function Wq(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=Wq;function zq(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=zq;function jq(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=jq;function Hq(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=Hq;function Kq(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=Kq;function qm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function Jq(e){return qm(e,Cl.AllSolutions)}A.getCrmAllSolutionsUrl=Jq;function Yq(e){return qm(e,Cl.AllPublishers)}A.getCrmAllPublishersUrl=Yq;function Qq(e){return qm(e,Cl.DevResources)}A.getCrmDevResourcesUrl=Qq;function Xq(e,t=nE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=Xq;function Zq(e){return`${e}apps`}A.getCrmMyAppsUrl=Zq;function e3(e){return iE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=e3;function t3(e){return`${iE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=t3;function iE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function r3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=r3;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 n3(e,t,r=nE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=n3;function i3(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=i3;function o3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=o3;function a3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=a3;function s3(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=s3;function l3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=l3;function u3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=u3;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.getProcessDesignerUrl=c3;function d3(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=d3;function f3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=f3;function p3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=p3;function m3(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=m3;function h3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=h3;function g3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=g3;function y3(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=y3;function b3(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=b3;function v3(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=v3;function w3(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=w3;function C3(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=C3;function E3(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=E3;function A3(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=A3;function S3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=S3;function N3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=N3;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 _3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=_3;function T3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=T3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function D3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=D3;function I3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=I3;function O3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=O3;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 P3(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=dV;function fV(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=fV;function pV(e){return`/api/data/v9.0/deploymentenvironments+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=P3;function R3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=R3;function L3(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=pV;function mV(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=L3;function k3(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=mV;function hV(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=hV;function gV(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=gV;function yV(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=yV;function bV(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=bV;function vV(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=vV;function wV(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=wV;function CV(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=k3;function $3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=$3;function x3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=x3;function F3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=F3;function M3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=M3;function U3(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=U3;function B3(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=B3;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?$filter=(${t})- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=CV;function EV(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=EV;function AV(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=q3;function V3(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=AV;var SV=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=G3;var W3=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=SV;function NV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=NV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function _V(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=_V;A.OrgSettingOverrideName="organizationsettings";function TV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=TV;A.AppSettingOverrideName="appsettings";function DV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=DV;var ql;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(ql||(A.RetrievePlatform=ql={}));function IV(e,t,r,n=ql.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==ql.All&&o.push(`RetrievePlatformSettings=${n===ql.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=IV;function OV(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=OV;function PV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=PV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function RV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=RV;function XE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=XE;function LV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||XE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=LV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var tA=v(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.DataverseClient=void 0;var kV=Eh(),Jo=Q(),ZE=fe(),$V=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function xV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return $V.has(s)}function FV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function eA(e,t){var r;if(!xV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Sh=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${kV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Jo.SdkError?n:new Jo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=eA(t,r);return(0,ZE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=eA(FV(t),r);return(0,ZE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Jo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Jo.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};rd.DataverseClient=Sh});var iA=v(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.findColumns=cr.findTables=cr.readCheckColumns=cr.readColumnHints=cr.fetchEntityMetadataFromApi=cr.COLUMN_DETAIL_VERSION=void 0;var od=fe(),Ar=oe();function an(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}cr.COLUMN_DETAIL_VERSION=2;function Nh(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Yo(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function nd(e,t){return(await ad(e,t)).rows}async function ad(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Jr(e){return`/EntityDefinitions(LogicalName='${(0,Ar.odataPathLiteral)(e)}')`}async function MV(e,t,r){let n=await nd(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function UV(e){return`${Jr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function BV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:an(a.Label),...Yo(a.Label)?{localizedLabel:Yo(a.Label)}:{}}}))}}function _h(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:an(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function qV(e,t,r){var n;let i=c=>ad(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Nh(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(_h)));let u=await i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Nh(d.TrueOption.Label)&&Nh(d.FalseOption.Label),s.set(c.LogicalName,[_h(d.FalseOption),_h(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function VV(e,t,r){let{rows:n,ok:i}=await ad(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function id(e,t){return e<t?-1:e>t?1:0}var rA={OneToMany:0,ManyToOne:1,ManyToMany:2};function GV(e,t){return rA[e.type]-rA[t.type]||id(e.schemaName,t.schemaName)||id(e.relatedEntity,t.relatedEntity)||id(e.relatedAttribute,t.relatedAttribute)}async function WV(e,t){var r,n,i,o;let a=[],s=await nd(e,`${Jr(t)}/OneToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await nd(e,`${Jr(t)}/ManyToOneRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await nd(e,`${Jr(t)}/ManyToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(GV)}async function zV(e,t){var r,n,i,o,a;let s=`${Jr(t)}`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,od.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,C;return{logicalName:g.LogicalName,displayName:an(g.DisplayName),...Yo(g.DisplayName)?{localizedDisplayName:Yo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(C=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...an(g.Description)?{description:an(g.Description)}:{}}}).sort((g,b)=>id(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=ad(e,UV(t)),[,,m,p,h]=await Promise.all([MV(e,t,d),BV(f,d),qV(e,t,f),VV(e,t,d),WV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:an(u.DisplayName),...Yo(u.DisplayName)?{localizedDisplayName:Yo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...an(u.Description)?{description:an(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:cr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}cr.fetchEntityMetadataFromApi=zV;var nA=40;async function Th(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=nA){let u=a.slice(l,l+nA).map(f=>`LogicalName eq '${(0,Ar.odataLiteral)(f)}'`).join(" or "),c=t+(0,Ar.odataQuery)([["$select",r],["$filter",u]]),d=(0,od.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function jV(e,t,r){return(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Yo(i.DisplayName);return{logicalName:i.LogicalName,displayName:an(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}cr.readColumnHints=jV;async function HV(e,t,r){let i=(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:an(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Th(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}cr.readCheckColumns=HV;async function KV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,od.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:an(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}cr.findTables=KV;async function JV(e,t,r,n){var i,o;let a=`${Jr(t)}/Attributes`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,od.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:an(d.DisplayName),attributeType:(m=d.AttributeType)!==null&&m!==void 0?m:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}cr.findColumns=JV});var Oh=v(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.renderTypeRegistrations=Sr.buildGenPageLegacyEnums=Sr.renderGenPageAuthoringTypes=Sr.buildGenPageRuntimeTypes=Sr.toDesignerEntity=Sr.TABLE_LOGICAL_NAME=void 0;Sr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function Dh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var YV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function sd(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function sA(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=sd(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function oA(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function lA(e){return!YV.has(e.logicalName)&&(!e.attributeOf||sd(e)==="image")&&e.isValidForRead!==!1}var aA=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function uA(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(oA),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(oA);return[...n,...i]}function Ih(e){var t;let r=[],n=new Set,i=uA(e);for(let o of i){let a=sd(o),s=a==="image";lA(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:sA(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}Sr.toDesignerEntity=Ih;function cA(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Ih(n);return pA(r,t)}Sr.buildGenPageRuntimeTypes=cA;var dA=`export interface TableRegistrations extends BaseTableRegistrations {-`,fA=`export interface EnumRegistrations extends BaseEnumRegistrations {-`;function QV(e,t){return e.length>0?cA(e,t).text:hA(`${dA}}-`,`${fA}}-`,"","")}Sr.renderGenPageAuthoringTypes=QV;function XV(e){let t=new Set;for(let n of e)for(let i of Ih(n).Attributes)aA.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of uA(n)){let o=`${n.logicalName}_${i.logicalName}`,a=sA(i);if(lA(i)||!aA.has(sd(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:mA(o,a,!1,s),model:s})}return r}Sr.buildGenPageLegacyEnums=XV;function pA(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=dA,u=fA,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${Dh(f.Description)}+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=W3;function z3(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=z3;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function j3(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=j3;A.OrgSettingOverrideName="organizationsettings";function H3(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=H3;A.AppSettingOverrideName="appsettings";function K3(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=K3;var wl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(wl||(A.RetrievePlatform=wl={}));function J3(e,t,r,n=wl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==wl.All&&o.push(`RetrievePlatformSettings=${n===wl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=J3;function Y3(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=Y3;function Q3(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=Q3;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function X3(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=X3;function oE({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=oE;function Z3({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||oE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=Z3;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var lE=v(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.DataverseClient=void 0;var eV=Bm(),$o=Q(),aE=ye(),tV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function rV(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 tV.has(s)}function nV(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 sE(e,t){var r;if(!rV(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 Vm=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${eV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof $o.SdkError?n:new $o.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=sE(t,r);return(0,aE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=sE(nV(t),r);return(0,aE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new $o.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new $o.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new $o.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new $o.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new $o.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};Pc.DataverseClient=Vm});var dE=v(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.findColumns=rr.findTables=rr.readCheckColumns=rr.readColumnHints=rr.fetchEntityMetadataFromApi=rr.COLUMN_DETAIL_VERSION=void 0;var kc=ye(),hr=se();function Yr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}rr.COLUMN_DETAIL_VERSION=2;function Gm(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 xo(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 Rc(e,t){return(await $c(e,t)).rows}async function $c(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 Br(e){return`/EntityDefinitions(LogicalName='${(0,hr.odataPathLiteral)(e)}')`}async function iV(e,t,r){let n=await Rc(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,hr.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 oV(e){return`${Br(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function aV(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:Yr(a.Label),...xo(a.Label)?{localizedLabel:xo(a.Label)}:{}}}))}}function Wm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Yr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function sV(e,t,r){var n;let i=c=>$c(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,hr.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=>Gm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Wm)));let u=await i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Gm(d.TrueOption.Label)&&Gm(d.FalseOption.Label),s.set(c.LogicalName,[Wm(d.FalseOption),Wm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function lV(e,t,r){let{rows:n,ok:i}=await $c(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,hr.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 Lc(e,t){return e<t?-1:e>t?1:0}var uE={OneToMany:0,ManyToOne:1,ManyToMany:2};function uV(e,t){return uE[e.type]-uE[t.type]||Lc(e.schemaName,t.schemaName)||Lc(e.relatedEntity,t.relatedEntity)||Lc(e.relatedAttribute,t.relatedAttribute)}async function cV(e,t){var r,n,i,o;let a=[],s=await Rc(e,`${Br(t)}/OneToManyRelationships${(0,hr.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 Rc(e,`${Br(t)}/ManyToOneRelationships${(0,hr.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 Rc(e,`${Br(t)}/ManyToManyRelationships${(0,hr.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(uV)}async function dV(e,t){var r,n,i,o,a;let s=`${Br(t)}`+(0,hr.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,kc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,E;return{logicalName:g.LogicalName,displayName:Yr(g.DisplayName),...xo(g.DisplayName)?{localizedDisplayName:xo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&E!==void 0?E:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Yr(g.Description)?{description:Yr(g.Description)}:{}}}).sort((g,b)=>Lc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=$c(e,oV(t)),[,,m,p,h]=await Promise.all([iV(e,t,d),aV(f,d),sV(e,t,f),lV(e,t,d),cV(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:Yr(u.DisplayName),...xo(u.DisplayName)?{localizedDisplayName:xo(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,...Yr(u.Description)?{description:Yr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:rr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}rr.fetchEntityMetadataFromApi=dV;var cE=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+=cE){let u=a.slice(l,l+cE).map(f=>`LogicalName eq '${(0,hr.odataLiteral)(f)}'`).join(" or "),c=t+(0,hr.odataQuery)([["$select",r],["$filter",u]]),d=(0,kc.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 fV(e,t,r){return(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=xo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Yr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}rr.readColumnHints=fV;async function pV(e,t,r){let i=(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Yr(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,`${Br(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}rr.readCheckColumns=pV;async function mV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,hr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,kc.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:Yr(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}rr.findTables=mV;async function hV(e,t,r,n){var i,o;let a=`${Br(t)}/Attributes`+(0,hr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,kc.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:Yr(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}rr.findColumns=hV});var Km=v(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.renderTypeRegistrations=gr.buildGenPageLegacyEnums=gr.renderGenPageAuthoringTypes=gr.buildGenPageRuntimeTypes=gr.toDesignerEntity=gr.TABLE_LOGICAL_NAME=void 0;gr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function jm(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var gV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function xc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function mE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=xc(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 fE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function hE(e){return!gV.has(e.logicalName)&&(!e.attributeOf||xc(e)==="image")&&e.isValidForRead!==!1}var pE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function gE(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(fE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(fE);return[...n,...i]}function Hm(e){var t;let r=[],n=new Set,i=gE(e);for(let o of i){let a=xc(o),s=a==="image";hE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:mE(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))}}gr.toDesignerEntity=Hm;function yE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Hm(n);return wE(r,t)}gr.buildGenPageRuntimeTypes=yE;var bE=`export interface TableRegistrations extends BaseTableRegistrations {+`,vE=`export interface EnumRegistrations extends BaseEnumRegistrations {+`;function yV(e,t){return e.length>0?yE(e,t).text:EE(`${bE}}+`,`${vE}}+`,"","")}gr.renderGenPageAuthoringTypes=yV;function bV(e){let t=new Set;for(let n of e)for(let i of Hm(n).Attributes)pE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of gE(n)){let o=`${n.logicalName}_${i.logicalName}`,a=mE(i);if(hE(i)||!pE.has(xc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:CE(o,a,!1,s),model:s})}return r}gr.buildGenPageLegacyEnums=bV;function wE(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=bE,u=vE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${jm(f.Description)}`),c+=`export type ${f.LogicalName} = TableRow<{// Primary Key Columnreadonly ${f.PrimaryIdAttribute}: string,@@ -62,19 +62,19 @@ var eq=Object.create;var qc=Object.defineProperty;var tq=Object.getOwnPropertyDe`;break;case"customer":case"lookup":{let g=(r=m.Targets)!==null&&r!==void 0?r:m.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}p=` // Foreign Key Column${m.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${m.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;p+=`${b},`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${m.LogicalName}`;p+=`: ${g},-`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=mA(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},+`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=CE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.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+=` // ${Dh(m.Description)}+`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${jm(m.Description)}`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+``),c+=` ${p}`)}c+=`}>`}return l+=`}`,u+=`}-`,{text:hA(l,u,c,d),enums:i}}Sr.renderTypeRegistrations=pA;function mA(e,t,r,n){var i;let o=`const enum ${e} {-`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${Dh(a.color)}+`,{text:EE(l,u,c,d),enums:i}}gr.renderTypeRegistrations=wE;function CE(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: ${jm(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 hA(e,t,r,n){return`+`}function EE(e,t,r,n){return`// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------${e}${t}@@ -345,23 +345,23 @@ export interface GeneratedComponentProps {dataApi: UxAgentDataApi;pageInput?: PageInput;}-`}});var bA=v(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});ld.generateGenPageRuntimeTypes=void 0;var yA=Oh(),Qo=Q(),gA=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Xo="generateGenPageRuntimeTypes";async function ZV(e,t,r){let n=eG(t),i=tG(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Qo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Xo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,yA.renderGenPageAuthoringTypes)(o,i)}ld.generateGenPageRuntimeTypes=ZV;function eG(e){if(!Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!yA.TABLE_LOGICAL_NAME.test(r))throw new Qo.InvalidArgumentError(`${Xo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Qo.InvalidArgumentError(`${Xo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function tG(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Qo.InvalidArgumentError(`${Xo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!gA.has(r))throw new Qo.InvalidArgumentError(`${Xo}: detail must be one of ${[...gA].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var SA=v(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.getEnvironmentLanguages=Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var rG=Q(),CA=fe();Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var vA="/organizations?$select=languagecode",nG="/RetrieveProvisionedLanguages()",iG="/RetrieveAvailableLanguages()";function EA(e,t){return new rG.SdkError(Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function AA(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function wA(e,t,r,n){let i=(0,CA.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(AA))throw EA(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function oG(e){var t;let r=(0,CA.ensureSuccess)(await e.get(vA),e.apiUrl(vA)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!AA(i))throw EA("the organization read","did not answer one row with a language code");let o=await wA(e,nG,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await wA(e,iG,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Zo.getEnvironmentLanguages=oG});var Wl=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.projectConnectorOperationSchema=lt.projectConnectorOperations=lt.validateConnectorSwagger=lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=lt.CONNECTOR_OPERATION_NOT_FOUND_CODE=lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var Gl=Q();lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";lt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var NA=64,_A=128,TA=2e5,DA=4e6,aG=new Set(["get","put","post","delete","patch","head","options"]),sG=new Set(["query","header","path","formData","body"]);function sn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dt(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function et(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new Gl.SdkError(lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function fo(e,t){return new Gl.SdkError(lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function lG(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!Tn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Lh(e,t,r){if(!t.startsWith("#/"))throw fo(r,`has a $ref that is not a local '#/\u2026' pointer (${et(t)})`);if(t.includes("%"))throw fo(r,`has a $ref with a percent-encoded character (${et(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${et(t)}): a '~' not followed by 0 or 1`);let n=lG(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${et(t)})`);return n.value}function ud(e,t){if(Tn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Dt(e.$ref)}, not a string`);return e.$ref}}function uG(e,t,r){if(!sn(t))throw ke(r,`is ${Dt(t)}, not a parameter object`);let n=t,i=ud(t,r);if(i!==void 0){let s=Lh(e,i,r);if(!sn(s))throw ke(r,`has a $ref (${et(i)}) that resolves to ${Dt(s)}, not a parameter object`);if(ud(s,`${r} \u2192 ${et(i)}`)!==void 0)throw fo(r,`has a $ref (${et(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!sG.has(o))throw ke(r,`has an in that is ${typeof o=="string"?et(o):Dt(o)}, not one of query, header, path, formData or body`);if(Tn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Dt(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(Tn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Dt(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Ph(e){return`${e.in}:${e.name}`}function OA(e,t,r){if(!Tn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Dt(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=uG(e,o,s),u=Ph(l);if(i.has(u))throw ke(s,`repeats the parameter ${et(l.name)} in ${et(l.in)}, which must be unique in its list`);return i.add(u),l})}function PA(e,t,r){let n=t.responses;if(!Tn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!sn(o))throw ke(i,`is ${Dt(o)}, not a response object`);let a=o,s=ud(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${et(s)}) that does not name a response ('#/responses/<name>')`);let l=Lh(e,s,i);if(!sn(l))throw ke(i,`has a $ref (${et(s)}) that resolves to ${Dt(l)}, not a response object`);if(ud(l,`${i} \u2192 ${et(s)}`)!==void 0)throw fo(i,`has a $ref (${et(s)}) to a response that is itself a $ref`);a=l}if(Tn(a,"content"))throw fo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(Tn(a,"schema")){if(!sn(a.schema))throw ke(i,`has a schema that is ${Dt(a.schema)}, not an object`);return a.schema}}function IA(e,t,r){if(!Tn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Dt(n)}, not a string`);return n}function cG(e,t,r,n,i){if(!sn(t))throw ke(r,`is ${Dt(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Dt(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${et(o)}, which must be unique in the document`);n.add(o);let a=IA(t,"summary",r),s=IA(t,"description",r),l=OA(e,t,r);if(!sn(t.responses))throw ke(r,`has no responses object (${Dt(t.responses)})`);return PA(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function kh(e){if(!sn(e))throw ke("the document",`is ${Dt(e)}, not an object`);if(Tn(e,"openapi"))throw fo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!Tn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw fo("the document",`declares swagger ${et(String(e.swagger))}, not 2.0`);let t=e.paths;if(!sn(t))throw ke("the document",`has paths that are ${Dt(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${et(i)}]`;if(!sn(o))throw ke(a,`is ${Dt(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(aG.has(l.toLowerCase()))r.push(cG(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of OA(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw fo(a,`has a ${et(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function dG(e){kh(e)}lt.validateConnectorSwagger=dG;var Rh=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new Gl.SdkError(lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>TA)throw this.tooLarge(`more than ${TA} nodes`)}text(t){if(this.characters+=t,this.characters>DA)throw this.tooLarge(`more than ${DA} characters of strings and keys`)}checkDepth(t){if(t>_A)throw this.tooLarge(`nesting deeper than ${_A} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(sn(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=NA)throw this.tooLarge(`a $ref chain of more than ${NA} references`);let n=Lh(this.root,t,this.where);if(!sn(n))throw ke(this.where,`has a schema $ref (${et(t)}) that resolves to ${Dt(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function fG(e){let{operations:t}=kh(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}lt.projectConnectorOperations=fG;function pG(e,t){if(typeof t!="string"||t==="")throw new Gl.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=kh(e),i=n.find(u=>u.id===t);if(!i)throw new Gl.SdkError(lt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${et(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Ph)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Ph(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=PA(r,i.node,i.where),l=s===void 0?{}:new Rh(r,`${i.where} (${et(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}lt.projectConnectorOperationSchema=pG});var ea=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zl=Q(),mG=fe(),hG=Wl();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=Nr;function ns(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=ns;function is(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=is;function LA(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=LA;function gG(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=gG;var yG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,bG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function vG(e){let t=LA(e),r=t?t.host.toLowerCase():"";if(bG.test(r))return"Test";let n=yG.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=vG;function Yn(e,t){return new zl.SdkError(hG.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Yn;function wG(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=wG;function CG(e){if(typeof e=="string"&&e.length>0)return is(e,500);if(Nr(e)){let t=Nr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return is(r,500)}return"request failed"}J.messageOf=CG;function kA(e){return Nr(e)&&Nr(e.error)?e.error.code:void 0}J.errorCodeOf=kA;function EG(e){if(Nr(e)&&Nr(e.error)&&Nr(e.error.innererror))return e.error.innererror.code}function AG(e,t,r){let n=[],i=kA(t);typeof i=="string"&&i.length>0&&n.push(is(i,80));let o=EG(t);typeof o=="string"&&o.length>0&&n.push(is(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,zl.attachCause)(new zl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=AG;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var SG=/^[A-Za-z0-9_.-]{1,128}$/,NG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function _G(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(SG.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${is(e,80)}'`:ns(e)}.`)}J.connectorShortName=_G;function TG(e,t,r){let n=`Connection row ${t}`;if(!Nr(e))throw Yn(n,`it is ${ns(e)}, not an object`);let i=e.properties;if(!Nr(i))throw Yn(n,`its properties are ${ns(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Yn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Yn(n,"its apiId names no single connector");if(NG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Yn(n,"it has no name");let l=i.environment,u=Nr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Yn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Yn(n,`its displayName is ${ns(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Yn(n,`its statuses are ${ns(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=Nr(f)?f.status:void 0;if(typeof m!="string")throw Yn(n,"one of its statuses has no string status");return m})}}J.readConnection=TG;var RA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function DG(e){let t=(0,mG.ensureSuccess)(await e.get(RA),e.apiUrl(RA)).body,r=Nr(t)?t.Detail:void 0,n=Nr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new zl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=DG});var qA=v(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.ConnectivityApi=_r.CONNECTIVITY_UNAUTHORIZED_CODE=_r.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=_r.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=_r.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=_r.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Yt=Q(),IG=fe(),dd=Wl(),Hl=ea(),Kl=ea();Object.defineProperty(_r,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_UNAUTHORIZED_CODE}});var $A="2016-11-01",OG="2021-04-01",PG="https://api.bap.microsoft.com",RG="https://test.api.bap.microsoft.com",LG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,kG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,xA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",Oi="/providers/Microsoft.PowerApps/apis/",$G=/^[A-Za-z0-9_.-]{1,128}$/,xG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),FG="ServiceDecommissioned";function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function po(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Qn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function jl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function FA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function MG(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function ln(e,t){return new Yt.SdkError(dd.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function cd(e){return new Yt.SdkError(Hl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function MA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function UA(e){if(typeof e=="string"&&e.length>0)return Qn(e,500);if(gt(e)){let t=gt(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Qn(r,500)}return"request failed"}function UG(e){return gt(e)&>(e.error)?e.error.code:void 0}function BA(e){if(typeof e=="string"){let r=e.slice(0,Oi.length).toLowerCase()===Oi.toLowerCase()?e.slice(Oi.length):e;if($G.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Yt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${Oi}shared_office365users'); got ${typeof e=="string"?`'${Qn(e,80)}'`:po(e)}.`)}function BG(e,t,r){let n=`Connection row ${t}`;if(!gt(e))throw ln(n,`it is ${po(e)}, not an object`);let i=e.properties;if(!gt(i))throw ln(n,`its properties are ${po(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,Oi.length).toLowerCase()!==Oi.toLowerCase())throw ln(n,`its apiId is not '${Oi}<connector>'`);let a=o.slice(Oi.length);if(a===""||a.includes("/"))throw ln(n,"its apiId names no single connector");if(xG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw ln(n,"it has no name");let l=i.environment,u=gt(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw ln(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw ln(n,`its displayName is ${po(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw ln(n,`its statuses are ${po(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=gt(f)?f.status:void 0;if(typeof m!="string")throw ln(n,"one of its statuses has no string status");return m})}}var $h=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${$A}&$filter=${MA(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw ln(u,`its value is ${po(d)}, not an array`);for(let m of d){let p=BG(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw ln(u,`its nextLink is ${f===""?"an empty string":po(f)}, not a non-empty string`);if(i.has(f))throw new Yt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Qn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=BA(t);return(0,dd.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=BA(t);if(typeof r!="string"||r==="")throw new Yt.InvalidArgumentError("operationId must be a non-empty string.");return(0,dd.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Yt.SdkError(Hl.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${OG}`,o=(await this.send(t,i,!1)).body,a=gt(o)?o.properties:void 0,s=gt(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw cd(`BAP's environment row is not the one named '${Qn(n,80)}' (its name)`);let l=gt(a)&>(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?jl(l):void 0,c=jl(this.instanceUrl);if(!u||!c||!FA(u,c))throw cd("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=gt(a)?a.runtimeEndpoints:void 0,f=gt(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?jl(f):void 0;if(!m||m.protocol!=="https:"||!MG(m.host.toLowerCase()))throw cd("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=jl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=LG.exec(r);if(n&&n[1]!=="9")return PG;if(kG.test(r))return RG;throw new Yt.SdkError(Hl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Qn(t.host,80)}'`:`'${Qn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,IG.ensureSuccess)(await this.org.get(xA),this.org.apiUrl(xA)).body,r=gt(t)?t.Detail:void 0,n=gt(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw cd("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${Oi}${i}?api-version=${$A}&$filter=${MA(n.id)}`,a=(await this.send(t,o,!0)).body,s=gt(a)?a.properties:void 0,l=gt(s)?s.swagger:void 0;if(!gt(l))throw ln(`The connector '${Qn(r,80)}'`,`its properties.swagger is ${po(l)}, not an object`);return(0,dd.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=jl(t);if(!n)throw new Yt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Qn(t)}'`);if(!FA(n,r))throw new Yt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Qn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Yt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Yt.SdkError?o:new Yt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Yt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Yt.ConnectionError(t,r,UA(n),n);return i&&r===410&&UG(n)===FG?(0,Yt.attachCause)(new Yt.SdkError(Hl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${UA(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,Hl.connectivityUnauthorized)(r,n,a):a}};_r.ConnectivityApi=$h});var Bh=v(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.projectConnectorTableSchema=Be.projectConnectorTables=Be.tableSchemaSuffix=Be.tablesSuffix=Be.encodeTable=Be.encodeDataset=Be.checkTabularConnection=Be.runtimeAuthority=Be.tabularRevision=Be.checkTableSchemaArguments=Be.checkListTablesArguments=void 0;var ta=Q(),M=ea(),qG=/^[A-Za-z0-9_.-]{1,128}$/,ra=/^\.{1,2}$/,VG="shared_sharepointonline",GG=/^[0-9]{1,9}$/,WG=/^[A-Za-z0-9._~-]+$/,zG=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,jG=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,HG=/^[A-Za-z0-9._~!'()*-]$/,KG=/^[0-9A-Fa-f]{2}$/;function Pi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Jl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function xh(e,t){return new ta.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function fd(e,t){return new ta.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function JG(e){if(typeof e=="string"&&qG.test(e)&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Jl(e)}.`)}function YG(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||ra.test(r))===void 0)return e;throw new ta.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Jl(e)}.`)}}function QG(e){if(typeof e=="string"&&e!==""&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Jl(e)}.`)}function GA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:JG(t),dataset:YG(r)}}Be.checkListTablesArguments=GA;function XG(e,t,r,n){return{...GA(e,t,r),table:QG(n)}}Be.checkTableSchemaArguments=XG;function ZG(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!Pi(n,"interfaces"))throw xh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!Pi(i,"CDPTabular1"))throw xh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!GG.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=e8(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw xh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Be.tabularRevision=ZG;function e8(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>WG.test(i)&&!ra.test(i))?t:void 0}function t8(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw fd(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:zG.exec(l);if(!c||ra.test(c[1]))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:jG.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>ra.test(c)))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Be.runtimeAuthority=t8;function r8(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Jl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Jl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Be.checkTabularConnection=r8;function VA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function n8(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!KG.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!HG.test(e[t]))return!1;return!0}function WA(e,t){let r,n,i;try{r=VA(e),n=VA(r),i=decodeURIComponent(n)}catch{throw new ta.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!n8(n)||ra.test(n)||i!==r)throw new ta.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function Uh(e){return e.split(",").map((t,r)=>WA(t,`dataset part ${r}`)).join(",")}Be.encodeDataset=Uh;function zA(e){return WA(e,"table")}Be.encodeTable=zA;function i8(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===VG?"allTables":"tables";return`/datasets/${Uh(t)}/${r}`}Be.tablesSuffix=i8;function o8(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${Uh(e)}`}/tables/${zA(t)}`}Be.tableSchemaSuffix=o8;function os(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function a8(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(os(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=os(e,"value"),i=n.found?n:os(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>s8(n,i))}}Be.projectConnectorTables=a8;function s8(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=os(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=os(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=os(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function Fh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function Mh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function l8(e,t){var r,n;if(Pi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=Mh(e,"type",t),o=Mh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!Pi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(Pi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=Mh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function u8(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Fh(e,"items","items"),i=Fh(e,"schema","schema"),o=i?Fh(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&Pi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&Pi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:l8(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Be.projectConnectorTableSchema=u8});var jA=v(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.PowerPlatformApiDiscovery=void 0;var qh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};pd.PowerPlatformApiDiscovery=qh});var HA=v(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});md.PowerPlatformApiDiscovery=void 0;var c8=jA();Object.defineProperty(md,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return c8.PowerPlatformApiDiscovery}})});var QA=v(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.platformTokenAudience=mo.platformEnvironment=mo.platformClusterOf=void 0;var KA=HA(),JA=Q(),YA=ea(),d8=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,f8=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,p8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,m8=/^default-/i;function Vh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function h8(e){try{return new URL(e).host.toLowerCase()}catch{return}}function g8(e){let t=h8(e);if(t){if(f8.test(t))return{cloud:"Test",category:"test"};let r=d8.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new JA.SdkError(YA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${Vh(t)}'`:`'${Vh(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}mo.platformClusterOf=g8;function y8(e,t){let r=m8.test(e)?e.slice(8):e;if(!p8.test(r))throw new JA.SdkError(YA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${Vh(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new KA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}mo.platformEnvironment=y8;function b8(e){return new KA.PowerPlatformApiDiscovery(e).getTokenAudience()}mo.platformTokenAudience=b8});var ZA=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.PlatformConnectivityApi=as.assertTabularCloud=void 0;var Dn=Q(),Gh=Wl(),pe=ea(),XA=QA(),Ri=Bh(),Wh="1";function zh(e){let t=(0,pe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Dn.SdkError(pe.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}as.assertTabularCloud=zh;var jh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${Wh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,pe.unreadable)(s,`its value is ${(0,pe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,pe.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,pe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,pe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Dn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,pe.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,pe.connectorShortName)(t);return(0,Gh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,pe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Dn.InvalidArgumentError("operationId must be a non-empty string.");return(0,Gh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){zh(this.instanceUrl);let i=(0,Ri.checkListTablesArguments)(t,r,n),o=(0,Ri.tablesSuffix)(i.short,i.dataset);return(0,Ri.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){zh(this.instanceUrl);let o=(0,Ri.checkTableSchemaArguments)(t,r,n,i),a=(0,Ri.tableSchemaSuffix)(o.dataset,o.table);return(0,Ri.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ri.tabularRevision)(o,t.short),s=(0,Ri.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,pe.environmentFilter)(i.name)}&api-version=${Wh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ri.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new Dn.SdkError(pe.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,XA.platformClusterOf)(this.instanceUrl),n=await(0,pe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,XA.platformEnvironment)(n,r),a=(0,pe.parseUrl)(i);if(!a)throw(0,pe.unreadable)("The Power Platform API origin",`'${(0,pe.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,pe.environmentFilter)(r.name)}&api-version=${Wh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,pe.isObject)(i)?i.name:void 0;if(!(0,pe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,pe.bounded)(o,80)}'`:(0,pe.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,pe.isObject)(n)?n.swagger:void 0;if(!(0,pe.isObject)(i))throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`its properties.swagger is ${(0,pe.kindOf)(i)}, not an object`);return(0,Gh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,pe.parseUrl)(t);if(!n)throw new Dn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,pe.bounded)(t)}'`);if(!(0,pe.sameOrigin)(n,r))throw new Dn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,pe.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof Dn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Dn.SdkError?s:new Dn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Dn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new Dn.ConnectionError(t,r,(0,pe.messageOf)(n),n);return i.includes(r)?(0,pe.connectivityUnauthorized)(r,n,a):a}};as.PlatformConnectivityApi=jh});var tS=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.ConnectivityRouter=void 0;var Hh=Q(),v8=qA(),hd=ea(),eS=Bh(),Kh=ZA(),Jh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new Kh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,hd.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new Hh.SdkError(hd.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new v8.ConnectivityApi(this.org,this.instanceUrl,r);throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};gd.ConnectivityRouter=Jh});var ss=v(Li=>{"use strict";function w8(e,t,r){if(r===void 0&&(r=Array.prototype),e&&typeof r.find=="function")return r.find.call(e,t);for(var n=0;n<e.length;n++)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];if(t.call(void 0,i,n,e))return i}}function Qh(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function C8(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}var rS=Qh({HTML:"text/html",isHTML:function(e){return e===rS.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nS=Qh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nS.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),yd=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,Yh=new RegExp("[\\-\\.0-9"+yd.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),E8=new RegExp("^"+yd.source+Yh.source+"*(?::"+yd.source+Yh.source+"*)?$");Li.assign=C8;Li.find=w8;Li.freeze=Qh;Li.MIME_TYPE=rS;Li.NAMESPACE=nS;Li.nameStartChar=yd;Li.nameChar=Yh;Li.tagNamePattern=E8});var ug=v(Fi=>{var Xh=ss(),Xn=Xh.find,Ql=Xh.NAMESPACE,ls=Xh.tagNamePattern;function A8(e){return e!==""}function S8(e){return e?e.split(/[\t\n\f\r ]+/).filter(A8):[]}function N8(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function iS(e){if(!e)return[];var t=S8(e);return Object.keys(t.reduce(N8,{}))}function _8(e){return function(t){return e&&e.indexOf(t)!==-1}}function Zl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Dr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Zl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Ir={},un=Ir.ELEMENT_NODE=1,us=Ir.ATTRIBUTE_NODE=2,Yl=Ir.TEXT_NODE=3,fS=Ir.CDATA_SECTION_NODE=4,pS=Ir.ENTITY_REFERENCE_NODE=5,T8=Ir.ENTITY_NODE=6,Zh=Ir.PROCESSING_INSTRUCTION_NODE=7,eg=Ir.COMMENT_NODE=8,mS=Ir.DOCUMENT_NODE=9,hS=Ir.DOCUMENT_TYPE_NODE=10,ki=Ir.DOCUMENT_FRAGMENT_NODE=11,D8=Ir.NOTATION_NODE=12,Qt={},Ot={},vce=Qt.INDEX_SIZE_ERR=(Ot[1]="Index size error",1),wce=Qt.DOMSTRING_SIZE_ERR=(Ot[2]="DOMString size error",2),Tr=Qt.HIERARCHY_REQUEST_ERR=(Ot[3]="Hierarchy request error",3),Cce=Qt.WRONG_DOCUMENT_ERR=(Ot[4]="Wrong document",4),oS=Qt.INVALID_CHARACTER_ERR=(Ot[5]="Invalid character",5),Ece=Qt.NO_DATA_ALLOWED_ERR=(Ot[6]="No data allowed",6),Ace=Qt.NO_MODIFICATION_ALLOWED_ERR=(Ot[7]="No modification allowed",7),gS=Qt.NOT_FOUND_ERR=(Ot[8]="Not found",8),Sce=Qt.NOT_SUPPORTED_ERR=(Ot[9]="Not supported",9),aS=Qt.INUSE_ATTRIBUTE_ERR=(Ot[10]="Attribute in use",10),In=Qt.INVALID_STATE_ERR=(Ot[11]="Invalid state",11),Nce=Qt.SYNTAX_ERR=(Ot[12]="Syntax error",12),_ce=Qt.INVALID_MODIFICATION_ERR=(Ot[13]="Invalid modification",13),Tce=Qt.NAMESPACE_ERR=(Ot[14]="Invalid namespace",14),Dce=Qt.INVALID_ACCESS_ERR=(Ot[15]="Invalid access",15);function me(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ot[e]),this.message=Ot[e],Error.captureStackTrace&&Error.captureStackTrace(this,me);return r.code=e,t&&(this.message=this.message+": "+t),r}me.prototype=Error.prototype;Zl(Qt,me);function $i(){}$i.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],o=0;o<this.length;o++)lg(this[o],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function cs(e,t){this._node=e,this._refresh=t,tg(this)}function tg(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(IS(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];Zl(r,e),e._inc=t}}cs.prototype.item=function(e){return tg(this),this[e]||null};Dr(cs,$i);function vd(){this._nameIndex=Object.create(null)}function yS(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function I8(e,t){e._nameIndex[t.nodeName]=t}function bS(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function sS(e,t,r,n){if(n?(t[yS(t,n)]=r,bS(t,n)):t[t.length++]=r,I8(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&CS(i,e,n),O8(i,e,r))}}function lS(e,t,r){var n=yS(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,bS(t,r),e){var o=e.ownerDocument;o&&(CS(o,e,r),r.ownerElement=null)}}else throw new me(gS,new Error(e.tagName+"@"+r))}vd.prototype={length:0,item:$i.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var r=this[t];if(r.nodeName==e)return r}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new me(aS);var r=this._nameIndex[e.nodeName];return sS(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new me(aS);return r=this.getNamedItemNS(e.namespaceURI,e.localName),sS(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return lS(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return lS(this._ownerElement,this,r),r},getNamedItemNS:function(e,t){for(var r=this.length;r--;){var n=this[r];if(n.localName==t&&n.namespaceURI==e)return n}return null}};function vS(){}vS.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new eu;if(n.implementation=this,n.childNodes=new $i,n.doctype=r||null,r&&n.appendChild(r),t){var i=n.createElementNS(e,t);n.appendChild(i)}return n},createDocumentType:function(e,t,r){var n=new Sd;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Cd(this,e,t)},replaceChild:function(e,t){Cd(this,e,t,AS),t&&this.removeChild(t)},removeChild:function(e){return ES(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return DS(this.ownerDocument||this,this,e)},normalize:function(){It(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Yl&&t.nodeType===Yl){for(var n=[],i=r;i!==null&&i.nodeType===Yl;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Ad(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==us?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var r=t._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];t=t.nodeType==us?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function wS(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Zl(Ir,De);Zl(Ir,De.prototype);function wd(e,t){return It(e,null,{enter:function(r){return t(r)?It.STOP:!0}})===It.STOP}function It(e,t,r){for(var n=[{node:e,context:t,phase:It.ENTER}];n.length>0;){var i=n.pop();if(i.phase===It.ENTER){var o=r.enter(i.node,i.context);if(o===It.STOP)return It.STOP;if(n.push({node:i.node,context:o,phase:It.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:It.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}It.STOP=Symbol("walkDOM.STOP");It.ENTER=0;It.EXIT=1;function eu(){this.ownerDocument=this}function O8(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ql.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function CS(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ql.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Ad(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function ES(e,t){var r=t.previousSibling,n=t.nextSibling;return r?r.nextSibling=n:e.firstChild=n,n?n.previousSibling=r:e.lastChild=r,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,Ad(e.ownerDocument,e),t}function P8(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function R8(e){return e&&(Zn(e)||rg(e)||xi(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function xi(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function Zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function rg(e){return e&&e.nodeType===De.TEXT_NODE}function uS(e,t){var r=e.childNodes||[];if(Xn(r,Zn)||xi(t))return!1;var n=Xn(r,xi);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function cS(e,t){var r=e.childNodes||[];function n(o){return Zn(o)&&o!==t}if(Xn(r,n))return!1;var i=Xn(r,xi);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function L8(e,t,r){if(!P8(e))throw new me(Tr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new me(gS,"child not in parent");if(!R8(t)||xi(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new me(Tr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function k8(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!uS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!uS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){if(Xn(n,xi))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element");if(!r&&a)throw new me(Tr,"Doctype can not be appended since element is present")}}function AS(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!cS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!cS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){let l=function(u){return xi(u)&&u!==r};var s=l;if(Xn(n,l))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element")}}function Cd(e,t,r,n){L8(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||k8)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===ki){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Xl(o,l)}while(o!==a&&(o=o.nextSibling));return Ad(e.ownerDocument||e,e),t.nodeType==ki&&(t.firstChild=t.lastChild=null),t}function Xl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===un&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)Xl(i,t),i=i.nextSibling}}function $8(e,t){t.parentNode&&t.parentNode.removeChild(t),t.parentNode=e,t.previousSibling=e.lastChild,t.nextSibling=null,t.previousSibling?t.previousSibling.nextSibling=t:e.firstChild=t,e.lastChild=t,Ad(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Xl(t,r),t}eu.prototype={nodeName:"#document",nodeType:mS,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==ki){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Cd(this,e,t),Xl(e,this),this.documentElement===null&&e.nodeType===un&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ES(this,e)},replaceChild:function(e,t){Cd(this,e,t,AS),Xl(e,this),t&&this.removeChild(t),Zn(e)&&(this.documentElement=e)},importNode:function(e,t){return x8(this,e,t)},getElementById:function(e){var t=null;return wd(this.documentElement,function(r){if(r.nodeType==un&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=iS(e);return new cs(this,function(r){var n=[];return t.length>0&&wd(r.documentElement,function(i){if(i!==r&&i.nodeType===un){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=iS(o);a=t.every(_8(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new na;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new $i;var r=t.attributes=new vd;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Nd;return e.ownerDocument=this,e.childNodes=new $i,e},createTextNode:function(e){var t=new ng;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new ig;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new me(oS,'data contains "]]>"');var t=new og;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new sg;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Ed;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!ls.test(e))throw new me(oS,'not a valid xml name "'+e+'"');var t=new ag;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new na,n=t.split(":"),i=r.attributes=new vd;return r.childNodes=new $i,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=e,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,i._ownerElement=r,r},createAttributeNS:function(e,t){var r=new Ed,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}};Dr(eu,De);function na(){this._nsMap={}}na.prototype={nodeType:un,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var r=this.ownerDocument.createAttribute(e);r.value=r.nodeValue=""+t,this.setAttributeNode(r)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===ki?this.insertBefore(e,null):$8(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);r&&this.removeAttributeNode(r)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);return r&&r.value||""},setAttributeNS:function(e,t,r){var n=this.ownerDocument.createAttributeNS(e,t);n.value=n.nodeValue=""+r,this.setAttributeNode(n)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new cs(this,function(t){var r=[];return wd(t,function(n){n!==t&&n.nodeType==un&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new cs(this,function(r){var n=[];return wd(r,function(i){i!==r&&i.nodeType===un&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};eu.prototype.getElementsByTagName=na.prototype.getElementsByTagName;eu.prototype.getElementsByTagNameNS=na.prototype.getElementsByTagNameNS;Dr(na,De);function Ed(){}Ed.prototype.nodeType=us;Dr(Ed,De);function tu(){}tu.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(Ot[Tr])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){var n=this.data.substring(0,e),i=this.data.substring(e+t);r=n+r+i,this.nodeValue=this.data=r,this.length=r.length}};Dr(tu,De);function ng(){}ng.prototype={nodeName:"#text",nodeType:Yl,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};Dr(ng,tu);function ig(){}ig.prototype={nodeName:"#comment",nodeType:eg};Dr(ig,tu);function og(){}og.prototype={nodeName:"#cdata-section",nodeType:fS};Dr(og,tu);function Sd(){}Sd.prototype.nodeType=hS;Dr(Sd,De);function SS(){}SS.prototype.nodeType=D8;Dr(SS,De);function NS(){}NS.prototype.nodeType=T8;Dr(NS,De);function ag(){}ag.prototype.nodeType=pS;Dr(ag,De);function Nd(){}Nd.prototype.nodeName="#document-fragment";Nd.prototype.nodeType=ki;Dr(Nd,De);function sg(){}sg.prototype.nodeType=Zh;Dr(sg,De);function _S(){}_S.prototype.serializeToString=function(e,t,r,n){return TS.call(e,t,r,n)};De.prototype.toString=TS;function TS(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return lg(this,i,e,t,l,n),i.join("")}function dS(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ql.XML||i===Ql.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function bd(e,t,r,n){if(n&&!ls.test(t))throw new me(In,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,wS),'"')}function lg(e,t,r,n,i,o){i||(i=[]),It(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case un:var c=a.attributes,d=c.length,f=a.tagName;u=Ql.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!ls.test(m))throw new me(In,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),C=0;C<d;C++){var S=c.item(C);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var C=0;C<d;C++){var S=c.item(C);if(dS(S,u,w)){var O=S.prefix||"",L=S.namespaceURI;bd(t,O?"xmlns:"+O:"xmlns",L,o),w.push({prefix:O,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):bd(t,I.name,I.value,o))}if(f===m&&dS(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;bd(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;P;)P.data?t.push(P.data):lg(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case mS:case ki:return{ns:l.slice(),isHTML:u,tag:null};case us:return bd(t,a.name,a.value,o),null;case Yl:return t.push(a.data.replace(/[<&>]/g,wS)),null;case fS:if(o&&a.data.indexOf("]]>")!==-1)throw new me(In,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case eg:if(o&&a.data.indexOf("-->")!==-1)throw new me(In,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case hS:if(o){if(!ls.test(a.name))throw new me(In,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new me(In,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new me(In,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new me(In,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Le=a.internalSubset;Le&&t.push(" [",Le,"]"),t.push(">")}return null;case Zh:if(o){if(!ls.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new me(In,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new me(In,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case pS:if(o&&!ls.test(a.nodeName))throw new me(In,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function x8(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===us||r;return s?a:null}}),n}function DS(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new $i),a.ownerDocument=e;var u=r;switch(a.nodeType){case un:var c=i.attributes,d=a.attributes=new vd,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(DS(e,c.item(m),!0));break;case us:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function IS(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(cs.prototype,"length",{get:function(){return tg(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===un||this.nodeType===ki){var e=[];return It(this,null,{enter:function(t){if(t.nodeType===un||t.nodeType===ki)return!0;if(t.nodeType===Zh||t.nodeType===eg)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case un:case ki:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),IS=function(e,t,r){e["$$"+t]=r})}catch{}Fi.DocumentType=Sd;Fi.DOMException=me;Fi.DOMImplementation=vS;Fi.Element=na;Fi.Node=De;Fi.NodeList=$i;Fi.walkDOM=It;Fi.XMLSerializer=_S});var PS=v(ru=>{"use strict";var OS=ss().freeze;ru.XML_ENTITIES=OS({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ru.HTML_ENTITIES=OS({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`-`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});ru.entityMap=ru.HTML_ENTITIES});var xS=v(dg=>{var ou=ss().NAMESPACE,cg=ss().tagNamePattern,ds=0,ho=1,fs=2,nu=3,ps=4,ms=5,iu=6,_d=7;function hs(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,hs)}hs.prototype=new Error;hs.prototype.name=hs.name;function kS(){}kS.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),q8(t,t={}),F8(e,t,r,n,this.errorHandler),n.endDocument()}};function F8(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var Ke=55296+(de>>10),ur=56320+(de&1023);return String.fromCharCode(Ke,ur)}else return String.fromCharCode(de)}function a(de){var Ke=de.slice(1,-1);return Object.hasOwnProperty.call(r,Ke)?r[Ke]:Ke.charAt(0)==="#"?o(parseInt(Ke.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var Ke=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(Ke,0,de-h),h=de}}function l(de,Ke){for(;de>=c&&(Ke=d.exec(e));)u=Ke.index,c=u+Ke[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),C=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),K=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),K=g+1+C.length):/[ \t\n\r]/.test(C)&&cg.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,L=S.tagName==C,I=L||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,C),O)for(var D in O)Object.prototype.hasOwnProperty.call(O,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=G8(e,g,n);break;case"!":f&&l(g),K=V8(e,g,n,i);break;default:f&&l(g);var P=new $S,x=m[m.length-1].currentNSMap,K=M8(e,g,P,x,a,i),Le=P.length;if(!P.closed&&B8(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Le){for(var lr=RS(f,{}),Ge=0;Ge<Le;Ge++){var Ut=P[Ge];l(Ut.offset),Ut.locator=RS(f,{})}n.locator=lr,LS(P,n,x)&&m.push(P),n.locator=f}else LS(P,n,x)&&m.push(P);ou.isHTML(P.uri)&&!P.closed?K=U8(e,K,P.tagName,a,n):K++}}catch(de){if(de instanceof hs)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function RS(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function M8(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=ds;;){var d=e.charAt(u);if(c===ds&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ho)s=e.slice(t,u),c=nu;else if(c===fs)c=nu;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===nu||c===ho)if(c===ho&&(o.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),a(s,l,t-1),c=ms;else throw new Error("attribute value no end '"+d+"' match");else if(c==ps)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=ms;else throw new Error('attribute value must after "="');break;case"/":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:c=_d,r.closed=!0;case ps:case ho:break;case fs:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==ds&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:break;case ps:case ho:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case fs:c===fs&&(l=s),c==ps?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!ou.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case nu:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case ds:r.setTagName(e.slice(t,u)),c=iu;break;case ho:s=e.slice(t,u),c=fs;break;case ps:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case ms:c=iu;break}else switch(c){case fs:var f=r.tagName;(!ou.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ho;break;case ms:o.warning('attribute space is required"'+s+'"!!');case iu:c=ho,t=u;break;case nu:c=ps,t=u;break;case _d:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function LS(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=ou.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=ou.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var m=e.uri=r[l||""];if(t.startElement(m,u,n,e),e.closed){if(t.endElement(m,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function U8(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function B8(e,t,r,n){var i=n[r];return i==null&&(i=e.lastIndexOf("</"+r+">"),i<t&&(i=e.lastIndexOf("</"+r)),n[r]=i),i<t}function q8(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function V8(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=W8(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function G8(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function $S(){this.attributeNames={}}$S.prototype={setTagName:function(e){if(!cg.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!cg.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}};function W8(e,t){var r,n=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);r=i.exec(e);)if(n.push(r),r[1])return n}dg.XMLReader=kS;dg.ParseError=hs});var GS=v(Dd=>{var z8=ss(),j8=ug(),FS=PS(),BS=xS(),H8=j8.DOMImplementation,MS=z8.NAMESPACE,K8=BS.ParseError,J8=BS.XMLReader;function qS(e){return e.replace(/\r[\n\u0085]/g,`+`}});var NE=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.generateGenPageRuntimeTypes=void 0;var SE=Km(),Fo=Q(),AE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Mo="generateGenPageRuntimeTypes";async function vV(e,t,r){let n=wV(t),i=CV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Fo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Mo}: 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,SE.renderGenPageAuthoringTypes)(o,i)}Fc.generateGenPageRuntimeTypes=vV;function wV(e){if(!Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!SE.TABLE_LOGICAL_NAME.test(r))throw new Fo.InvalidArgumentError(`${Mo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Fo.InvalidArgumentError(`${Mo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function CV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Fo.InvalidArgumentError(`${Mo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!AE.has(r))throw new Fo.InvalidArgumentError(`${Mo}: detail must be one of ${[...AE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var PE=v(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.getEnvironmentLanguages=Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var EV=Q(),DE=ye();Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var _E="/organizations?$select=languagecode",AV="/RetrieveProvisionedLanguages()",SV="/RetrieveAvailableLanguages()";function IE(e,t){return new EV.SdkError(Uo.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 OE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function TE(e,t,r,n){let i=(0,DE.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(OE))throw IE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function NV(e){var t;let r=(0,DE.ensureSuccess)(await e.get(_E),e.apiUrl(_E)).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(!OE(i))throw IE("the organization read","did not answer one row with a language code");let o=await TE(e,AV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await TE(e,SV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Uo.getEnvironmentLanguages=NV});var Al=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.projectConnectorOperationSchema=nt.projectConnectorOperations=nt.validateConnectorSwagger=nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=nt.CONNECTOR_OPERATION_NOT_FOUND_CODE=nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var El=Q();nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";nt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var RE=64,LE=128,kE=2e5,$E=4e6,_V=new Set(["get","put","post","delete","patch","head","options"]),TV=new Set(["query","header","path","formData","body"]);function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Et(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Xe(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new El.SdkError(nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function Zi(e,t){return new El.SdkError(nt.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 DV(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||!vn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Qm(e,t,r){if(!t.startsWith("#/"))throw Zi(r,`has a $ref that is not a local '#/\u2026' pointer (${Xe(t)})`);if(t.includes("%"))throw Zi(r,`has a $ref with a percent-encoded character (${Xe(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${Xe(t)}): a '~' not followed by 0 or 1`);let n=DV(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${Xe(t)})`);return n.value}function Mc(e,t){if(vn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Et(e.$ref)}, not a string`);return e.$ref}}function IV(e,t,r){if(!Qr(t))throw ke(r,`is ${Et(t)}, not a parameter object`);let n=t,i=Mc(t,r);if(i!==void 0){let s=Qm(e,i,r);if(!Qr(s))throw ke(r,`has a $ref (${Xe(i)}) that resolves to ${Et(s)}, not a parameter object`);if(Mc(s,`${r} \u2192 ${Xe(i)}`)!==void 0)throw Zi(r,`has a $ref (${Xe(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!TV.has(o))throw ke(r,`has an in that is ${typeof o=="string"?Xe(o):Et(o)}, not one of query, header, path, formData or body`);if(vn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Et(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(vn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Et(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Jm(e){return`${e.in}:${e.name}`}function FE(e,t,r){if(!vn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Et(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=IV(e,o,s),u=Jm(l);if(i.has(u))throw ke(s,`repeats the parameter ${Xe(l.name)} in ${Xe(l.in)}, which must be unique in its list`);return i.add(u),l})}function ME(e,t,r){let n=t.responses;if(!vn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Qr(o))throw ke(i,`is ${Et(o)}, not a response object`);let a=o,s=Mc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${Xe(s)}) that does not name a response ('#/responses/<name>')`);let l=Qm(e,s,i);if(!Qr(l))throw ke(i,`has a $ref (${Xe(s)}) that resolves to ${Et(l)}, not a response object`);if(Mc(l,`${i} \u2192 ${Xe(s)}`)!==void 0)throw Zi(i,`has a $ref (${Xe(s)}) to a response that is itself a $ref`);a=l}if(vn(a,"content"))throw Zi(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(vn(a,"schema")){if(!Qr(a.schema))throw ke(i,`has a schema that is ${Et(a.schema)}, not an object`);return a.schema}}function xE(e,t,r){if(!vn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Et(n)}, not a string`);return n}function OV(e,t,r,n,i){if(!Qr(t))throw ke(r,`is ${Et(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Et(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${Xe(o)}, which must be unique in the document`);n.add(o);let a=xE(t,"summary",r),s=xE(t,"description",r),l=FE(e,t,r);if(!Qr(t.responses))throw ke(r,`has no responses object (${Et(t.responses)})`);return ME(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function Xm(e){if(!Qr(e))throw ke("the document",`is ${Et(e)}, not an object`);if(vn(e,"openapi"))throw Zi("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!vn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw Zi("the document",`declares swagger ${Xe(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Qr(t))throw ke("the document",`has paths that are ${Et(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Xe(i)}]`;if(!Qr(o))throw ke(a,`is ${Et(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(_V.has(l.toLowerCase()))r.push(OV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of FE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw Zi(a,`has a ${Xe(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function PV(e){Xm(e)}nt.validateConnectorSwagger=PV;var Ym=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new El.SdkError(nt.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>kE)throw this.tooLarge(`more than ${kE} nodes`)}text(t){if(this.characters+=t,this.characters>$E)throw this.tooLarge(`more than ${$E} characters of strings and keys`)}checkDepth(t){if(t>LE)throw this.tooLarge(`nesting deeper than ${LE} 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(Qr(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>=RE)throw this.tooLarge(`a $ref chain of more than ${RE} references`);let n=Qm(this.root,t,this.where);if(!Qr(n))throw ke(this.where,`has a schema $ref (${Xe(t)}) that resolves to ${Et(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function RV(e){let{operations:t}=Xm(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}})}}nt.projectConnectorOperations=RV;function LV(e,t){if(typeof t!="string"||t==="")throw new El.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=Xm(e),i=n.find(u=>u.id===t);if(!i)throw new El.SdkError(nt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Xe(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Jm)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Jm(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=ME(r,i.node,i.where),l=s===void 0?{}:new Ym(r,`${i.where} (${Xe(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}nt.projectConnectorOperationSchema=LV});var Bo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Sl=Q(),kV=ye(),$V=Al();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=yr;function Ba(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ba;function qa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=qa;function BE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=BE;function xV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=xV;var FV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,MV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function UV(e){let t=BE(e),r=t?t.host.toLowerCase():"";if(MV.test(r))return"Test";let n=FV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=UV;function Vn(e,t){return new Sl.SdkError($V.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Vn;function BV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=BV;function qV(e){if(typeof e=="string"&&e.length>0)return qa(e,500);if(yr(e)){let t=yr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return qa(r,500)}return"request failed"}J.messageOf=qV;function qE(e){return yr(e)&&yr(e.error)?e.error.code:void 0}J.errorCodeOf=qE;function VV(e){if(yr(e)&&yr(e.error)&&yr(e.error.innererror))return e.error.innererror.code}function GV(e,t,r){let n=[],i=qE(t);typeof i=="string"&&i.length>0&&n.push(qa(i,80));let o=VV(t);typeof o=="string"&&o.length>0&&n.push(qa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Sl.attachCause)(new Sl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=GV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var WV=/^[A-Za-z0-9_.-]{1,128}$/,zV=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function jV(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(WV.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Sl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${qa(e,80)}'`:Ba(e)}.`)}J.connectorShortName=jV;function HV(e,t,r){let n=`Connection row ${t}`;if(!yr(e))throw Vn(n,`it is ${Ba(e)}, not an object`);let i=e.properties;if(!yr(i))throw Vn(n,`its properties are ${Ba(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 Vn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Vn(n,"its apiId names no single connector");if(zV.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Vn(n,"it has no name");let l=i.environment,u=yr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Vn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Vn(n,`its displayName is ${Ba(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Vn(n,`its statuses are ${Ba(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=yr(f)?f.status:void 0;if(typeof m!="string")throw Vn(n,"one of its statuses has no string status");return m})}}J.readConnection=HV;var UE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function KV(e){let t=(0,kV.ensureSuccess)(await e.get(UE),e.apiUrl(UE)).body,r=yr(t)?t.Detail:void 0,n=yr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Sl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=KV});var KE=v(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.ConnectivityApi=br.CONNECTIVITY_UNAUTHORIZED_CODE=br.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=br.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=br.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=br.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Wt=Q(),JV=ye(),Bc=Al(),_l=Bo(),Tl=Bo();Object.defineProperty(br,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(br,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(br,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_UNAUTHORIZED_CODE}});var VE="2016-11-01",YV="2021-04-01",QV="https://api.bap.microsoft.com",XV="https://test.api.bap.microsoft.com",ZV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,e4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,GE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",bi="/providers/Microsoft.PowerApps/apis/",t4=/^[A-Za-z0-9_.-]{1,128}$/,r4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),n4="ServiceDecommissioned";function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eo(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Gn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Nl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function WE(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function i4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function Xr(e,t){return new Wt.SdkError(Bc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function Uc(e){return new Wt.SdkError(_l.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function zE(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function jE(e){if(typeof e=="string"&&e.length>0)return Gn(e,500);if(ct(e)){let t=ct(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Gn(r,500)}return"request failed"}function o4(e){return ct(e)&&ct(e.error)?e.error.code:void 0}function HE(e){if(typeof e=="string"){let r=e.slice(0,bi.length).toLowerCase()===bi.toLowerCase()?e.slice(bi.length):e;if(t4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Wt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${bi}shared_office365users'); got ${typeof e=="string"?`'${Gn(e,80)}'`:eo(e)}.`)}function a4(e,t,r){let n=`Connection row ${t}`;if(!ct(e))throw Xr(n,`it is ${eo(e)}, not an object`);let i=e.properties;if(!ct(i))throw Xr(n,`its properties are ${eo(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,bi.length).toLowerCase()!==bi.toLowerCase())throw Xr(n,`its apiId is not '${bi}<connector>'`);let a=o.slice(bi.length);if(a===""||a.includes("/"))throw Xr(n,"its apiId names no single connector");if(r4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Xr(n,"it has no name");let l=i.environment,u=ct(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Xr(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Xr(n,`its displayName is ${eo(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Xr(n,`its statuses are ${eo(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ct(f)?f.status:void 0;if(typeof m!="string")throw Xr(n,"one of its statuses has no string status");return m})}}var Zm=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=${VE}&$filter=${zE(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 Xr(u,`its value is ${eo(d)}, not an array`);for(let m of d){let p=a4(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 Xr(u,`its nextLink is ${f===""?"an empty string":eo(f)}, not a non-empty string`);if(i.has(f))throw new Wt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Gn(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=HE(t);return(0,Bc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=HE(t);if(typeof r!="string"||r==="")throw new Wt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Bc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Wt.SdkError(_l.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${YV}`,o=(await this.send(t,i,!1)).body,a=ct(o)?o.properties:void 0,s=ct(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw Uc(`BAP's environment row is not the one named '${Gn(n,80)}' (its name)`);let l=ct(a)&&ct(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Nl(l):void 0,c=Nl(this.instanceUrl);if(!u||!c||!WE(u,c))throw Uc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ct(a)?a.runtimeEndpoints:void 0,f=ct(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Nl(f):void 0;if(!m||m.protocol!=="https:"||!i4(m.host.toLowerCase()))throw Uc("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=Nl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=ZV.exec(r);if(n&&n[1]!=="9")return QV;if(e4.test(r))return XV;throw new Wt.SdkError(_l.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Gn(t.host,80)}'`:`'${Gn(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,JV.ensureSuccess)(await this.org.get(GE),this.org.apiUrl(GE)).body,r=ct(t)?t.Detail:void 0,n=ct(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw Uc("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}${bi}${i}?api-version=${VE}&$filter=${zE(n.id)}`,a=(await this.send(t,o,!0)).body,s=ct(a)?a.properties:void 0,l=ct(s)?s.swagger:void 0;if(!ct(l))throw Xr(`The connector '${Gn(r,80)}'`,`its properties.swagger is ${eo(l)}, not an object`);return(0,Bc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Nl(t);if(!n)throw new Wt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Gn(t)}'`);if(!WE(n,r))throw new Wt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Gn(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 Wt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Wt.SdkError?o:new Wt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Wt.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 Wt.ConnectionError(t,r,jE(n),n);return i&&r===410&&o4(n)===n4?(0,Wt.attachCause)(new Wt.SdkError(_l.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${jE(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,_l.connectivityUnauthorized)(r,n,a):a}};br.ConnectivityApi=Zm});var ih=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 qo=Q(),M=Bo(),s4=/^[A-Za-z0-9_.-]{1,128}$/,Vo=/^\.{1,2}$/,l4="shared_sharepointonline",u4=/^[0-9]{1,9}$/,c4=/^[A-Za-z0-9._~-]+$/,d4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,f4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,p4=/^[A-Za-z0-9._~!'()*-]$/,m4=/^[0-9A-Fa-f]{2}$/;function vi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function eh(e,t){return new qo.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function qc(e,t){return new qo.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 h4(e){if(typeof e=="string"&&s4.test(e)&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Dl(e)}.`)}function g4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Vo.test(r))===void 0)return e;throw new qo.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Dl(e)}.`)}}function y4(e){if(typeof e=="string"&&e!==""&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Dl(e)}.`)}function YE(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:h4(t),dataset:g4(r)}}Me.checkListTablesArguments=YE;function b4(e,t,r,n){return{...YE(e,t,r),table:y4(n)}}Me.checkTableSchemaArguments=b4;function v4(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(!vi(n,"interfaces"))throw eh(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(!vi(i,"CDPTabular1"))throw eh(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(!u4.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=w4(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 eh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=v4;function w4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>c4.test(i)&&!Vo.test(i))?t:void 0}function C4(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 qc(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 qc(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:d4.exec(l);if(!c||Vo.test(c[1]))throw qc(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:f4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Vo.test(c)))throw qc(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=C4;function E4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Dl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Dl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=E4;function JE(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function A4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!m4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!p4.test(e[t]))return!1;return!0}function QE(e,t){let r,n,i;try{r=JE(e),n=JE(r),i=decodeURIComponent(n)}catch{throw new qo.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!A4(n)||Vo.test(n)||i!==r)throw new qo.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function nh(e){return e.split(",").map((t,r)=>QE(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=nh;function XE(e){return QE(e,"table")}Me.encodeTable=XE;function S4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===l4?"allTables":"tables";return`/datasets/${nh(t)}/${r}`}Me.tablesSuffix=S4;function N4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${nh(e)}`}/tables/${XE(t)}`}Me.tableSchemaSuffix=N4;function Va(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 _4(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(Va(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=Va(e,"value"),i=n.found?n:Va(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)=>T4(n,i))}}Me.projectConnectorTables=_4;function T4(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=Va(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=Va(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=Va(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 th(e,t,r){if(!vi(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 rh(e,t,r){if(!vi(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 D4(e,t){var r,n;if(vi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=rh(e,"type",t),o=rh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!vi(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(vi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=rh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function I4(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=th(e,"items","items"),i=th(e,"schema","schema"),o=i?th(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&&vi(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&&vi(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:D4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=I4});var ZE=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.PowerPlatformApiDiscovery=void 0;var oh=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}`)}}};Vc.PowerPlatformApiDiscovery=oh});var eA=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.PowerPlatformApiDiscovery=void 0;var O4=ZE();Object.defineProperty(Gc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return O4.PowerPlatformApiDiscovery}})});var iA=v(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.platformTokenAudience=to.platformEnvironment=to.platformClusterOf=void 0;var tA=eA(),rA=Q(),nA=Bo(),P4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,R4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,L4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,k4=/^default-/i;function ah(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function $4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function x4(e){let t=$4(e);if(t){if(R4.test(t))return{cloud:"Test",category:"test"};let r=P4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new rA.SdkError(nA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${ah(t)}'`:`'${ah(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.`)}to.platformClusterOf=x4;function F4(e,t){let r=k4.test(e)?e.slice(8):e;if(!L4.test(r))throw new rA.SdkError(nA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${ah(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 tA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}to.platformEnvironment=F4;function M4(e){return new tA.PowerPlatformApiDiscovery(e).getTokenAudience()}to.platformTokenAudience=M4});var aA=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.PlatformConnectivityApi=Ga.assertTabularCloud=void 0;var wn=Q(),sh=Al(),fe=Bo(),oA=iA(),wi=ih(),lh="1";function uh(e){let t=(0,fe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new wn.SdkError(fe.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.")}Ga.assertTabularCloud=uh;var ch=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=${lh}`,[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,fe.unreadable)(s,`its value is ${(0,fe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,fe.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,fe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,fe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new wn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,fe.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,fe.connectorShortName)(t);return(0,sh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,fe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new wn.InvalidArgumentError("operationId must be a non-empty string.");return(0,sh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){uh(this.instanceUrl);let i=(0,wi.checkListTablesArguments)(t,r,n),o=(0,wi.tablesSuffix)(i.short,i.dataset);return(0,wi.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){uh(this.instanceUrl);let o=(0,wi.checkTableSchemaArguments)(t,r,n,i),a=(0,wi.tableSchemaSuffix)(o.dataset,o.table);return(0,wi.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,wi.tabularRevision)(o,t.short),s=(0,wi.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,fe.environmentFilter)(i.name)}&api-version=${lh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,wi.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 wn.SdkError(fe.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,oA.platformClusterOf)(this.instanceUrl),n=await(0,fe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,oA.platformEnvironment)(n,r),a=(0,fe.parseUrl)(i);if(!a)throw(0,fe.unreadable)("The Power Platform API origin",`'${(0,fe.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,fe.environmentFilter)(r.name)}&api-version=${lh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,fe.isObject)(i)?i.name:void 0;if(!(0,fe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,fe.bounded)(o,80)}'`:(0,fe.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,fe.isObject)(n)?n.swagger:void 0;if(!(0,fe.isObject)(i))throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`its properties.swagger is ${(0,fe.kindOf)(i)}, not an object`);return(0,sh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,fe.parseUrl)(t);if(!n)throw new wn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,fe.bounded)(t)}'`);if(!(0,fe.sameOrigin)(n,r))throw new wn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,fe.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 wn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof wn.SdkError?s:new wn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new wn.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 wn.ConnectionError(t,r,(0,fe.messageOf)(n),n);return i.includes(r)?(0,fe.connectivityUnauthorized)(r,n,a):a}};Ga.PlatformConnectivityApi=ch});var lA=v(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.ConnectivityRouter=void 0;var dh=Q(),U4=KE(),Wc=Bo(),sA=ih(),fh=aA(),ph=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,fh.assertTabularCloud)(this.instanceUrl),(0,sA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,fh.assertTabularCloud)(this.instanceUrl),(0,sA.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 fh.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 dh.SdkError(Wc.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,Wc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new dh.SdkError(Wc.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 U4.ConnectivityApi(this.org,this.instanceUrl,r);throw new dh.SdkError(Wc.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.")}};zc.ConnectivityRouter=ph});var Wa=v(Ci=>{"use strict";function B4(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 hh(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 uA=hh({HTML:"text/html",isHTML:function(e){return e===uA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),cA=hh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===cA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),jc=/[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]/,mh=new RegExp("[\\-\\.0-9"+jc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),V4=new RegExp("^"+jc.source+mh.source+"*(?::"+jc.source+mh.source+"*)?$");Ci.assign=q4;Ci.find=B4;Ci.freeze=hh;Ci.MIME_TYPE=uA;Ci.NAMESPACE=cA;Ci.nameStartChar=jc;Ci.nameChar=mh;Ci.tagNamePattern=V4});var Th=v(Ni=>{var gh=Wa(),Wn=gh.find,Ol=gh.NAMESPACE,za=gh.tagNamePattern;function G4(e){return e!==""}function W4(e){return e?e.split(/[\t\n\f\r ]+/).filter(G4):[]}function z4(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function dA(e){if(!e)return[];var t=W4(e);return Object.keys(t.reduce(z4,{}))}function j4(e){return function(t){return e&&e.indexOf(t)!==-1}}function Rl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function wr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Rl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Cr={},Zr=Cr.ELEMENT_NODE=1,ja=Cr.ATTRIBUTE_NODE=2,Il=Cr.TEXT_NODE=3,vA=Cr.CDATA_SECTION_NODE=4,wA=Cr.ENTITY_REFERENCE_NODE=5,H4=Cr.ENTITY_NODE=6,yh=Cr.PROCESSING_INSTRUCTION_NODE=7,bh=Cr.COMMENT_NODE=8,CA=Cr.DOCUMENT_NODE=9,EA=Cr.DOCUMENT_TYPE_NODE=10,Ei=Cr.DOCUMENT_FRAGMENT_NODE=11,K4=Cr.NOTATION_NODE=12,zt={},St={},Ise=zt.INDEX_SIZE_ERR=(St[1]="Index size error",1),Ose=zt.DOMSTRING_SIZE_ERR=(St[2]="DOMString size error",2),vr=zt.HIERARCHY_REQUEST_ERR=(St[3]="Hierarchy request error",3),Pse=zt.WRONG_DOCUMENT_ERR=(St[4]="Wrong document",4),fA=zt.INVALID_CHARACTER_ERR=(St[5]="Invalid character",5),Rse=zt.NO_DATA_ALLOWED_ERR=(St[6]="No data allowed",6),Lse=zt.NO_MODIFICATION_ALLOWED_ERR=(St[7]="No modification allowed",7),AA=zt.NOT_FOUND_ERR=(St[8]="Not found",8),kse=zt.NOT_SUPPORTED_ERR=(St[9]="Not supported",9),pA=zt.INUSE_ATTRIBUTE_ERR=(St[10]="Attribute in use",10),Cn=zt.INVALID_STATE_ERR=(St[11]="Invalid state",11),$se=zt.SYNTAX_ERR=(St[12]="Syntax error",12),xse=zt.INVALID_MODIFICATION_ERR=(St[13]="Invalid modification",13),Fse=zt.NAMESPACE_ERR=(St[14]="Invalid namespace",14),Mse=zt.INVALID_ACCESS_ERR=(St[15]="Invalid access",15);function pe(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,St[e]),this.message=St[e],Error.captureStackTrace&&Error.captureStackTrace(this,pe);return r.code=e,t&&(this.message=this.message+": "+t),r}pe.prototype=Error.prototype;Rl(zt,pe);function Ai(){}Ai.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++)_h(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 Ha(e,t){this._node=e,this._refresh=t,vh(this)}function vh(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(xA(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];Rl(r,e),e._inc=t}}Ha.prototype.item=function(e){return vh(this),this[e]||null};wr(Ha,Ai);function Kc(){this._nameIndex=Object.create(null)}function SA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function J4(e,t){e._nameIndex[t.nodeName]=t}function NA(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function mA(e,t,r,n){if(n?(t[SA(t,n)]=r,NA(t,n)):t[t.length++]=r,J4(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&DA(i,e,n),Y4(i,e,r))}}function hA(e,t,r){var n=SA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,NA(t,r),e){var o=e.ownerDocument;o&&(DA(o,e,r),r.ownerElement=null)}}else throw new pe(AA,new Error(e.tagName+"@"+r))}Kc.prototype={length:0,item:Ai.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 pe(pA);var r=this._nameIndex[e.nodeName];return mA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new pe(pA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),mA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return hA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return hA(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 _A(){}_A.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ll;if(n.implementation=this,n.childNodes=new Ai,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 Zc;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 Yc(this,e,t)},replaceChild:function(e,t){Yc(this,e,t,OA),t&&this.removeChild(t)},removeChild:function(e){return IA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return $A(this.ownerDocument||this,this,e)},normalize:function(){At(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Il&&t.nodeType===Il){for(var n=[],i=r;i!==null&&i.nodeType===Il;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Xc(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 TA(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Rl(Cr,De);Rl(Cr,De.prototype);function Jc(e,t){return At(e,null,{enter:function(r){return t(r)?At.STOP:!0}})===At.STOP}function At(e,t,r){for(var n=[{node:e,context:t,phase:At.ENTER}];n.length>0;){var i=n.pop();if(i.phase===At.ENTER){var o=r.enter(i.node,i.context);if(o===At.STOP)return At.STOP;if(n.push({node:i.node,context:o,phase:At.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:At.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}At.STOP=Symbol("walkDOM.STOP");At.ENTER=0;At.EXIT=1;function Ll(){this.ownerDocument=this}function Y4(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ol.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function DA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ol.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Xc(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 IA(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,Xc(e.ownerDocument,e),t}function Q4(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function X4(e){return e&&(zn(e)||wh(e)||Si(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Si(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function wh(e){return e&&e.nodeType===De.TEXT_NODE}function gA(e,t){var r=e.childNodes||[];if(Wn(r,zn)||Si(t))return!1;var n=Wn(r,Si);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function yA(e,t){var r=e.childNodes||[];function n(o){return zn(o)&&o!==t}if(Wn(r,n))return!1;var i=Wn(r,Si);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Z4(e,t,r){if(!Q4(e))throw new pe(vr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new pe(AA,"child not in parent");if(!X4(t)||Si(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new pe(vr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function eG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!gA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!gA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){if(Wn(n,Si))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element");if(!r&&a)throw new pe(vr,"Doctype can not be appended since element is present")}}function OA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!yA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!yA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){let l=function(u){return Si(u)&&u!==r};var s=l;if(Wn(n,l))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element")}}function Yc(e,t,r,n){Z4(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||eG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ei){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Pl(o,l)}while(o!==a&&(o=o.nextSibling));return Xc(e.ownerDocument||e,e),t.nodeType==Ei&&(t.firstChild=t.lastChild=null),t}function Pl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Zr&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)Pl(i,t),i=i.nextSibling}}function tG(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,Xc(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Pl(t,r),t}Ll.prototype={nodeName:"#document",nodeType:CA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ei){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Yc(this,e,t),Pl(e,this),this.documentElement===null&&e.nodeType===Zr&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),IA(this,e)},replaceChild:function(e,t){Yc(this,e,t,OA),Pl(e,this),t&&this.removeChild(t),zn(e)&&(this.documentElement=e)},importNode:function(e,t){return rG(this,e,t)},getElementById:function(e){var t=null;return Jc(this.documentElement,function(r){if(r.nodeType==Zr&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=dA(e);return new Ha(this,function(r){var n=[];return t.length>0&&Jc(r.documentElement,function(i){if(i!==r&&i.nodeType===Zr){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=dA(o);a=t.every(j4(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Go;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ai;var r=t.attributes=new Kc;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new ed;return e.ownerDocument=this,e.childNodes=new Ai,e},createTextNode:function(e){var t=new Ch;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Eh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new pe(fA,'data contains "]]>"');var t=new Ah;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Nh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Qc;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!za.test(e))throw new pe(fA,'not a valid xml name "'+e+'"');var t=new Sh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Go,n=t.split(":"),i=r.attributes=new Kc;return r.childNodes=new Ai,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 Qc,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}};wr(Ll,De);function Go(){this._nsMap={}}Go.prototype={nodeType:Zr,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===Ei?this.insertBefore(e,null):tG(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 Ha(this,function(t){var r=[];return Jc(t,function(n){n!==t&&n.nodeType==Zr&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ha(this,function(r){var n=[];return Jc(r,function(i){i!==r&&i.nodeType===Zr&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ll.prototype.getElementsByTagName=Go.prototype.getElementsByTagName;Ll.prototype.getElementsByTagNameNS=Go.prototype.getElementsByTagNameNS;wr(Go,De);function Qc(){}Qc.prototype.nodeType=ja;wr(Qc,De);function kl(){}kl.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(St[vr])},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}};wr(kl,De);function Ch(){}Ch.prototype={nodeName:"#text",nodeType:Il,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};wr(Ch,kl);function Eh(){}Eh.prototype={nodeName:"#comment",nodeType:bh};wr(Eh,kl);function Ah(){}Ah.prototype={nodeName:"#cdata-section",nodeType:vA};wr(Ah,kl);function Zc(){}Zc.prototype.nodeType=EA;wr(Zc,De);function PA(){}PA.prototype.nodeType=K4;wr(PA,De);function RA(){}RA.prototype.nodeType=H4;wr(RA,De);function Sh(){}Sh.prototype.nodeType=wA;wr(Sh,De);function ed(){}ed.prototype.nodeName="#document-fragment";ed.prototype.nodeType=Ei;wr(ed,De);function Nh(){}Nh.prototype.nodeType=yh;wr(Nh,De);function LA(){}LA.prototype.serializeToString=function(e,t,r,n){return kA.call(e,t,r,n)};De.prototype.toString=kA;function kA(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 _h(this,i,e,t,l,n),i.join("")}function bA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ol.XML||i===Ol.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function Hc(e,t,r,n){if(n&&!za.test(t))throw new pe(Cn,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,TA),'"')}function _h(e,t,r,n,i,o){i||(i=[]),At(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 Zr:var c=a.attributes,d=c.length,f=a.tagName;u=Ol.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&&!za.test(m))throw new pe(Cn,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),E=0;E<d;E++){var S=c.item(E);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var E=0;E<d;E++){var S=c.item(E);if(bA(S,u,w)){var P=S.prefix||"",L=S.namespaceURI;Hc(t,P?"xmlns:"+P:"xmlns",L,o),w.push({prefix:P,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):Hc(t,I.name,I.value,o))}if(f===m&&bA(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;Hc(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var O=a.firstChild;if(O||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;O;)O.data?t.push(O.data):_h(O,t,u,n,w.slice(),o),O=O.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case CA:case Ei:return{ns:l.slice(),isHTML:u,tag:null};case ja:return Hc(t,a.name,a.value,o),null;case Il:return t.push(a.data.replace(/[<&>]/g,TA)),null;case vA:if(o&&a.data.indexOf("]]>")!==-1)throw new pe(Cn,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case bh:if(o&&a.data.indexOf("-->")!==-1)throw new pe(Cn,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case EA:if(o){if(!za.test(a.name))throw new pe(Cn,'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 pe(Cn,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new pe(Cn,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new pe(Cn,'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 Re=a.internalSubset;Re&&t.push(" [",Re,"]"),t.push(">")}return null;case yh:if(o){if(!za.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new pe(Cn,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new pe(Cn,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case wA:if(o&&!za.test(a.nodeName))throw new pe(Cn,'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 rG(e,t,r){var n;return At(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 $A(e,t,r){var n;return At(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 Ai),a.ownerDocument=e;var u=r;switch(a.nodeType){case Zr:var c=i.attributes,d=a.attributes=new Kc,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode($A(e,c.item(m),!0));break;case ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function xA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ha.prototype,"length",{get:function(){return vh(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===Zr||this.nodeType===Ei){var e=[];return At(this,null,{enter:function(t){if(t.nodeType===Zr||t.nodeType===Ei)return!0;if(t.nodeType===yh||t.nodeType===bh)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Zr:case Ei: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}}}),xA=function(e,t,r){e["$$"+t]=r})}catch{}Ni.DocumentType=Zc;Ni.DOMException=pe;Ni.DOMImplementation=_A;Ni.Element=Go;Ni.Node=De;Ni.NodeList=Ai;Ni.walkDOM=At;Ni.XMLSerializer=LA});var MA=v($l=>{"use strict";var FA=Wa().freeze;$l.XML_ENTITIES=FA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});$l.HTML_ENTITIES=FA({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"});$l.entityMap=$l.HTML_ENTITIES});var GA=v(Ih=>{var Ml=Wa().NAMESPACE,Dh=Wa().tagNamePattern,Ka=0,ro=1,Ja=2,xl=3,Ya=4,Qa=5,Fl=6,td=7;function Xa(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Xa)}Xa.prototype=new Error;Xa.prototype.name=Xa.name;function qA(){}qA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),sG(t,t={}),nG(e,t,r,n,this.errorHandler),n.endDocument()}};function nG(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var He=55296+(de>>10),bn=56320+(de&1023);return String.fromCharCode(He,bn)}else return String.fromCharCode(de)}function a(de){var He=de.slice(1,-1);return Object.hasOwnProperty.call(r,He)?r[He]:He.charAt(0)==="#"?o(parseInt(He.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var He=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(He,0,de-h),h=de}}function l(de,He){for(;de>=c&&(He=d.exec(e));)u=He.index,c=u+He[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),E=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+S.tagName),K=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),K=g+1+E.length):/[ \t\n\r]/.test(E)&&Dh.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var P=S.localNSMap,L=S.tagName==E,I=L||S.tagName&&S.tagName.toLowerCase()==E.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,E),P)for(var D in P)Object.prototype.hasOwnProperty.call(P,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=uG(e,g,n);break;case"!":f&&l(g),K=lG(e,g,n,i);break;default:f&&l(g);var O=new VA,x=m[m.length-1].currentNSMap,K=iG(e,g,O,x,a,i),Re=O.length;if(!O.closed&&aG(e,K,O.tagName,p)&&(O.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Re){for(var qt=UA(f,{}),ge=0;ge<Re;ge++){var je=O[ge];l(je.offset),je.locator=UA(f,{})}n.locator=qt,BA(O,n,x)&&m.push(O),n.locator=f}else BA(O,n,x)&&m.push(O);Ml.isHTML(O.uri)&&!O.closed?K=oG(e,K,O.tagName,a,n):K++}}catch(de){if(de instanceof Xa)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function UA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function iG(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=Ka;;){var d=e.charAt(u);if(c===Ka&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ro)s=e.slice(t,u),c=xl;else if(c===Ja)c=xl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===xl||c===ro)if(c===ro&&(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=Qa;else throw new Error("attribute value no end '"+d+"' match");else if(c==Ya)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Qa;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:c=td,r.closed=!0;case Ya:case ro:break;case Ja:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Ka&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:break;case Ya:case ro:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ja:c===Ja&&(l=s),c==Ya?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Ml.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case xl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Ka:r.setTagName(e.slice(t,u)),c=Fl;break;case ro:s=e.slice(t,u),c=Ja;break;case Ya:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case Qa:c=Fl;break}else switch(c){case Ja:var f=r.tagName;(!Ml.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ro;break;case Qa:o.warning('attribute space is required"'+s+'"!!');case Fl:c=ro,t=u;break;case xl:c=Ya,t=u;break;case td:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function BA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Ml.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Ml.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var 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 oG(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 aG(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 sG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function lG(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=cG(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 uG(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 VA(){this.attributeNames={}}VA.prototype={setTagName:function(e){if(!Dh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Dh.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 cG(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}Ih.XMLReader=qA;Ih.ParseError=Xa});var YA=v(nd=>{var dG=Wa(),fG=Th(),WA=MA(),HA=GA(),pG=fG.DOMImplementation,zA=dG.NAMESPACE,mG=HA.ParseError,hG=HA.XMLReader;function KA(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}function VS(e){this.options=e||{locator:{}}}VS.prototype.parseFromString=function(e,t){var r=this.options,n=new J8,i=r.domBuilder||new au,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?FS.HTML_ENTITIES:FS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=Y8(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=MS.HTML),s.xml=s.xml||MS.XML;var c=r.normalizeLineEndings||qS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function Y8(e,t,r){if(!e){if(t instanceof au)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+fg(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function au(){this.cdata=!1}function gs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}au.prototype={startDocument:function(){this.doc=new H8().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;Td(this,o),this.currentElement=o,this.locator&&gs(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&gs(n.getLocator(s),u),u.value=u.nodeValue=l,o.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&gs(this.locator,r),Td(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=US.apply(this,arguments),e){if(this.cdata)var n=this.doc.createCDATASection(e);else var n=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(n):/^\s*$/.test(e)&&this.doc.appendChild(n),this.locator&&gs(this.locator,n)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,r){e=US.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&gs(this.locator,n),Td(this,n)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,r){var n=this.doc.implementation;if(n&&n.createDocumentType){var i=n.createDocumentType(e,t,r);this.locator&&gs(this.locator,i),Td(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,fg(this.locator))},error:function(e){console.error("[xmldom error] "+e,fg(this.locator))},fatalError:function(e){throw new K8(e,this.locator)}};function fg(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function US(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){au.prototype[e]=function(){return null}});function Td(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Dd.__DOMHandler=au;Dd.normalizeLineEndings=qS;Dd.DOMParser=VS});var ys=v(Id=>{var WS=ug();Id.DOMImplementation=WS.DOMImplementation;Id.XMLSerializer=WS.XMLSerializer;Id.DOMParser=GS().DOMParser});var jS={};nn(jS,{CCFControlConstants:()=>zS,CCFPropertyConstants:()=>mg,CustomControlDataType:()=>F,CustomControlNames:()=>Mi,DefaultControlNameKeys:()=>pg,ICCModeEnum:()=>go,JSONParametersConstants:()=>hg,LookUpType:()=>Od,ManifestXMLConstants:()=>Xt,NumberType:()=>Pd,Usage:()=>ia});var zS,mg,hg,Xt,F,pg,Mi,go,ia,Od,Pd,oa=k(()=>{"use strict";zS={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},mg={Name:"Name",Value:"Value",Type:"Type",TypeGroup:"TypeGroup",Usage:"Usage",Static:"Static",Primary:"Primary",Columns:"Columns",EnableViewPicker:"EnableViewPicker",EntityName:"EntityName",FilteredViewIds:"FilteredViewIds",ReferencingName:"ReferencingName",RelationshipName:"RelationshipName",RelationshipType:"RelationshipType",TargetEntityType:"TargetEntityType",ViewId:"ViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DefaultViewId:"DefaultViewId",BindAttribute:"BindAttribute",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",QuickForms:"QuickForms",EntityNameKey:"EntityNameKey",CardFormType:"Form.Card",CardFormId:"CardFormId",Hidden:"Hidden",Required:"Required",DefaultValue:"DefaultValue"},hg={GroupDefinition:"GroupDefinition"},Xt={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(F||(F={}));(function(e){e.BooleanType="CC_FlipLabel_Name",e.DateTimeType="CC_TextBox_Name",e.DecimalType="CC_TextBox_Name",e.DoubleType="CC_TextBox_Name",e.IntegerType="CC_TextBox_Name",e.LookupType="CC_TextBox_Name",e.MemoType="CC_TextArea_Name",e.MoneyType="CC_TextBox_Name",e.OptionSetType="CC_OptionSet_Name",e.StringType="CC_TextBox_Name",e.GridType="CC_ReadOnlyGrid_Name",e.UnboundCustomControlType="CC_UnboundCustomControl_Name"})(pg||(pg={}));(function(e){e.ArcKnobControl="MscrmControls.Knob.ArcKnobControl",e.CardFeedNameControl="MscrmControls.CardFeedContainer.CardFeedContainer",e.CheckboxControl="MscrmControls.FieldControls.CheckboxControl",e.DateTimeControl="MscrmControls.FieldControls.DateTimeControl",e.DurationControl="MscrmControls.FieldControls.DurationControl",e.EditableGridControl="MscrmControls.Grid.GridControl",e.EmailEngagementActionsControl="MscrmControls.EmailEngagement.EmailEngagementActionsControl",e.FormComponent="MscrmControls.ModelForm.ModelFormControl",e.LanguageCodeControl="MscrmControls.FieldControls.LanguagePickerControl",e.LinearSliderControl="MscrmControls.Slider.LinearSliderControl",e.MultiSelectOptionSetControl="MscrmControls.MultiSelectPicklist.UpdMSPicklistControl",e.OptionSetControl="MscrmControls.OptionSet.OptionSetControl",e.PowerBIPCFControl="MscrmControls.PowerBIPCFControl",e.PredictiveScoringWidget="MscrmControls.Sales.PredictiveScoringWidget.PredictiveScoringWidget",e.ReadonlyGrid="MscrmControls.Grid.ReadOnlyGrid",e.SimilarCasesGrid="MscrmControls.Containers.SimilarCasesGridControl",e.StarRatingControl="MscrmControls.Rating.StarRatingControl",e.TimeZoneControl="MscrmControls.FieldControls.TimeZonePickListControl",e.ModelFormControl="MscrmControls.ModelForm.ModelFormControl",e.AutoCompleteControl="MscrmControls.AutoComplete.AutoCompleteControl",e.CanvasAppControl="MscrmControls.Canvas.CanvasControl",e.PowerAppsOneGrid="Microsoft.PowerApps.PowerAppsOneGrid"})(Mi||(Mi={}));(function(e){e[e.Read=0]="Read",e[e.Edit=1]="Edit",e[e.Both=2]="Both",e[e.Container=3]="Container",e[e.Unknown=4]="Unknown"})(go||(go={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ia||(ia={}));Od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],Pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var bs,dr,su=k(()=>{"use strict";bs=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,r){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(r),!0)}upsert(t,r){this.update(t,r)||this.add(t,r)}sortedUpsert(t,r){if(!this.update(t,r)){let n=0;for(;n<this.keys.length&&this.keys[n]<t;)n++;this.keys.splice(n,0,t),this.values.splice(n,0,r)}}clear(){this.keys=[],this.values=[]}containsKey(t){return this.keys.indexOf(t)!==-1}containsValue(t){return this.values.indexOf(t)!==-1}count(){return this.keys.length}getValue(t){let r=this.keys.indexOf(t);return r!==-1?this.values[r]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let r=this.keys.indexOf(t);return r!==-1?(this.keys.splice(r,1),this.values.splice(r,1),!0):!1}update(t,r){let n=this.keys.indexOf(t);return n!==-1?(this.values[n]=r,!0):!1}},dr=class{data={};add(t,r){return this.containsKey(t)?!1:(this.data[t]=r,!0)}upsert(t,r){this.data[t]=r}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let r in this.data)if(this.data[r]===t)return!0;return!1}count(){return Object.keys(this.data).length}getValue(t){return this.containsKey(t)?this.data[t]:!1}getKeys(){return Object.keys(this.data)}getValues(){let t=[];for(let r in this.data)t.push(this.data[r]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,r){return this.containsKey(t)?(this.data[t]=r,!0):!1}getInternalObject(){return this.data}}});var HS={};nn(HS,{AttributeDataSourceType:()=>lu,AttributeDataSourceTypeMask:()=>Rd,AttributePrecisionSource:()=>uu,EntityAttributeDataSourceType:()=>aa,EntityAttributeDateTimeBehavior:()=>bg,EntityAttributeImeMode:()=>yg,EntityAttributePrecisionSource:()=>vg,EntityAttributeRequiredLevel:()=>yo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ui,EntityResxKeyLookUp:()=>Ld,SourceTypeMask:()=>gg});var Ui,$,W,yo,aa,gg,lu,Rd,yg,bg,vg,uu,Ld,vs=k(()=>{"use strict";su();Ui=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return Ld.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})($||($={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));yo=class extends Ui{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},aa=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?lu.Persistent:parseInt(lu[this.name])}},gg=class e extends Ui{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(Rd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(lu||(lu={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(Rd||(Rd={}));yg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},bg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},vg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?uu.Currency:parseInt(uu[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(uu||(uu={}));Ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new bs;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(aa.Persistent,"SystemCustomization.String.Source.persistent"),t.add(aa.Calculated,"SystemCustomization.String.Source.calculated"),t.add(aa.Rollup,"SystemCustomization.String.Source.rollup"),t.add(aa.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var cu=v(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.parsePcfManifest=ut.parseControlElement=ut.parseManifestRoot=ut.firstLevel=ut.attr=ut.elementChildren=ut.manifestTypesForColumn=ut.DEFAULT_TYPE_GROUPS=void 0;var Q8=ys(),H=(oa(),zr(jS)),ve=(vs(),zr(HS));ut.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var X8="Phone";function Z8(e,t,r){switch(e){case ve.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case ve.EntityAttributeType.Customer:case ve.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case ve.EntityAttributeType.DateTime:return t===ve.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case ve.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case ve.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case ve.EntityAttributeType.File:return[H.CustomControlDataType.File];case ve.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case ve.EntityAttributeType.WholeNumber:return t===ve.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===ve.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===ve.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case ve.EntityAttributeType.LookupType:case ve.EntityAttributeType.Lookup:return t===ve.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case ve.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case ve.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case ve.EntityAttributeType.Owner:case ve.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case ve.EntityAttributeType.PartyList:case ve.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case ve.EntityAttributeType.Status:case ve.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case ve.EntityAttributeType.SingleLineofText:switch(t){case ve.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case ve.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case ve.EntityAttributeTypeFormat.Text:return r===X8?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case ve.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case ve.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case ve.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case ve.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ut.manifestTypesForColumn=Z8;function wg(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}ut.elementChildren=wg;function On(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ut.attr=On;function ei(e,...t){return wg(e).filter(r=>t.includes(r.tagName))}ut.firstLevel=ei;function e9(e){let t=new Map;for(let r of ei(e,"type-group"))t.set(String(On(r,"name")),ei(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function t9(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(wg(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var r9={input:"input",bound:"bound",output:"output"};function n9(e,t,r){let n=On(e,"usage"),i=n!==null&&r9[n]||"input",o=On(e,"default-value"),a=ei(e,"value").map(m=>{let p={name:On(m,"name"),value:String(m.textContent),isDefault:On(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=On(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ut.DEFAULT_TYPE_GROUPS,s)?ut.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=On(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:On(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:On(e,"required")==="true",hidden:On(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function KS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new Q8.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}ut.parseManifestRoot=KS;function JS(e){let t=ei(KS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ut.parseControlElement=JS;function i9(e){let t=JS(e),r=e9(t),n=ei(t,"data-set"),i=ei(t,"property"),o=ei(t,"groups"),a=[],s=!1;for(let u of i){let c=n9(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>ei(u,"group").some(c=>ei(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:t9(t)}}ut.parsePcfManifest=i9});var QS=v(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.readPcfColumn=Cs.readControlManifest=void 0;var ws=oe(),o9=cu();function Cg(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function a9(e,t){var r;let n="/customcontrols"+(0,ws.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ws.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Cg(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,o9.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}Cs.readControlManifest=a9;var s9=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function YS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function l9(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ws.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ws.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ws.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Cg(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=YS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=s9.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ws.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Cg(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=YS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}Cs.readPcfColumn=l9});var sa=v(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});kd.DEFAULT_LCID=void 0;kd.DEFAULT_LCID=1033});var ct=v(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.assignMissingIds=ti.pointerTouchesValueMap=ti.isValueMapKey=ti.newId=void 0;var u9=Xa();function XS(){return globalThis.crypto.randomUUID().toLowerCase()}ti.newId=XS;function c9(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ag=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function d9(e){return Ag.has(e)}ti.isValueMapKey=d9;function f9(e){return u9.JsonPointer.parse(e).some(t=>Ag.has(t))}ti.pointerTouchesValueMap=f9;function p9(e){return Eg(e),e}ti.assignMissingIds=p9;function Eg(e){if(Array.isArray(e)){e.forEach(t=>Eg(t));return}if(c9(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=XS());for(let t of Object.keys(e))t==="id"||Ag.has(t)||Eg(e[t])}}});var Es=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.sendChangeSet=Or.partResponse=Or.postChangeSet=Or.parseChangeSetParts=Or.parseChangeSetStatuses=Or.renderChangeSet=void 0;var bo=Q(),Sg=fe(),ZS=ct(),du=oe();function Ng(e,t){let r=`batch_${(0,ZS.newId)()}`,n=`changeset_${(0,ZS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,du.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,du.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,du.assertNoControlChars)(m,"batch operation header name"),(0,du.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new bo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,du.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r+`)}function JA(e){this.options=e||{locator:{}}}JA.prototype.parseFromString=function(e,t){var r=this.options,n=new hG,i=r.domBuilder||new Ul,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?WA.HTML_ENTITIES:WA.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=gG(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=zA.HTML),s.xml=s.xml||zA.XML;var c=r.normalizeLineEndings||KA;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function gG(e,t,r){if(!e){if(t instanceof Ul)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Oh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Ul(){this.cdata=!1}function Za(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Ul.prototype={startDocument:function(){this.doc=new pG().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;rd(this,o),this.currentElement=o,this.locator&&Za(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&&Za(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&&Za(this.locator,r),rd(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=jA.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&&Za(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=jA.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Za(this.locator,n),rd(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&&Za(this.locator,i),rd(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Oh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Oh(this.locator))},fatalError:function(e){throw new mG(e,this.locator)}};function Oh(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function jA(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){Ul.prototype[e]=function(){return null}});function rd(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}nd.__DOMHandler=Ul;nd.normalizeLineEndings=KA;nd.DOMParser=JA});var es=v(id=>{var QA=Th();id.DOMImplementation=QA.DOMImplementation;id.XMLSerializer=QA.XMLSerializer;id.DOMParser=YA().DOMParser});var ZA={};Hr(ZA,{CCFControlConstants:()=>XA,CCFPropertyConstants:()=>Rh,CustomControlDataType:()=>F,CustomControlNames:()=>_i,DefaultControlNameKeys:()=>Ph,ICCModeEnum:()=>no,JSONParametersConstants:()=>Lh,LookUpType:()=>od,ManifestXMLConstants:()=>jt,NumberType:()=>ad,Usage:()=>Wo});var XA,Rh,Lh,jt,F,Ph,_i,no,Wo,od,ad,zo=k(()=>{"use strict";XA={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"},Rh={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"},Lh={GroupDefinition:"GroupDefinition"},jt={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"})(Ph||(Ph={}));(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"})(_i||(_i={}));(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"})(no||(no={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(Wo||(Wo={}));od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],ad=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var ts,nr,Bl=k(()=>{"use strict";ts=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}},nr=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 eS={};Hr(eS,{AttributeDataSourceType:()=>ql,AttributeDataSourceTypeMask:()=>sd,AttributePrecisionSource:()=>Vl,EntityAttributeDataSourceType:()=>jo,EntityAttributeDateTimeBehavior:()=>xh,EntityAttributeImeMode:()=>$h,EntityAttributePrecisionSource:()=>Fh,EntityAttributeRequiredLevel:()=>io,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ti,EntityResxKeyLookUp:()=>ld,SourceTypeMask:()=>kh});var Ti,$,W,io,jo,kh,ql,sd,$h,xh,Fh,Vl,ld,rs=k(()=>{"use strict";Bl();Ti=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return ld.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})($||($={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));io=class extends Ti{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},jo=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?ql.Persistent:parseInt(ql[this.name])}},kh=class e extends Ti{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(sd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ql||(ql={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(sd||(sd={}));$h=class e extends Ti{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"}},xh=class e extends Ti{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"}},Fh=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?Vl.Currency:parseInt(Vl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Vl||(Vl={}));ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new ts;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(jo.Persistent,"SystemCustomization.String.Source.persistent"),t.add(jo.Calculated,"SystemCustomization.String.Source.calculated"),t.add(jo.Rollup,"SystemCustomization.String.Source.rollup"),t.add(jo.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Uh=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.parsePcfManifest=it.parseControlElement=it.parseManifestRoot=it.firstLevel=it.attr=it.elementChildren=it.manifestTypesForColumn=it.DEFAULT_TYPE_GROUPS=void 0;var yG=es(),H=(zo(),Fr(ZA)),we=(rs(),Fr(eS));it.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 bG="Phone";function vG(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===bG?[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}}it.manifestTypesForColumn=vG;function Mh(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}it.elementChildren=Mh;function En(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}it.attr=En;function jn(e,...t){return Mh(e).filter(r=>t.includes(r.tagName))}it.firstLevel=jn;function wG(e){let t=new Map;for(let r of jn(e,"type-group"))t.set(String(En(r,"name")),jn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function CG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(Mh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var EG={input:"input",bound:"bound",output:"output"};function AG(e,t,r){let n=En(e,"usage"),i=n!==null&&EG[n]||"input",o=En(e,"default-value"),a=jn(e,"value").map(m=>{let p={name:En(m,"name"),value:String(m.textContent),isDefault:En(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=En(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(it.DEFAULT_TYPE_GROUPS,s)?it.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=En(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:En(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:En(e,"required")==="true",hidden:En(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function tS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new yG.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}it.parseManifestRoot=tS;function rS(e){let t=jn(tS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}it.parseControlElement=rS;function SG(e){let t=rS(e),r=wG(t),n=jn(t,"data-set"),i=jn(t,"property"),o=jn(t,"groups"),a=[],s=!1;for(let u of i){let c=AG(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=>jn(u,"group").some(c=>jn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:CG(t)}}it.parsePcfManifest=SG});var iS=v(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.readPcfColumn=is.readControlManifest=void 0;var ns=se(),NG=Uh();function Bh(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 _G(e,t){var r;let n="/customcontrols"+(0,ns.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ns.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Bh(`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,NG.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}is.readControlManifest=_G;var TG=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 nS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function DG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ns.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ns.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ns.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:Bh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=nS(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=TG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ns.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Bh(`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=nS(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))}}}is.readPcfColumn=DG});var Ho=v(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.DEFAULT_LCID=void 0;ud.DEFAULT_LCID=1033});var dt=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.assignMissingIds=Hn.pointerTouchesValueMap=Hn.isValueMapKey=Hn.newId=void 0;var IG=$a();function oS(){return globalThis.crypto.randomUUID().toLowerCase()}Hn.newId=oS;function OG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Vh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function PG(e){return Vh.has(e)}Hn.isValueMapKey=PG;function RG(e){return IG.JsonPointer.parse(e).some(t=>Vh.has(t))}Hn.pointerTouchesValueMap=RG;function LG(e){return qh(e),e}Hn.assignMissingIds=LG;function qh(e){if(Array.isArray(e)){e.forEach(t=>qh(t));return}if(OG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=oS());for(let t of Object.keys(e))t==="id"||Vh.has(t)||qh(e[t])}}});var Wl=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.sendChangeSet=Er.partResponse=Er.postChangeSet=Er.parseChangeSetParts=Er.parseChangeSetStatuses=Er.renderChangeSet=void 0;var oo=Q(),Gh=ye(),aS=dt(),Gl=se();function Wh(e,t){let r=`batch_${(0,aS.newId)()}`,n=`changeset_${(0,aS.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 oo.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 oo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Gl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Gl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,Gl.assertNoControlChars)(m,"batch operation header name"),(0,Gl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new oo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Gl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([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}}Or.renderChangeSet=Ng;function eN(e,t){var r;return(r=_g(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Or.parseChangeSetStatuses=eN;function _g(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r+`),batchId:r,contentIds:i}}Er.renderChangeSet=Wh;function sS(e,t){var r;return(r=zh(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Er.parseChangeSetStatuses=sS;function zh(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}Or.parseChangeSetParts=_g;async function m9(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Sg.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=eN(a.body,o);if(l===void 0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new bo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Or.postChangeSet=m9;function tN(e){let t=e.text.replace(/\r\n/g,`+`);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}Er.parseChangeSetParts=zh;async function kG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Gh.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new oo.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=sS(a.body,o);if(l===void 0)throw new oo.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 oo.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 oo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Er.postChangeSet=kG;function lS(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}}Or.partResponse=tN;async function h9(e,t,r){let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=_g(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Sg.ensureSuccess)(tN(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Sg.ensureSuccess)(a,s),!l||l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Or.sendChangeSet=h9});var $d=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var Se=fe(),te=oe(),ri=sa(),he=Q(),g9=Es(),y9={String:"Microsoft.Dynamics.CRM.StringAttributeMetadata",Memo:"Microsoft.Dynamics.CRM.MemoAttributeMetadata",Integer:"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",Decimal:"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",Money:"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",Boolean:"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",DateTime:"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",Picklist:"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",Lookup:"Microsoft.Dynamics.CRM.LookupAttributeMetadata"};function tt(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:b9(e,t)}}var rN=65535;function b9(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new he.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new he.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>rN)throw new he.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${rN})`);if(i.has(s))throw new he.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new he.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function sN(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new he.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=sN;function fu(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var nN=["None","ApplicationRequired","Recommended"];function Ig(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function iN(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function pu(e){let t=(0,Se.readCreatedId)(e,"MetadataId");if(!t)throw new he.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function v9(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,L,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new he.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new he.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:tt((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:tt((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(O=t.dateFormat)!==null&&O!==void 0?O:"DateAndTime"};case"choice":return oN(t,r,!1);case"multiChoice":return oN(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((P=t.autoNumberFormat)===null||P===void 0)&&P.trim()))throw new he.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new he.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function oN(e,t,r){let i={"@odata.type":r?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:r?"Virtual":"Picklist",AttributeTypeName:{Value:r?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new he.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(o=>({Value:o.value,Label:tt(o.label,t)}))},i}var Tg=new WeakMap;async function w9(e,t){var r,n;let i=(r=Tg.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new he.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Tg.get(e);return l||(l=new Map,Tg.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=w9;async function C9(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!nN.includes(b))throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${nN.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let C=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,S=Ig(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:fu(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:tt((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&dN(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:tt(t.displayName,C),DisplayCollectionName:tt((a=t.pluralName)!==null&&a!==void 0?a:sN(t.displayName),C),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ur=>Og(ur,C))]};t.description&&(I.Description=tt(t.description,C));let D="/EntityDefinitions",P=(0,Se.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=pu(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Le=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),lr=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${O.toLowerCase()}', { required: '${b}' }).`:"",Ut;try{Ut=await lN(e,K,Le,lr)}catch(ur){throw w?(0,he.attachCause)(new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ur instanceof Error?ur.message:String(ur)}).${Ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),ur):ur}if(!Ut)throw new he.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Le} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${Ge}`);let de=Ut.body,Ke={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(Ke.primaryColumnRequired=await E9(e,t.schemaName,Ke,b,Le,lr)),Ke}ie.createTable=C9;async function lN(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,Se.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function E9(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await lN(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await hN(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,he.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function Og(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...v9(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:fu((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:tt(e.displayName,i)};return e.description&&(o.Description=tt(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),uN(o,e),o}function uN(e,t){t.isValidForCreate!==void 0&&(e.IsValidForCreate=t.isValidForCreate),t.isValidForUpdate!==void 0&&(e.IsValidForUpdate=t.isValidForUpdate),t.isValidForRead!==void 0&&(e.IsValidForRead=t.isValidForRead)}async function A9(e,t,r){var n;let i=Og(r,(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,Se.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:pu(a)};if(r.visualization&&r.visualization!=="None")try{await mN(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new he.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw(0,he.attachCause)(u,l),u}return s}ie.createColumn=A9;var As="/controlconfigurations",cN="CustomRenderersConfiguration",Dg={RadialDial:"c3d4e5f6-a7b8-9012-cdef-345678901234",LineChart:"a1b2c3d4-e5f6-7890-abcd-ef1234567890",HeatMap:"e7f8a9b0-c1d2-4e3f-5a6b-7c8d9e0f1a2b",StarRating:"b5e4c3d2-f1a0-4e2b-8a7c-9d3f5c1e6b04"};function dN(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new he.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${r.schemaName}') is not supported \u2014 the attribute metadata and its control-configuration row are separate writes. Create the column, then call setColumnVisualization; or use the single-column createColumn.`)}function fN(e){return JSON.stringify({type:Dg[e]})}function S9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Dg).find(i=>Dg[i]===r);return n??"None"}async function pN(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${As}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,Se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function N9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,Se.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new he.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function mN(e,t,r,n,i){let o={name:cN,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:fN(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.post(As,o),e.apiUrl(As))}async function _9(e,t,r){var n;let i=await pN(e,t,r);return S9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=_9;async function T9(e,t,r,n){let o=(await pN(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await N9(e,t,r);if(a){let u=`${As}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:cN,metadatajson:fN(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await mN(e,t,r,l,n);for(let u of s){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=T9;async function D9(e,t,r){if(r.length===0)return;if(dN(r,"createColumns"),!e.supportsAtomicBatch)throw new he.InvalidArgumentError(`createColumns writes ${r.length} columns on '${t}' as ONE atomic change set, which needs a verbatim request body. Implement HttpClient.postRaw, or call createColumn per column and accept that a failure can leave the table partly extended.`);let n=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`;await(0,g9.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Og(i,(o=i.languageCode)!==null&&o!==void 0?o:ri.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=D9;async function I9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,l=Ig(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,s),RequiredLevel:fu((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,Se.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=I9;async function O9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:tt(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,Se.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=O9;async function P9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new he.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Ig(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:fu((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:tt((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new he.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,Se.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:pu(d),lookupLogicalName:u}}ie.createRelationship=P9;async function R9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=R9;async function hN(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:ri.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,Se.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=y9[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new he.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,Se.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=tt(n.displayName,a)),n.description!==void 0&&(p.Description=tt(n.description,a)),n.required!==void 0&&(p.RequiredLevel=fu(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new he.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);if(n.integerFormat!==void 0&&c.AttributeType!=="Integer")throw new he.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),uN(p,n);let h=`${s}(${f})`;(0,Se.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=hN;async function L9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=L9;async function k9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new he.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=k9;async function aN(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,Se.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function $9(e,t){var r;let n=t.name.toLowerCase(),i=await aN(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:tt(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:tt(l.label,o)}))};t.description&&(a.Description=tt(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,Se.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:pu(l)}}catch(l){let u;try{u=await aN(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=$9;async function x9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=x9;async function F9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,Se.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:pu(s)}}ie.createAlternateKey=F9;async function M9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=M9;async function U9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new he.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.normalizeGuid)(l,"MetadataId");for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",r.displayName!==void 0&&(s.DisplayName=tt(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=tt(r.pluralName,i)),r.description!==void 0&&(s.Description=tt(r.description,i)),r.auditEnabled!==void 0&&iN(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&iN(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,Se.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=U9});var wo=v(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.rebuildRaw=Pr.assembleChildren=Pr.spliceChildren=Pr.mergeAttrs=Pr.rawFromNode=Pr.emptyBag=void 0;var vo=Q(),gN=1e6,Fd=512;function B9(){return{a:[],c:[]}}Pr.emptyBag=B9;function yN(e,t=0){if(t>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>yN(r,t+1))}}Pr.rawFromNode=yN;function q9(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Pr.mergeAttrs=q9;function xd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>gN)throw new vo.InvalidArgumentError(`Bag child index must be an integer in [0, ${gN}] (got ${String(l)})`);if(r.has(l))throw new vo.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Pr.spliceChildren=xd;function V9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:xd(e.w.c,t)};return xd(e.c,[r])}return xd(e.c,t)}Pr.assembleChildren=V9;function bN(e,t,r,n=0){if(n>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);G9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,bN(o,t,i,n+1));return i}Pr.rebuildRaw=bN;function G9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new vo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new vo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(r.a)||!Array.isArray(r.c))throw new vo.InvalidArgumentError(`Malformed hybrid node '${r.n}': 'a' and 'c' must be arrays`);for(let n of r.a)if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")throw new vo.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Co=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.installDomShim=void 0;var vN=ys(),wN=!1,W9={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};function z9(){if(wN)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=vN.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=vN.XMLSerializer),typeof e.Node>"u"&&(e.Node=W9),wN=!0}Md.installDomShim=z9});var Eo=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.projectElementBag=rt.serializeNode=rt.domEngine=rt.nodeLikeFromDom=rt.parseXmlRoot=rt.EMPTY_FORM_SENTINEL=rt.TEXT_SENTINEL=void 0;var j9=wo(),Ss=Q(),H9=Co();rt.TEXT_SENTINEL="#text";rt.EMPTY_FORM_SENTINEL="#empty";var Bd=new WeakSet;function K9(e,t){(0,H9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new Ss.InvalidArgumentError("XML source has no root element (empty or malformed input)");return J9(r),Q9(n),Z9(i),e5(i),n5(i,r),i}rt.parseXmlRoot=K9;function J9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw EN(3)}var Y9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function Q9(e){var t;for(let r of Y9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new Ss.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var X9=new Set([1,3]);function Z9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!X9.has(o.nodeType))throw new Ss.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function e5(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw EN(a.nodeType)}}function EN(e){return new Ss.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function t5(e){let t=[],r=/<([^>]*)>/g;for(let n=r.exec(e);n!==null;n=r.exec(e)){let i=n[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function r5(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function AN(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function n5(e,t){let r=t5(t),n=r5(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];AN(a)||Bd.add(a)}}function Pg(e){let t=e.nodeType===3;return{getNodeName:()=>t?rt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:rt.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return Bd.has(e)&&!AN(e)&&i.push({key:rt.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Pg(o))}return r}}}rt.nodeLikeFromDom=Pg;function i5(e){return{make:t=>t===rt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===rt.EMPTY_FORM_SENTINEL?Bd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}rt.domEngine=i5;function SN(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=31&&r!==9&&r!==10&&r!==13||r===65534||r===65535)throw Ud(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ud(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ud(r)}}function Ud(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Ss.InvalidArgumentError(`Value contains U+${t}, a character not permitted in XML 1.0 (control char / lone surrogate / non-character); it cannot be serialized losslessly`)}function o5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function a5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function s5(e){return NN(e,0)}rt.serializeNode=s5;var CN=512;function NN(e,t){var r;if(t>CN)throw new Ss.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${CN}`);if(e.nodeType===3)return a5((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+o5(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return Bd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=NN(l,t+1);return i+"</"+n.tagName+">"}function l5(e){let t=Pg(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,j9.rawFromNode)(r)}))}}rt.projectElementBag=l5});var cn=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.rejectUnknownKeys=Zt.childObjects=Zt.optionalGuidId=Zt.optionalEnum=Zt.eachObject=Zt.issue=Zt.isJsonObject=void 0;function _N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Zt.isJsonObject=_N;function Ns(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Zt.issue=Ns;function TN(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{_N(o)?i.push({node:o,index:a}):n.push(Ns(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Zt.eachObject=TN;function u5(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(Ns(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Zt.optionalEnum=u5;var c5=/^(?:\{[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}\}|[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})$/;function d5(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!c5.test(o)&&i.push(Ns(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Zt.optionalGuidId=d5;function f5(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?TN(o,a,n,i):(i.push(Ns(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Zt.childObjects=f5;function p5(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(Ns(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Zt.rejectUnknownKeys=p5});var zd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var m5=ys(),h5=Xa(),Rg=ct(),dn=cn();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var g5=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Rr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),g5.test(t)?t:""}B.normGuid=Rr;function Ao(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=Ao;function hu(e){return Ee(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=hu;function Ee(e){return Array.isArray(e)?e:[]}function Mg(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function ON(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function PN(e){return Pn(e).map(t=>t.cell)}B.typedCells=PN;function Pn(e){let t=[];return Ee(e?.tabs).forEach((r,n)=>{Ee(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ee(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ee(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ee(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Pn;function Bi(e){return Pe(e)?Rr(Mg(e.bag,"uniqueid")):""}B.controlUniqueId=Bi;function y5(e){let t=new Set;for(let{cell:r}of Pn(e)){let n=ca(r.control)?Bi(r.control):"";n&&t.add(n)}return t}function b5(e){let t=new Map;for(let{cell:r}of Pn(e)){let n=Pe(r.control)?Bi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function v5(e){return e!==void 0&&e.genPage===void 0&&(qg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Wd(e))}function Lg(e,t){if(Pe(e)){t(e);for(let r of Ee(e.c))Lg(r,t)}}function la(e,t){var r;if(Pe(e)){for(let n of Ee(e.c))Lg(n?.node,t);for(let n of Ee((r=e.w)===null||r===void 0?void 0:r.c))Lg(n?.node,t)}}function Vd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Rr(Ao(i,"uniqueid")))};return la(e?.bag,n),Ee(e?.tabs).forEach(i=>{Pe(i)&&(la(i.bag,n),Ee(i.columns).forEach(o=>{Pe(o)&&(la(o.bag,n),Ee(o.sections).forEach(a=>{Pe(a)&&(la(a.bag,n),Ee(a.rows).forEach(s=>{Pe(s)&&(la(s.bag,n),Ee(s.cells).forEach(l=>{Pe(l)&&(la(l.bag,n),Pe(l.control)&&(r(Bi(l.control)),la(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Vd;function _s(e){return Ee(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=_s;function ua(e,t){var r;let n=Rr(t);if(n)return Ee((r=_s(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Rr(Ao(i,"forControl"))===n)}B.descriptionFor=ua;function gu(e){return Ee(e.c).filter(RN)}B.pageEntries=gu;function RN(e){return e?.n==="customControl"&&Ao(e,"name")===B.GENPAGE_CONTROL_NAME}function kg(e,t){let r=Ee(e.c).find(n=>n?.n==="parameters");return Ee(r?.c).find(n=>n?.n===t)}B.entryParameter=kg;function $g(e){return Ao(e,"static")==="true"}B.isStaticParameter=$g;function yu(e){let t=gu(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=kg(t[i],"RefId");if(!o||!$g(o))return{kind:"unsupported"};let a=Rr(hu(o));if(!a)return{kind:"unsupported"};let s=kg(t[i],"PageInput");if(s&&!$g(s))return{kind:"unsupported"};let l=s?hu(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=yu;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ug(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=Ug;function Bg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Bg;function qg(e){return ON(e.classId!==void 0?e.classId:Mg(e.bag,"classid"))}B.effectiveClassId=qg;function Wd(e){return!e.fieldName}B.isUnbound=Wd;function Vg(e,t){if(Bg(e)!=="Main"||!Wd(t)||qg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Bi(t),n=r?ua(e.bag,r):void 0;return n!==void 0&&yu(n).kind==="projectable"}B.isRecognizedEmbed=Vg;function w5(e){for(let t of PN(e)){let r=t.control;if(!r||!Vg(e,r))continue;let n=yu(ua(e.bag,Bi(r)));if(n.kind!=="projectable")continue;let i=Ug(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=w5;var C5=new Set(["pageId","inputData"]);function mu(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function E5(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new m5.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=Rr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=mu(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?mu(l):[]){let d=Rr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of mu(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=mu(f).find(g=>g.nodeName==="parameters"),p=m?mu(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Rr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=E5;function qd(e){return{n:`<${e}`,a:[],c:[]}}function xg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[qd(t)]}}function Fg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function A5(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[xg("RefId",t),...r===void 0?[]:[xg("PageInput",Fg(r))]]}]}))}}function Gd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>Gd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&Gd(e[n],t[n]))}return e===t}function S5(e,t,r){let n=Ee(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Rr(hu(i))!==t&&(i.c=[qd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?hu(a):void 0;if(Gd(Ug(s),r))return;if(r!==void 0){a?a.c=[qd(Fg(r,s))]:n.c.push(xg("PageInput",Fg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[qd(JSON.stringify(l))]}function Gg(e){let t=Ee(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=Gg;function N5(e,t){var r;let n=e.bag,i=_s(n);if(i&&t){let o=Vd(t),a=Vd(e),s=y5(t),l=b5(e),u=Ee(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&gu(d).length>0?Rr(Ao(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&v5(l.get(f))&&Gd(d,ua(t.bag,f))){let m=Ee(d.c).filter(p=>!RN(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of Pn(e)){let a=o.control;if(!ca(a)||!Pe(a.genPage))continue;let s=Rr(a.genPage.pageId),l=a.genPage.inputData,u=Bi(a);if(!u){if(bu(a)!==void 0)continue;u=Wg(a)}let c=ua(n,u);if(c){for(let m of gu(c))S5(m,s,l);continue}i||(i={i:Gg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Mg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(A5(f,s,l))}}B.reconcileEmbedDescriptions=N5;function _5(e,t){let r=_s(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Pn(e).some(({cell:a})=>ca(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=_s(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ee(o.bag.c),o.bag.c.push({i:Gg(e.bag),node:a}))}for(let{cell:a}of Pn(o))ca(a.control)&&(LN(a.control),kN(a));return o}B.commitEmbedState=_5;function T5(e){if(Pn(e).some(({cell:r})=>ca(r.control)))return!0;let t=_s(e.bag);return Ee(t?.node.c).some(r=>r?.n==="controlDescription"&&gu(r).length>0)}B.mayCommitEmbedState=T5;function LN(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=LN;function kN(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=kN;function ca(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=ca;function DN(e){return ca(e.control)&&(!e.control.id||!e.id||bu(e.control)===void 0)}function bu(e){let t=Ee(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=bu;function D5(e){if(!Pn(e).some(({cell:r})=>DN(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Pn(t)){if(!DN(r))continue;let n=r.control;n.id||(n.id=(0,Rg.newId)()),r.id||(r.id=(0,Rg.newId)()),bu(n)===void 0&&Wg(n)}return t}B.mintEmbedIdentity=D5;function Wg(e){let t=(0,Rg.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ee(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ee(e.bag.c),t}B.setUniqueId=Wg;function IN(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function I5(e){let t=Ee(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=Ao(r,"name"))!==null&&n!==void 0?n:Ao(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function O5(e){let t=[],r;for(let{cell:n,pointer:i}of Pn(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){P5(e,o,a,t);continue}r=r??Vd(e),R5(e,o,a,r,t)}return t}B.genPageEmbedIssues=O5;function P5(e,t,r,n){if(!Vg(e,t))return;let i=yu(ua(e.bag,Bi(t)));n.push((0,dn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function R5(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,dn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${IN(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Rr(s.pageId))&&i.push((0,dn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,dn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${IN(s.inputData)}`));for(let m of Object.keys(s))C5.has(m)||i.push((0,dn.issue)(h5.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Wd(t)||i.push((0,dn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&ON(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,dn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Bg(e);l!=="Main"&&i.push((0,dn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=bu(t);u!==void 0&&!Rr(u)&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Bi(t);if(!c)return;let d=ua(e.bag,c),f=d?yu(d):void 0;d&&f?.kind==="none"?i.push((0,dn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${I5(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,dn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var jg=v(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.findMissingGenPages=So.GENPAGE_LOOKUP_CHUNK=void 0;var L5=Tt(),zg=oe();So.GENPAGE_LOOKUP_CHUNK=50;async function k5(e,t,r){let n=[...new Set(t.map(o=>(0,zg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=So.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+So.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,zg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,L5.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,zg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}So.findMissingGenPages=k5});var vu=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertSystemFormKind=Pt.readSystemFormType=Pt.decodeCode=Pt.assertSystemFormRecordKind=Pt.describeSystemFormType=Pt.systemFormKindOf=Pt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var xN=Q(),$5=fe(),$N=oe();Pt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var x5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},F5={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function jd(e){return Number.isInteger(e)?x5[e]:void 0}Pt.systemFormKindOf=jd;function FN(e){var t;return Number.isFinite(e)?`a ${(t=F5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Pt.describeSystemFormType=FN;function MN(e,t,r,n){let i=FN(r),o=jd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function M5(e,t,r,n){let i=Hg(e?.type);if(jd(i)!==r)throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,i,n));return i}Pt.assertSystemFormRecordKind=M5;function Hg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Pt.decodeCode=Hg;async function U5(e,t){return await UN(e,t,!1)}Pt.readSystemFormType=U5;async function B5(e,t){return UN(e,t,!0)}async function UN(e,t,r){var n;let o=`/systemforms(${(0,$N.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$N.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,$5.ensureSuccess)(a,e.apiUrl(o)),Hg((n=a.body)===null||n===void 0?void 0:n.type)}async function q5(e,t,r){let n=await B5(e,t);if(!(n===void 0||jd(n)===r))throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,n,"delete"))}Pt.assertSystemFormKind=q5});var Jg=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.patchSystemForm=Yr.assertSystemFormContentUnchanged=Yr.readSystemFormRowEtag=Yr.unpublishedSystemFormPath=Yr.FORM_TYPE_IMMUTABLE_CODE=void 0;var fn=fe(),V5=oe(),Hd=Q(),No=vu();Yr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function Kg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,V5.odataQuery)([["$select",t]])}Yr.unpublishedSystemFormPath=Kg;function BN(e,t){return(0,fn.readRowEtag)(e,"systemforms","formid",t)}Yr.readSystemFormRowEtag=BN;async function qN(e,t,r,n,i){(0,fn.requireEtag)(i,r,t);let o=(0,fn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,No.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,fn.readEtag)(o);if(s===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Yr.assertSystemFormContentUnchanged=qN;async function G5(e,t,r,n,i,o){(0,fn.requireEtag)(i,r,t);let a=await BN(e,t);if(a===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await qN(e,t,r,Kg(t,"formid,type"),i);if(n.type!==void 0&&(0,No.decodeCode)(n.type)!==s)throw new Hd.SdkError(Yr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,No.describeSystemFormType)(s)} to ${(0,No.describeSystemFormType)((0,No.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,fn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,fn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),W5(e,t,r,o)}Yr.patchSystemForm=G5;async function W5(e,t,r,n){let i;try{let o=Kg(t,n.select),a=(0,fn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,fn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,No.decodeCode)(s?.type),m=(0,No.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,No.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var e0=v(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.getFormSecurityRoles=qt.setFormSecurityRoles=qt.formApi=qt.readPrimaryCreateRefusal=qt.FORM_GENPAGE_TARGET_UNVERIFIABLE=qt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var z5=Tt(),Rt=fe(),pn=oe(),da=Q(),Yg=Eo(),GN=zd(),j5=jg(),Qg=Jg(),wu=vu();qt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";qt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var WN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",H5={select:WN,required:["name","type","objecttypecode"]},K5="formid,name,type,objecttypecode",J5=2,Y5={Main:J5,QuickView:6,QuickCreate:7,Card:11},zN=new WeakMap;function Q5(e){return typeof e=="object"&&e!==null?zN.get(e):void 0}qt.readPrimaryCreateRefusal=Q5;qt.formApi={async get(e,t){let r=(0,pn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select",WN]]),i=(0,Rt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,wu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Rt.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>Y5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,pn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,pn.odataQuery)([["$select",K5],["$filter",a.join(" and ")]])}`;return(await(0,z5.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=VN(t);n!==void 0&&await jN(e,Zg(n,"payload"),[]);let i=(0,Rt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Rt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Rt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Rt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&zN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Rt.resolveCreatedId)(l,"formid","form",r),etag:(0,Rt.readEtag)(l)}},async update(e,t,r,n){let i=(0,pn.normalizeGuid)(t,"id"),o=VN(r);return o!==void 0&&await Z5(e,i,o,n),(0,Qg.patchSystemForm)(e,i,"form",r,n,H5)},readContentThenToken(e,t){return qt.formApi.get(e,t)},async delete(e,t){let r=(0,pn.normalizeGuid)(t,"id");return await(0,wu.assertSystemFormKind)(e,r,"form"),(0,Rt.deleteRecord)(e,"systemforms",r)}};var Xg="DisplayConditions";async function X5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new da.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,pn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Rt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,wu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Rt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new da.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Yg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new da.InvalidArgumentError(`form '${s}' produced no owner document`);let h=HN(m,Xg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new da.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(Xg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",P),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,pn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Yg.serializeNode)(m);await(0,Qg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Qg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,Rt.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Rt.requireEtag)(O,"form",s)}}),e.apiUrl(L))}qt.setFormSecurityRoles=X5;function VN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(GN.GENPAGE_CONTROL_NAME)?t:void 0}function Zg(e,t){try{return(0,GN.activeEmbedBindings)(e)}catch(r){throw new da.SdkError(qt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function jN(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,j5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new da.SdkError(qt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function Z5(e,t,r,n){var i;(0,Rt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Rt.readEtag)(a);if(s===null||s!==n)throw new da.SdkError(Rt.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?Zg(l,"server"):[];await jN(e,Zg(r,"payload"),u)}function HN(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName===t)return i}}async function eW(e,t){var r,n;let i=(0,pn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Yg.parseXmlRoot)(s,"<form/>"),u=HN(l,Xg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.replace(/[{}]/g,"").toLowerCase())}}let m=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...m!==null&&m!==""?{order:Number(m)}:{}}}qt.getFormSecurityRoles=eW});var Jd=v(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.deleteSolution=ye.getDeploymentSettingsTemplate=ye.importSolution=ye.exportSolution=ye.removeSolutionComponent=ye.addSolutionComponent=ye.setSolutionVersion=ye.createSolution=ye.createPublisher=ye.getSolution=ye.fetchSolutionComponents=ye.resolveGenPageComponentType=ye.SolutionComponentType=void 0;var tW=Tt(),Gt=fe(),mr=oe(),rW=ct(),er=Q();ye.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var nW=[ye.SolutionComponentType.SavedQuery,ye.SolutionComponentType.Workflow,ye.SolutionComponentType.SavedQueryVisualization,ye.SolutionComponentType.SystemForm,ye.SolutionComponentType.AppModule],KN="uxagentproject",JN=new WeakMap;async function t_(e){var t;let r=JN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${KN}')${(0,mr.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Gt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new er.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${KN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return JN.set(e,o),o}ye.resolveGenPageComponentType=t_;var YN=1,QN=0;async function iW(e,t){let r=(0,mr.normalizeGuid)(t,"solutionId"),n=await t_(e),o=[YN,...nW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,mr.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,tW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===YN){let f=c.rootcomponentbehavior;(f===QN||f===String(QN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}ye.fetchSolutionComponents=iW;function oW(e){let t=e.length===38&&e.startsWith("{")&&e.endsWith("}")?e.slice(1,-1):e;return/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(t)}async function aW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new er.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=oW(f)?`solutionid eq ${(0,mr.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,mr.odataLiteral)(f)}'`,p=`/solutions${(0,mr.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Gt.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new er.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new er.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new er.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,mr.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,mr.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}ye.getSolution=aW;async function sW(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,Gt.ensureSuccess)(await(0,Gt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Gt.readCreatedId)(i,"publisherid");if(!o)throw new er.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}ye.createPublisher=sW;async function lW(e,t){var r;let n=(0,mr.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let o=(0,Gt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Gt.readCreatedId)(o,"solutionid");if(!a)throw new er.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}ye.createSolution=lW;async function uW(e,t,r){let i=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}ye.setSolutionVersion=uW;async function cW(e,t){var r;let i={ComponentId:(0,mr.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(r=t.addRequiredComponents)!==null&&r!==void 0?r:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,Gt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}ye.addSolutionComponent=cW;async function dW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,mr.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Gt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}ye.removeSolutionComponent=dW;async function fW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Gt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new er.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}ye.exportSolution=fW;async function pW(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new er.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:SW(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,mr.normalizeGuid)(t.importJobId,"importJobId"):(0,rW.newId)()};if(!n)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await r_(e,t.base64,Cu,o),{parameters:s,applied:l}=NW(a,n);return i.ComponentParameters=s,(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,er.withCleanupWarnings)(a,o)}}ye.importSolution=pW;var Cu="importSolution",XN="getDeploymentSettingsTemplate";async function mW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new er.InvalidArgumentError(`${XN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await r_(e,n,XN,i),a=Kd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Kd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,er.withCleanupWarnings)(o,i)}}ye.getDeploymentSettingsTemplate=mW;function Kd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function r_(e,t,r,n){var i;let a=(i=(0,Gt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return gW(a,r)}finally{await hW(e,fa(a)?a.StageSolutionUploadId:void 0,n)}}async function hW(e,t,r){let n;try{n=(0,mr.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${Vt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Gt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function pr(e,t){return new er.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===Cu?" Nothing was imported.":""}`)}function ZN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>fa(r)&&typeof r.Message=="string"?r.Message:Vt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function gW(e,t){if(!fa(e))throw pr(t,`it holds no StageSolutionResults (${Vt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new er.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${Vt(r)}). Missing dependencies: ${ZN(e.MissingDependencies)}. Validation: ${ZN(e.SolutionValidationResults)}.${t===Cu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw pr(t,`StageSolutionStatus is ${Vt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw pr(t,`SolutionComponentsDetails is not a list (${Vt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!fa(l))throw pr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw pr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=yW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw pr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw pr(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw pr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=bW(f.get("type"),`${c}.type`,t),b=vW(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw pr(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function yW(e,t,r){if(!fa(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw pr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw pr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw pr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw pr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function bW(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw pr(r,`${t} is not a whole number (${Vt(e,40)})`)}}function vW(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw pr(r,`${t} is not true or false (${Vt(e,40)})`)}}var wW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),CW=["Workflows","CanvasApps","CopilotAgents"],EW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),AW=new Set(["LogicalName","ConnectionId","ConnectorId"]);function fr(e,t){return new er.InvalidArgumentError(`${Cu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function SW(e){let t="deploymentSettings";if(!fa(e))throw fr(t,`must be an object \u2014 the settings file, parsed (it was ${Vt(e,40)})`);for(let l of Object.keys(e))if(!wW.has(l))throw fr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of CW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw fr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw fr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw fr(`${t}.${l}`,`must be a list (it was ${Vt(u,40)})`);return u.map((c,d)=>{if(!fa(c))throw fr(`${t}.${l}[${d}]`,`must be an object (it was ${Vt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw fr(c,`must be a non-empty string (it was ${Vt(d,40)})`);if(d.trim()!==d)throw fr(c,`must not begin or end with whitespace (it was ${Vt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw fr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!EW.has(f))throw fr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw fr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${Vt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!AW.has(m))throw fr(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw fr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${Vt(f,40)})`);if(f.trim()!==f)throw fr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${Vt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw fr(`${c}.ConnectorId`,`must be a string (it was ${Vt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function e_(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function NW(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=e_(Kd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=e_(Kd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new er.InvalidArgumentError(`${Cu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function _W(e,t){let n=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ye.deleteSolution=_W});var l_=v(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.recoverFormCreate=yt.solutionMembershipProblem=yt.formWriteMismatches=yt.validateExistingForm=yt.formExistsAtId=yt.isFormRecordAt=yt.MAIN_FORM_TYPE=void 0;var Ts=oe(),n_=Tt(),i_=Jd();yt.MAIN_FORM_TYPE=2;function Yd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qd(e){return e instanceof Error?e.message:String(e)}function t0(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,Ts.normalizeGuid)(e,"a GUID")===(0,Ts.normalizeGuid)(t,"a GUID")}catch{return!1}}function r0(e,t){return Yd(e)&&t0(e.formid,t)}yt.isFormRecordAt=r0;async function TW(e,t){try{return r0((await e()).raw,t)}catch{return!1}}yt.formExistsAtId=TW;function o_(e,t){let r=e.raw;if(!Yd(r))return{problem:"it is not a record"};if(!r0(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==yt.MAIN_FORM_TYPE)return{problem:`its type is not ${yt.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}yt.validateExistingForm=o_;function a_(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}yt.formWriteMismatches=a_;async function s_(e,t){let r=e.solutionName;if(r)try{let n=await(0,n_.collectPages)(e,`/solutions${(0,Ts.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,Ts.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Yd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,Ts.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,n_.collectPages)(e,`/solutioncomponents${(0,Ts.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${i_.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Yd(l)&&l.componenttype===i_.SolutionComponentType.SystemForm&&t0(l.objectid,t)&&t0(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Qd(n)})`}}yt.solutionMembershipProblem=s_;async function DW(e){try{return await IW(e)}catch(t){return{refused:`the recovery could not be completed (${Qd(t)})`}}}yt.recoverFormCreate=DW;async function IW(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==yt.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Qd(f)})`}}let l=o_(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=a_(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Qd(f)})`}}let d=await s_(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Zd=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.disassociateRecords=Ye.associateRecords=Ye.createRecordsBulk=Ye.upsertRecord=Ye.queryAllRecords=Ye.queryRecords=Ye.getRecord=Ye.deleteRecord=Ye.updateRecord=Ye.createRecord=void 0;var n0=Tt(),Rn=fe(),tr=oe(),Ds=Q(),ni=$d();function Xd(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function OW(e,t,r){let i=`/${await(0,ni.resolveEntitySetName)(e,t)}`,o=(0,Rn.ensureSuccess)(await e.post(i,Xd(r)),e.apiUrl(i)),a=(0,Rn.readCreatedId)(o,`${t}id`);if(!a)throw new Ds.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ye.createRecord=OW;async function PW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),a=`/${await(0,ni.resolveEntitySetName)(e,t)}(${i})`;(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a))}Ye.updateRecord=PW;async function RW(e,t,r){let n=(0,tr.normalizeGuid)(r,"id"),o=`/${await(0,ni.resolveEntitySetName)(e,t)}(${n})`;(0,Rn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ye.deleteRecord=RW;async function LW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=await(0,ni.resolveEntitySetName)(e,t),a=(0,tr.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Rn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new Ds.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,n0.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ye.getRecord=LW;function kW(e){return e?.fetchXml?(0,tr.odataQuery)([["fetchXml",e.fetchXml]]):(0,tr.odataQuery)([["$select",e?.select&&e.select.length>0?e.select.join(","):void 0],["$filter",e?.filter],["$orderby",e?.orderBy],["$expand",e?.expand],["$top",e?.top]])}async function u_(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new Ds.InvalidArgumentError("queryRecords: `paginate` cannot be combined with `top` \u2014 Dataverse honors $top as a hard cap and omits @odata.nextLink, so the result would be silently capped at one page.");if(r.fetchXml)throw new Ds.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let o=`/${await(0,ni.resolveEntitySetName)(e,t)}${kW(r)}`;if(r?.paginate)return(0,n0.collectPages)(e,o,"queryRecords");let a=(0,Rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ds.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,n0.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ye.queryRecords=u_;async function $W(e,t,r){return u_(e,t,{...r,paginate:!0})}Ye.queryAllRecords=$W;function xW(e){if("id"in e)return`(${(0,tr.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,tr.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,tr.assertODataName)(e.key,"alternate key name")}=${t})`}async function FW(e,t,r,n){let i=xW(r),a=`/${await(0,ni.resolveEntitySetName)(e,t)}${i}`,s=(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a)),l=s.status===201,u=(0,Rn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,tr.normalizeGuid)(r.id,"id"):""),created:l}}Ye.upsertRecord=FW;async function MW(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,ni.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Xd(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Rn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new Ds.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ye.createRecordsBulk=MW;async function UW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=(0,tr.normalizeGuid)(n.targetId,"targetId"),a=await(0,ni.resolveEntitySetName)(e,t),s=await(0,ni.resolveEntitySetName)(e,n.targetEntity),l=(0,tr.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Rn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ye.associateRecords=UW;async function BW(e,t,r,n,i){let o=(0,tr.normalizeGuid)(r,"id"),a=(0,tr.normalizeGuid)(i,"targetId"),s=await(0,ni.resolveEntitySetName)(e,t),l=(0,tr.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Rn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ye.disassociateRecords=BW});var pa=v(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.base64ToUtf8=mn.base64ToBytes=mn.bytesToBase64=mn.utf8ToBase64=mn.utf8ToBytes=void 0;var i0=32768,Lr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Eu(){return globalThis}function c_(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function qW(e){let t="";for(let r=0;r<e.length;r+=i0)t+=String.fromCharCode(...e.subarray(r,r+i0));return t}function VW(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Lr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function GW(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Lr[i>>18&63]+Lr[i>>12&63]+Lr[i>>6&63]+Lr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Lr[i>>18&63]}${Lr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Lr[i>>18&63],a=Lr[i>>12&63],s=Lr[i>>6&63];t+=`${o}${a}${s}=`}return t}function WW(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Lr.indexOf(e[o])<<18|Lr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Lr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Lr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function zW(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):c_(e)}mn.utf8ToBytes=zW;function jW(e){let t=Eu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return d_(r?new r().encode(e):c_(e))}mn.utf8ToBase64=jW;function d_(e){let t=Eu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(qW(e)):GW(e)}mn.bytesToBase64=d_;function f_(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=VW(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return WW(r)}mn.base64ToBytes=f_;function HW(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=i0&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function KW(e){let t=Eu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):HW(f_(e))}mn.base64ToUtf8=KW});var g_=v(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.deleteWebResource=ii.getWebResource=ii.updateWebResource=ii.createWebResource=void 0;var JW=jr(),Au=fe(),ef=oe(),YW=pa(),p_=Q(),QW={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function m_(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,YW.utf8ToBase64)(e.content)}async function h_(e,t){return(0,JW.publishWebResourceById)(e,t)}async function XW(e,t){var r;let n=m_(t);if(n===void 0)throw new p_.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(r=t.displayName)!==null&&r!==void 0?r:t.name,webresourcetype:QW[t.type],content:n};t.description&&(i.description=t.description);let o=(0,Au.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,Au.readCreatedId)(o,"webresourceid");if(!a)throw new p_.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await h_(e,a),{id:a,name:t.name}}ii.createWebResource=XW;async function ZW(e,t,r){let n=(0,ef.normalizeGuid)(t,"id"),i={},o=m_(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,Au.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await h_(e,n)}ii.updateWebResource=ZW;async function e6(e,t){var r;let i=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})${(0,ef.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,Au.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}ii.getWebResource=e6;async function t6(e,t){let n=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})`;(0,Au.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ii.deleteWebResource=t6});var tf=v(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.applyAppSettings=Lt.setAppSetting=Lt.readAppSettings=Lt.resolveSettingDefinitions=Lt.APP_SETTING_UNSET=Lt.APP_SETTING_OFF=Lt.APP_SETTING_ON=Lt.HEADER_AND_NAVIGATION_REFRESH=void 0;var Is=fe(),qi=oe();Lt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Lt.APP_SETTING_ON="2";Lt.APP_SETTING_OFF="1";Lt.APP_SETTING_UNSET="0";function v_(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,qi.odataQuery)([["$select",e],["$filter",t]])}async function w_(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,qi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,Is.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}Lt.resolveSettingDefinitions=w_;async function r6(e,t){var r,n,i,o;let a=(0,qi.normalizeGuid)(t,"App id"),s=v_("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,Is.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,qi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,Is.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Lt.readAppSettings=r6;async function y_(e,t,r){var n,i,o;let a=v_("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Is.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function C_(e,t,r,n){let i=(0,qi.normalizeGuid)(t,"App id"),a=(await w_(e,[r])).get(r),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,qi.normalizeGuid)(s,"Setting definition id"),u=await y_(e,i,l);if(u)return b_(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await y_(e,i,l)}catch{p=void 0}if(p)return b_(e,p,n);throw f&&(0,Is.ensureSuccess)(f,e.apiUrl(c)),m}Lt.setAppSetting=C_;async function b_(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,qi.normalizeGuid)(t.id,"App setting id")})`;return(0,Is.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function n6(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await C_(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Lt.applyAppSettings=n6});var nf=v(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.HEADER_NAV_BOOLEAN_RULE=void 0;rf.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var o0=v(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});af.asUint8Array=void 0;var i6=Object.getPrototypeOf(Uint8Array.prototype);function of(e){let t=Object.getOwnPropertyDescriptor(i6,e);if(!t?.get)throw new Error(`this JavaScript engine has no %TypedArray%.prototype getter for ${String(e)}`);return t.get}var o6=of(Symbol.toStringTag),a6=of("buffer"),s6=of("byteOffset"),l6=of("byteLength");function u6(e){if(o6.call(e)==="Uint8Array")return new Uint8Array(a6.call(e),s6.call(e),l6.call(e))}af.asUint8Array=u6});var I_=v(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.zipStored=Os.crc32=void 0;var c6=Q(),d6=pa(),f6=o0(),p6=67324752,m6=33639248,h6=101010256,sf=30,a0=46,g6=22,E_=10,y6=20,A_=2048,S_=0,N_=0,__=33,b6=65535,v6=65535,T_=4294967295,w6=3988292384,lf;function C6(){if(!lf){lf=new Uint32Array(256);for(let e=0;e<256;e+=1){let t=e;for(let r=0;r<8;r+=1)t=t&1?w6^t>>>1:t>>>1;lf[e]=t}}return lf}function D_(e){let t=C6(),r=4294967295;for(let n=0;n<e.length;n+=1)r=t[(r^e[n])&255]^r>>>8;return(r^4294967295)>>>0}Os.crc32=D_;function oi(e){return new c6.InvalidArgumentError(`zip: ${e}`)}function E6(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!1;t+=1}else if(r>=56320&&r<=57343)return!1}return!0}function A6(e){if(typeof e!="string"||e.length===0)throw oi("every entry needs a non-empty name.");if(e.includes("\\"))throw oi(`'${e}' contains a backslash; ZIP paths use '/'.`);if(/^[A-Za-z]:/.test(e))throw oi(`'${e}' starts with a drive letter; ZIP paths are relative.`);if(e.split("/").some(t=>t===""||t==="."||t===".."))throw oi(`'${e}' is not a relative path of named segments (no leading, trailing or doubled '/', no '.' or '..').`);if(!E6(e))throw oi(`'${e}' contains an unpaired surrogate, which has no UTF-8 form.`);return e}function S6(e,t=T_){if(e.length>b6)throw oi(`${e.length} entries is more than the 65,535 a ZIP can count without ZIP64.`);let r=Math.min(t,T_),n=new Set,i=[],o=g6;for(let f of e){let m=A6(f.name);if(n.has(m))throw oi(`'${m}' appears twice.`);n.add(m);let p=(0,f6.asUint8Array)(f.data);if(!p)throw oi(`the data for '${m}' must be a Uint8Array.`);let h=(0,d6.utf8ToBytes)(m);if(h.length>v6)throw oi(`a name of ${h.length} UTF-8 bytes is more than the 65,535 a header can record.`);o+=sf+a0+2*h.length+p.byteLength,i.push({nameBytes:h,data:p})}if(o>r)throw oi(`the archive would be ${o} bytes, more than the ${r} allowed.`);let a=new Uint8Array(o),s=new DataView(a.buffer),l=[],u=[],c=0;for(let{nameBytes:f,data:m}of i){let p=D_(m);l.push(c),u.push(p),s.setUint32(c,p6,!0),s.setUint16(c+4,E_,!0),s.setUint16(c+6,A_,!0),s.setUint16(c+8,S_,!0),s.setUint16(c+10,N_,!0),s.setUint16(c+12,__,!0),s.setUint32(c+14,p,!0),s.setUint32(c+18,m.byteLength,!0),s.setUint32(c+22,m.byteLength,!0),s.setUint16(c+26,f.length,!0),a.set(f,c+sf),a.set(m,c+sf+f.length),c+=sf+f.length+m.byteLength}let d=c;return i.forEach(({nameBytes:f,data:m},p)=>{s.setUint32(c,m6,!0),s.setUint16(c+4,y6,!0),s.setUint16(c+6,E_,!0),s.setUint16(c+8,A_,!0),s.setUint16(c+10,S_,!0),s.setUint16(c+12,N_,!0),s.setUint16(c+14,__,!0),s.setUint32(c+16,u[p],!0),s.setUint32(c+20,m.byteLength,!0),s.setUint32(c+24,m.byteLength,!0),s.setUint16(c+28,f.length,!0),s.setUint32(c+42,l[p],!0),a.set(f,c+a0),c+=a0+f.length}),s.setUint32(c,h6,!0),s.setUint16(c+8,i.length,!0),s.setUint16(c+10,i.length,!0),s.setUint32(c+12,c-d,!0),s.setUint32(c+16,d,!0),a}Os.zipStored=S6});var W_=v($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.pcfManifestsEquivalent=$e.buildPcfSolutionZip=$e.pcfContentTypesXml=$e.pcfCustomizationsXml=$e.pcfSolutionXml=$e.pcfWebResourceName=$e.pcfControlName=$e.checkPcfControlPackage=$e.unboundPrefixes=$e.PCF_WEB_RESOURCE_TYPES=void 0;var N6=Q(),Qr=cu(),uf=pa(),_6=o0(),T6=I_();$e.PCF_WEB_RESOURCE_TYPES={html:1,htm:1,css:2,js:3,xml:4,png:5,jpg:6,jpeg:6,gif:7,xsl:9,xslt:9,ico:10,svg:11,resx:12};var D6=["code","css","resx","img","html"],O_=/^[A-Za-z_][A-Za-z0-9_]*$/,I6=/^\d+\.\d+\.\d+$/,O6=/^[A-Za-z0-9_.-]+$/;function bt(e){return new N6.InvalidArgumentError(`registerPcfControl: ${e}`)}function x_(e){return(0,Qr.elementChildren)(e).filter(t=>t.localName==="control"&&!t.namespaceURI)}function F_(e){let t=[],r=n=>{n.prefix&&!n.namespaceURI&&t.push(`<${n.tagName}>`);for(let i=0;i<n.attributes.length;i+=1){let o=n.attributes.item(i);o.prefix&&!o.namespaceURI&&t.push(`${o.name}="\u2026" on <${n.tagName}>`)}(0,Qr.elementChildren)(n).forEach(r)};return r(e),t}$e.unboundPrefixes=F_;function s0(e){let t=(0,Qr.parseManifestRoot)(e),r=F_(t);if(r.length>0)throw new Error(`the manifest uses a prefix no namespace declaration binds: ${r.join(", ")}.`);if(t.localName!=="manifest")throw new Error(`the manifest's root element is <${t.tagName}>, not <manifest>.`);if(t.namespaceURI)throw new Error(`the manifest's root element is <manifest> in the namespace '${t.namespaceURI}', not in no namespace.`);let n=x_(t)[0];if(!n)throw new Error("the control manifest has no <control> element");return{root:t,control:n}}function P6(e){let t=e.split("/");if(!t.every(a=>O6.test(a)&&a!=="."&&a!==".."))throw bt(`the resource path '${e}' is not a web resource name: use letters, digits, '_', '.' and '-' in '/'-separated segments, with no '.' or '..' segment.`);let r=t[t.length-1],n=r.lastIndexOf("."),i=n>0?r.slice(n+1).toLowerCase():"",o=Object.prototype.hasOwnProperty.call($e.PCF_WEB_RESOURCE_TYPES,i)?$e.PCF_WEB_RESOURCE_TYPES[i]:void 0;if(o===void 0)throw bt(`the resource path '${e}' has no web resource type; the extensions are ${Object.keys($e.PCF_WEB_RESOURCE_TYPES).join(", ")}.`);return o}function R6(e){var t,r,n;if(typeof e!="object"||e===null)throw bt("the control package must be an object with a manifest and files.");let{manifest:i,files:o}=e;if(typeof i!="string"||i.length===0)throw bt("the manifest must be the built ControlManifest.xml, as a string.");if(typeof o!="object"||o===null||Array.isArray(o))throw bt("files must be an object mapping each resource path to its bytes.");let a,s;try{({root:a,control:s}=s0(i))}catch(b){throw bt(b.message)}if(x_(a).length!==1)throw bt("the manifest must hold exactly one <control>.");let l=(t=(0,Qr.attr)(s,"namespace"))!==null&&t!==void 0?t:"",u=(r=(0,Qr.attr)(s,"constructor"))!==null&&r!==void 0?r:"",c=(n=(0,Qr.attr)(s,"version"))!==null&&n!==void 0?n:"";if(!l.split(".").every(b=>O_.test(b)))throw bt(`the control's namespace '${l}' is not a dotted identifier.`);if(!O_.test(u))throw bt(`the control's constructor '${u}' is not an identifier.`);if(!I6.test(c))throw bt(`the control's version '${c}' is not major.minor.patch.`);let d=(0,Qr.firstLevel)(s,"resources");if(d.length!==1)throw bt("the manifest must hold exactly one <resources> element.");let f=[],m=0;for(let b of(0,Qr.elementChildren)(d[0])){let w=(0,Qr.attr)(b,"path");if(!D6.includes(b.tagName)){if(w!==null)throw bt(`<${b.tagName} path="${w}"> is not a resource kind the SDK registers.`);continue}if(!w)throw bt(`a <${b.tagName}> resource has no path.`);m+=b.tagName==="code"?1:0,f.push(w)}if(m!==1)throw bt(`the manifest must name exactly one <code> resource; it names ${m}.`);let p=new Map,h=[];for(let b of f){let w=P6(b),C=b.toLowerCase();if(C==="controlmanifest.xml")throw bt(`the resource path '${b}' is where the package puts the manifest itself.`);let S=p.get(C);if(S!==void 0)throw bt(`the manifest names '${b}' and '${S}', which are the same web resource.`);if(p.set(C,b),!Object.prototype.hasOwnProperty.call(o,b))throw bt(`the manifest names '${b}', but files has no such key.`);let O=(0,_6.asUint8Array)(o[b]);if(!O)throw bt(`files['${b}'] must be a Uint8Array.`);h.push({path:b,data:O,webResourceType:w})}let g=Object.keys(o).filter(b=>!f.includes(b));if(g.length>0)throw bt(`files holds ${g.map(b=>`'${b}'`).join(", ")}, which the manifest does not name.`);return{namespace:l,constructorName:u,version:c,manifest:i,files:h}}$e.checkPcfControlPackage=R6;function L6(e,t){return`${e}_${t.namespace}.${t.constructorName}`}$e.pcfControlName=L6;function k6(e,t){return`cc_${e.namespace}.${e.constructorName}/${t}`}$e.pcfWebResourceName=k6;function Ps(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var $6=["City","County","Country","Fax","FreightTermsCode","ImportSequenceNumber","Latitude","Line1","Line2","Line3","Longitude","Name","PostalCode","PostOfficeBox","PrimaryContactName"],x6=["StateOrProvince","Telephone1","Telephone2","Telephone3","TimeZoneRuleVersionNumber","UPSZone","UTCOffset","UTCConversionTimeZoneCode"];function P_(e){let t=r=>r.map(n=>`<${n} xsi:nil="true"></${n}>`).join("");return`<Address><AddressNumber>${e}</AddressNumber><AddressTypeCode>1</AddressTypeCode>${t($6)}<ShippingMethodCode>1</ShippingMethodCode>${t(x6)}</Address>`}function M_(e){let t=Ps(e.solutionUniqueName),r=Ps(e.publisherUniqueName);return`<ImportExportXml version="9.1.0.643" SolutionPackageVersion="9.1" languagecode="1033" generatedBy="CrmLive" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SolutionManifest><UniqueName>${t}</UniqueName><LocalizedNames><LocalizedName description="${t}" languagecode="1033" /></LocalizedNames><Descriptions /><Version>1.0</Version><Managed>0</Managed><Publisher><UniqueName>${r}</UniqueName><LocalizedNames><LocalizedName description="${r}" languagecode="1033" /></LocalizedNames><Descriptions><Description description="${r}" languagecode="1033" /></Descriptions><EMailAddress xsi:nil="true"></EMailAddress><SupportingWebsiteUrl xsi:nil="true"></SupportingWebsiteUrl><CustomizationPrefix>${Ps(e.prefix)}</CustomizationPrefix><CustomizationOptionValuePrefix>${e.optionValuePrefix}</CustomizationOptionValuePrefix><Addresses>${P_(1)}${P_(2)}</Addresses></Publisher><RootComponents><RootComponent type="66" schemaName="${Ps(e.controlName)}" behavior="0" /></RootComponents><MissingDependencies /></SolutionManifest></ImportExportXml>`}$e.pcfSolutionXml=M_;function U_(e){let t=Ps(e);return`<ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Entities></Entities><Roles></Roles><Workflows></Workflows><FieldSecurityProfiles></FieldSecurityProfiles><Templates /><EntityMaps /><EntityRelationships /><OrganizationSettings /><optionsets /><CustomControls><CustomControl><Name>${t}</Name><FileName>/Controls/${t}/ControlManifest.xml</FileName><ForceUpdate>true</ForceUpdate></CustomControl></CustomControls><EntityDataProviders /><Languages><Language>1033</Language></Languages></ImportExportXml>`}$e.pcfCustomizationsXml=U_;function B_(e){let t=["xml"];for(let n of e){let i=n.slice(n.lastIndexOf(".")+1).toLowerCase();t.includes(i)||t.push(i)}return`<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${t.map(n=>`<Default Extension="${Ps(n)}" ContentType="application/octet-stream" />`).join("")}</Types>`}$e.pcfContentTypesXml=B_;function F6(e){let t=`Controls/${e.controlName}`,r=[{name:"customizations.xml",data:(0,uf.utf8ToBytes)(U_(e.controlName))},{name:"solution.xml",data:(0,uf.utf8ToBytes)(M_(e))},...e.control.files.map(n=>({name:`${t}/${n.path}`,data:n.data})),{name:`${t}/ControlManifest.xml`,data:(0,uf.utf8ToBytes)(e.control.manifest)},{name:"[Content_Types].xml",data:(0,uf.utf8ToBytes)(B_(e.control.files.map(n=>n.path)))}];return(0,T6.zipStored)(r)}$e.buildPcfSolutionZip=F6;var M6=/^[ \t\r\n]*$/,q_=1,c0=3,U6=4,V_=7;function cf(e,t){let r=(0,Qr.attr)(e,"xml:space");return r==="preserve"?!0:r==="default"?!1:t}function R_(e,t){var r;let n=[],i=e.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];(a.nodeType===q_||a.nodeType===U6||a.nodeType===V_||a.nodeType===c0&&(t||!M6.test((r=a.nodeValue)!==null&&r!==void 0?r:"")))&&n.push(a)}return n}function L_(e){return e.length>0&&e.every(t=>t.nodeType===c0)?e.map(t=>{var r;return(r=t.nodeValue)!==null&&r!==void 0?r:""}).join(""):void 0}function k_(e,t){var r;let n="",i=t;for(;i<e.length&&e[i].nodeType===c0;)n+=(r=e[i].nodeValue)!==null&&r!==void 0?r:"",i+=1;return{text:n,next:i}}function l0(e,t){return(e.namespaceURI||null)===(t.namespaceURI||null)&&e.localName===t.localName}function B6(e,t,r,n){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType===q_)return G_(e,t,r,n);if(e.nodeType===V_){let i=e,o=t;return i.target===o.target&&i.data===o.data}return e.nodeValue===t.nodeValue}function q6(e,t,r,n){let i=L_(e);if(i!==void 0)return i===L_(t);if(e.length===0)return t.length===0;let o=0,a=0;for(;;){let s=k_(e,o),l=k_(t,a);if(s.text!==l.text)return!1;if(o=s.next,a=l.next,o>=e.length&&a>=t.length)return!0;if(o>=e.length||a>=t.length||!B6(e[o],t[a],r,n))return!1;o+=1,a+=1}}function G_(e,t,r,n){if(!l0(e,t)||e.attributes.length!==t.attributes.length)return!1;for(let a=0;a<e.attributes.length;a+=1){let s=e.attributes.item(a),l=t.attributes.item(a);if(!l0(s,l)||s.value!==l.value)return!1}let i=cf(e,r),o=cf(t,n);return q6(R_(e,i),R_(t,o),i,o)}function u0(e){return(0,Qr.elementChildren)(e).reduce((t,r)=>t+1+u0(r),0)}function $_(e){return cf(e,cf(e.parentNode,!1))}function V6(e,t){let r,n;try{r=s0(t).control,n=s0(e).control}catch{return!1}if(r.attributes.length!==n.attributes.length)return!1;for(let u=0;u<r.attributes.length;u+=1){let c=r.attributes.item(u),d;for(let m=0;m<n.attributes.length&&!d;m+=1){let p=n.attributes.item(m);d=l0(c,p)?p:void 0}if(!d||!(c.localName==="version"&&!c.namespaceURI)&&c.value!==d.value)return!1}if(u0(r)!==u0(n))return!1;let i=(0,Qr.elementChildren)(r),o=(0,Qr.elementChildren)(n),a=$_(r),s=$_(n),l=Math.min(i.length,o.length);for(let u=0;u<l;u+=1)if(!G_(i[u],o[u],a,s))return!1;return!0}$e.pcfManifestsEquivalent=V6});var z_=v(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});df.sha256Hex=void 0;var G6=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ai=(e,t)=>e>>>t|e<<32-t;function W6(e){let t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint8Array(Math.ceil((e.length+9)/64)*64);r.set(e),r[e.length]=128;let n=new DataView(r.buffer);n.setUint32(r.length-8,Math.floor(e.length/536870912)),n.setUint32(r.length-4,e.length%536870912*8);let i=new Uint32Array(64);for(let o=0;o<r.length;o+=64){for(let p=0;p<16;p+=1)i[p]=n.getUint32(o+p*4);for(let p=16;p<64;p+=1){let h=ai(i[p-15],7)^ai(i[p-15],18)^i[p-15]>>>3,g=ai(i[p-2],17)^ai(i[p-2],19)^i[p-2]>>>10;i[p]=i[p-16]+h+i[p-7]+g>>>0}let[a,s,l,u,c,d,f,m]=t;for(let p=0;p<64;p+=1){let h=m+(ai(c,6)^ai(c,11)^ai(c,25))+(c&d^~c&f)+G6[p]+i[p]>>>0,g=(ai(a,2)^ai(a,13)^ai(a,22))+(a&s^a&l^s&l)>>>0;m=f,f=d,d=c,c=u+h>>>0,u=l,l=s,s=a,a=h+g>>>0}t[0]+=a,t[1]+=s,t[2]+=l,t[3]+=u,t[4]+=c,t[5]+=d,t[6]+=f,t[7]+=m}return Array.from(t,o=>o.toString(16).padStart(8,"0")).join("")}df.sha256Hex=W6});var aT=v(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.registerPcfControl=Ne.readJobVerdict=Ne.PCF_REGISTRATION_UNVERIFIED_CODE=Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE=Ne.PCF_RESOURCE_NAME_TAKEN_CODE=Ne.PCF_CONTROL_MANAGED_CODE=Ne.PCF_CONTROL_AMBIGUOUS_CODE=Ne.PCF_CONTROL_NAME_TAKEN_CODE=Ne.PCF_TARGET_SOLUTION_MANAGED_CODE=void 0;var z6=Es(),_o=Tt(),Vi=W_(),X_=jr(),d0=Jd(),We=Q(),j6=cu(),Su=pa(),To=fe(),Z_=ct(),nt=oe(),H6=z_();Ne.PCF_TARGET_SOLUTION_MANAGED_CODE="PCF_TARGET_SOLUTION_MANAGED";Ne.PCF_CONTROL_NAME_TAKEN_CODE="PCF_CONTROL_NAME_TAKEN";Ne.PCF_CONTROL_AMBIGUOUS_CODE="PCF_CONTROL_AMBIGUOUS";Ne.PCF_CONTROL_MANAGED_CODE="PCF_CONTROL_MANAGED";Ne.PCF_RESOURCE_NAME_TAKEN_CODE="PCF_RESOURCE_NAME_TAKEN";Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE="PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL";Ne.PCF_REGISTRATION_UNVERIFIED_CODE="PCF_REGISTRATION_UNVERIFIED";var it="registerPcfControl",f0=66,K6=5e3,j_=300*1e3,J6={hash:"webresourceid,name,ismanaged,webresourcetype,contenthash",tokens:"webresourceid,name,ismanaged,webresourcetype",content:"webresourceid,name,ismanaged,webresourcetype,content"},ff=new WeakMap;function pf(e){return new We.InvalidArgumentError(`${it}: ${e}`)}function Rs(e,t){return e.toLowerCase()===t.toLowerCase()}function si(e){return e.map(t=>`'${t}'`).join(", ")}function Y6(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Nu(e){return e instanceof We.ConnectionError&&(e.statusCode===0||To.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}function Q6(e,t){var r;if(e!==void 0&&(typeof e!="object"||e===null))throw pf("options must be an object.");let{solutionUniqueName:n,publishAll:i}=e??{};if(i!==void 0&&i!==!0)throw pf(`publishAll must be absent or the literal true (it was ${String(i)}): it consents to PublishAllXml, which publishes every pending customization in the org. Nothing was sent.`);if(n!==void 0&&(typeof n!="string"||!n.trim()))throw pf("solutionUniqueName must be a non-empty string. Nothing was sent.");let o=(r=n)!==null&&r!==void 0?r:t;if(!o)throw pf("name the solution the control joins \u2014 options.solutionUniqueName or MakerSdkOptions.solutionUniqueName: its publisher's prefix names the control, and the SDK never guesses one. Nothing was sent.");return{target:o,publishAll:i===!0}}function eT(e,t,r){let n=e?.["@odata.etag"];if(!(0,To.isVersionToken)(n))throw new We.ConnectionError(r,200,`${it}: ${t} came back without a version token (@odata.etag ${n===void 0?"missing":JSON.stringify(n)}), so a change since it was read could not be detected`);return n}function tT(e,t){var r,n,i,o;let a=e,s=String((r=a?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=a?.customcontrolid)!==null&&n!==void 0?n:""),"customcontrolid"),name:s,version:String((i=a?.version)!==null&&i!==void 0?i:""),manifest:String((o=a?.manifest)!==null&&o!==void 0?o:""),managed:a?.ismanaged===!0,etag:eT(e,`the control '${s}'`,t)}}function X6(e,t){var r,n;let i=e,o=String((r=i?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=i?.webresourceid)!==null&&n!==void 0?n:""),"webresourceid"),name:o,managed:i?.ismanaged===!0,type:Number(i?.webresourcetype),content:typeof i?.content=="string"?i.content:"",contentHash:typeof i?.contenthash=="string"?i.contenthash.toLowerCase():"",etag:eT(e,`the web resource '${o}'`,t)}}async function p0(e){let t=(0,nt.odataLiteral)(e.key),r=`/customcontrols${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"],["$filter",`endswith(name,'_${t}') or name eq '${t}'`]])}`,n=e.client.apiUrl(r),i=e.key.toLowerCase();return(await(0,_o.collectPages)(e.client,r,it)).filter(o=>{let a=typeof o.name=="string"?o.name.toLowerCase():"";return a===i||a.slice(a.indexOf("_")+1)===i}).map(o=>tT(o,n))}async function mf(e,t){let r=`cc_${e.key}/`,n=`/webresourceset${(0,nt.odataQuery)([["$select",J6[t]],["$filter",`startswith(name,'${(0,nt.odataLiteral)(r)}')`]])}`,i=e.client.apiUrl(n);return(await(0,_o.collectPages)(e.client,n,it)).filter(o=>typeof o.name=="string"&&o.name.toLowerCase().startsWith(r.toLowerCase())).map(o=>X6(o,i))}function Z6(e){let t=ff.get(e.sdkClient);if(t)return t;let r=`/EntityDefinitions(LogicalName='webresource')/Attributes${(0,nt.odataQuery)([["$select","LogicalName"],["$filter","LogicalName eq 'contenthash'"]])}`,n=e.client.apiUrl(r),i=e.client.get(r).then(o=>{var a;let s=(a=(0,To.ensureSuccess)(o,n).body)===null||a===void 0?void 0:a.value;if(!Array.isArray(s))throw new We.ConnectionError(n,o.status,`${it}: the columns of webresource came back unreadable`);return s.some(l=>l?.LogicalName==="contenthash")}).catch(o=>{throw ff.get(e.sdkClient)===i&&ff.delete(e.sdkClient),o});return ff.set(e.sdkClient,i),i}async function rT(e,t){let r=await(0,_o.collectPages)(e.client,`/customcontrols(${t})/customcontrol_resource_id${(0,nt.odataQuery)([["$select","webresourceid,name"]])}`,it);return new Set(r.map(n=>n.webresourceid).filter(n=>typeof n=="string"&&n!=="").map(n=>n.toLowerCase()))}async function m0(e,t){let r=`/customcontrols(${t})${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"]])}`,n=await e.client.get(r);if(n.status!==404)return(0,To.ensureSuccess)(n,e.client.apiUrl(r)),tT(n.body,e.client.apiUrl(r))}function H_(e,t,r){return new We.SdkError(Ne.PCF_RESOURCE_NAME_TAKEN_CODE,`${it}: ${si(t.map(n=>n.name))} ${t.length===1?"is":"are"} named as a file of ${e.name} but ${r}. An import would create a second web resource of the same name (the runtime loads by name); rename or delete ${t.length===1?"it":"them"} first. Nothing was written.`)}async function ez(e){let t=await p0(e),r=t.filter(u=>!Rs(u.name,e.name));if(r.length>0)throw new We.SdkError(Ne.PCF_CONTROL_NAME_TAKEN_CODE,`${it}: the control ${e.key} is registered as ${si(r.map(u=>u.name))}, under another publisher prefix \u2014 the platform keeps one control per namespace and constructor. Target a solution whose publisher has that prefix, or remove that control. Nothing was written.`);if(t.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${t.length} control rows are named ${e.name}; the SDK cannot tell which one to update. Nothing was written.`);let n=t[0];if(n?.managed)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${n.name} is managed; a managed control is changed by its solution's upgrade, not in place. Nothing was written.`);let i=await mf(e,await Z6(e)?"hash":"tokens");if(!n){if(i.length>0)throw H_(e,i,"no control of that name exists");return}e.progress.customControlId=n.id;let o=await rT(e,n.id),a=i.filter(u=>!o.has(u.id));if(a.length>0)throw H_(e,a,`${n.name} does not reference ${a.length===1?"it":"them"}`);let s=i.filter(u=>u.managed);if(s.length>0)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${si(s.map(u=>u.name))} of ${n.name} ${s.length===1?"is":"are"} managed. Nothing was written.`);let l=new Map;for(let u of e.checked.files){let c=(0,Vi.pcfWebResourceName)(e.checked,u.path),d=i.filter(f=>Rs(f.name,c));if(d.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${n.name} references ${d.length} web resources named '${c}'; the SDK cannot tell which one the runtime loads. Nothing was written.`);d.length===1&&l.set(u.path,d[0])}return{control:n,folder:i,files:l}}function tz(e){return(0,H6.sha256Hex)((0,Su.utf8ToBytes)((0,Su.bytesToBase64)(e.data)))}function rz(e,t){if(!t)return{mode:"created"};let{control:r}=t,n=(0,Vi.pcfManifestsEquivalent)(r.manifest,e.checked.manifest),i=e.checked.files.filter(s=>!t.files.has(s.path)).map(s=>s.path),o=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l!==void 0&&l.type!==s.webResourceType).map(({file:s,row:l})=>`'${l.name}' (type ${l.type}, not ${s.webResourceType})`);if(!n||i.length>0||o.length>0){if(!e.publishAll){let s=n?i.length>0?`${r.name} lacks ${si(i)}, which only a re-import restores`:`${r.name}'s ${o.join(", ")} cannot be repaired by a files-only write \u2014 only a re-import may`:`the manifest of ${r.name} changed`;throw new We.SdkError(Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE,`${it}: ${s}, and a re-imported control is applied only by PublishAllXml \u2014 which publishes EVERY pending customization in the org. Pass publishAll: true to consent. Nothing was written.`)}return{mode:"reimported",snapshot:t}}if(r.version!==e.checked.version){if(e.publishAll)return{mode:"reimported",snapshot:t};e.warnings.push(`${r.name} keeps version ${r.version}: a files-only update does not change it (pac's --incremental neither); applying ${e.checked.version} needs publishAll: true.`)}let a=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l.contentHash!==tz(s));return a.length>0?{mode:"updated",snapshot:t,changed:a}:{mode:"unchanged",snapshot:t}}async function hf(e,t){var r;if(!t){let s=await p0(e),l=await mf(e,"tokens");if(s.length>0||l.length>0)throw new We.VersionConflictError("customcontrol",e.name,null,null,`Since this registration first read the org, ${si([...s.map(u=>u.name),...l.map(u=>u.name)])} appeared. Nothing was written; retry the registration.`);return}let n=[],i=await m0(e,t.control.id);i?i.etag!==t.control.etag&&n.push(i.name):n.push(`${t.control.name} (deleted)`);let o=await mf(e,"tokens"),a=new Map(t.folder.map(s=>[s.id,s.etag]));for(let s of o)a.has(s.id)?a.get(s.id)!==s.etag&&n.push(s.name):n.push(`${s.name} (new)`);for(let s of t.folder)o.some(l=>l.id===s.id)||n.push(`${s.name} (deleted)`);if(n.length>0)throw new We.VersionConflictError("customcontrol",e.name,t.control.etag,(r=i?.etag)!==null&&r!==void 0?r:null,`Changed since this registration read it: ${si(n)} \u2014 by another writer, or by the platform touching them (an import or publish elsewhere in the org can move these tokens with no change). Nothing was written; retry the registration.`)}function nT(e){let t;try{t=(0,j6.parseManifestRoot)(typeof e=="string"?e:"")}catch{return{state:"unknown",reason:"settled, but its data log does not parse"}}if(t.tagName!=="importexportxml"||t.namespaceURI)return{state:"unknown",reason:`settled, but its data log's root is <${t.tagName}>`};let r=(0,Vi.unboundPrefixes)(t);if(r.length>0)return{state:"unknown",reason:`settled, but its data log uses a prefix no declaration binds (${r.join(", ")})`};let n=t.getAttribute("succeeded");return n==="success"||n==="warning"?{state:"success"}:n==="failure"?{state:"failure",message:t.getAttribute("status")||"the import failed"}:{state:"unknown",reason:"settled without a success, warning or failure verdict"}}Ne.readJobVerdict=nT;function nz(e,t){return new Promise(r=>{let n=setTimeout(()=>r("late"),t);e.then(i=>{clearTimeout(n),r({value:i})},i=>{clearTimeout(n),r({error:i})})})}async function iz(e,t){let r=`/importjobs(${t})${(0,nt.odataQuery)([["$select","completedon,data"]])}`,n=Date.now()+j_,i={state:"unknown",reason:`had not settled after ${j_/6e4} minutes`};for(;;){let o=Math.min(K6,n-Date.now());if(o<=0)return i;await new Promise(c=>setTimeout(c,o));let a=n-Date.now();if(a<=0)return i;let s=await nz(e.client.get(r),a);if(s==="late")return i;if("error"in s){if(Nu(s.error))continue;return{state:"unknown",reason:`could not be read (${s.error.message})`}}let l=s.value;if(l.status===404)continue;if(l.status<200||l.status>=300)return{state:"unknown",reason:`could not be read (HTTP ${l.status})`};let u=l.body;if(u?.completedon)return nT(u.data)}}async function oz(e,t,r){let n=(0,Z_.newId)(),i=e.checked.files.map(s=>s.path),o=r?i.filter(s=>!r.files.has(s)):i;e.progress.phase="import",e.progress.importJobId=n,e.started=!0;let a;try{await(0,d0.importSolution)(e.client,{base64:(0,Su.bytesToBase64)(t),overwriteUnmanagedCustomizations:!1,publishWorkflows:!1,importJobId:n})}catch(s){if(!Nu(s))throw s;a=s}if(a){let s=await iz(e,n);if(s.state==="failure")throw new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} reports that it FAILED: ${s.message}`,a);if(s.state==="unknown")throw e.progress.imported="unknown",e.progress.unconfirmed=[...i],e.progress.publishedUnknown=[...o],new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} ${s.reason}: whether it committed is unknown. Read importjobs(${n}), then retry the registration.`,a)}e.progress.imported="yes",e.progress.written=[...i],e.progress.published=[...o]}async function az(e){e.progress.phase="publish-all";let t=e.checked.files.map(r=>r.path).filter(r=>!e.progress.published.includes(r));try{await(0,X_.publishAllXml)(e.client)}catch(r){throw Nu(r)?(e.progress.publishAll="unknown",e.progress.publishedUnknown=[...e.progress.publishedUnknown,...t]):e.progress.publishAll="failed",r}e.progress.publishAll="succeeded",e.progress.published=[...e.progress.published,...t]}async function K_(e,t){var r,n;if(e.progress.imported==="unknown")return e.progress.temporaries.push(t.solution,t.publisher),[`The temporary solution '${t.solution}' and publisher '${t.publisher}' were left in place: the import's outcome is unknown, and an import still running may be using them. Delete them once importjobs(${e.progress.importJobId}) has settled.`];let i=(o,a)=>(e.progress.temporaries.push(...a),[`${si(a)} ${a.length===1?"was":"were"} left in place: ${o}. Delete ${a.length===1?"it":"them"} when convenient.`]);try{let o=await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.solution)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((r=a.solutionid)!==null&&r!==void 0?r:""),"solutionid");if(!await sz(e,s))return i(`the temporary solution holds components other than ${e.name}`,[t.solution,t.publisher]);let l=`/solutions(${s})`;(0,To.ensureSuccess)(await e.client.delete(l),e.client.apiUrl(l))}}catch(o){return i(`the temporary solution could not be removed (${o.message})`,[t.solution,t.publisher])}try{let o=await(0,_o.collectPages)(e.client,`/publishers${(0,nt.odataQuery)([["$select","publisherid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.publisher)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((n=a.publisherid)!==null&&n!==void 0?n:""),"publisherid");if((await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`_publisherid_value eq ${s}`]])}`,it)).length>0)return i("a solution uses the temporary publisher",[t.publisher]);let u=`/publishers(${s})`;(0,To.ensureSuccess)(await e.client.delete(u),e.client.apiUrl(u))}}catch(o){return i(`the temporary publisher could not be removed (${o.message})`,[t.publisher])}return[]}async function sz(e,t){var r,n;let i=await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t}`]])}`,it);for(let o of i){if(o.componenttype!==f0||typeof o.objectid!="string")return!1;let a=(0,nt.normalizeGuid)(o.objectid,"objectid");if(a!==e.progress.customControlId&&!Rs((n=(r=await m0(e,a))===null||r===void 0?void 0:r.name)!==null&&n!==void 0?n:"",e.name))return!1}return!0}async function J_(e,t,r){let n=(0,Z_.newId)().replace(/-/g,"").slice(0,12),i={solution:`CdsMakerSdkPcf${n}`,publisher:`CdsMakerSdkPcfPub${n}`},o=(0,Vi.buildPcfSolutionZip)({controlName:e.name,solutionUniqueName:i.solution,publisherUniqueName:i.publisher,prefix:e.solution.publisherPrefix,optionValuePrefix:e.solution.publisherOptionValuePrefix,control:e.checked});await hf(e,r);let a;try{await oz(e,o,r),t==="reimported"&&await az(e);let s=await fz(e,r),l=await h0(e,s.id);a=g0(e,t,s,l,e.checked.files.map(u=>u.path),[])}catch(s){throw(0,We.withCleanupWarnings)(s,await K_(e,i))}return a.warnings.push(...await K_(e,i)),a}async function Y_(e,t,r){try{return await r()}catch(n){throw Nu(n)&&e.progress.unconfirmed.push(...t),n}}function lz(e){return e instanceof We.SdkError&&e.code===To.VERSION_CONFLICT_CODE&&!(e instanceof We.VersionConflictError)}async function uz(e,t,r){let n=({file:a})=>({content:(0,Su.bytesToBase64)(a.data)}),i=r.map(({file:a})=>a.path);if(e.client.supportsAtomicBatch){let a=s=>Y_(e,i,()=>(0,z6.sendChangeSet)(e.client,r.map(l=>({method:"PATCH",path:`/webresourceset(${l.row.id})`,body:n(l),etag:s?l.row.etag:"*"})),`the files of ${e.name}`));try{await a(!0)}catch(s){if(!lz(s))throw s;await hf(e,t),await a(!1)}e.progress.written.push(...i);return}let o;for(let a of r){let s=`/webresourceset(${a.row.id})`,l=c=>Y_(e,[a.file.path],async()=>{let d=await e.client.patch(s,n(a),{headers:{"If-Match":c}});return d.status===412?d:(0,To.ensureSuccess)(d,e.client.apiUrl(s))}),u=await l(o===!1?"*":a.row.etag);if(u.status===412&&o===void 0&&(await hf(e,t),o=!1,u=await l("*")),u.status===412)throw new We.VersionConflictError("webresource",a.row.id,a.row.etag,null,`'${a.row.name}' changed after this registration read it${e.progress.written.length>0?`; ${si(e.progress.written)} had been written before it`:""}. Retry the registration once the other writer is done.`);o=o??!0,e.progress.written.push(a.file.path)}}async function cz(e,t){e.progress.phase="publish";let r=t.map(({file:i})=>i.path),n=t.map(({row:i})=>`<webresource>${(0,nt.xmlText)(i.id)}</webresource>`).join("");try{await(0,X_.publishXml)(e.client,`<importexportxml><webresources>${n}</webresources></importexportxml>`)}catch(i){throw Nu(i)&&e.progress.publishedUnknown.push(...r),i}e.progress.published.push(...r)}async function dz(e,t,r){await hf(e,t),e.progress.phase="write",e.started=!0,await uz(e,t,r),await cz(e,r),e.progress.phase="verify";let n=await m0(e,t.control.id);if(!n)throw gf(e,"updated",["the control was deleted"]);let i=[];if((n.version!==t.control.version||n.manifest!==t.control.manifest)&&i.push("its control row changed since it was read \u2014 another registration re-imported it"),i.push(...await oT(e,n.id)),i.length>0)throw gf(e,"updated",i);let o=await h0(e,n.id);return g0(e,"updated",n,o,[...e.progress.written],[...e.progress.published])}function gf(e,t,r){return new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} did not verify after it was ${t}: ${r.join("; ")}. Retrying the registration is safe.`)}function iT(e,t){let r=new Set(e.checked.files.map(n=>(0,Vi.pcfWebResourceName)(e.checked,n.path).toLowerCase()));for(let n of t){let i=`'${n.name}' is a file of ${e.name} that its manifest no longer names; the platform keeps it after a re-import, and the SDK does not delete it.`;!r.has(n.name.toLowerCase())&&!e.warnings.includes(i)&&e.warnings.push(i)}}async function oT(e,t){let r=await rT(e,t),n=await mf(e,"content"),i=[],o=n.filter(s=>!r.has(s.id));o.length>0&&i.push(`${si(o.map(s=>s.name))} in its folder ${o.length===1?"is":"are"} not its own`);let a=n.filter(s=>r.has(s.id));for(let s of e.checked.files){let l=(0,Vi.pcfWebResourceName)(e.checked,s.path),u=a.filter(d=>Rs(d.name,l));if(u.length!==1){i.push(`it references ${u.length} web resources named '${l}'`);continue}let[c]=u;c.type!==s.webResourceType&&i.push(`'${c.name}' has the web resource type ${c.type}, not ${s.webResourceType}`),c.managed&&i.push(`'${c.name}' is managed`),Y6((0,Su.base64ToBytes)(c.content),s.data)||i.push(`the published content of '${c.name}' is not the file sent`)}return iT(e,a),i}async function fz(e,t){e.progress.phase="verify";let r=t?"reimported":"created",n=await p0(e),i=n.filter(l=>Rs(l.name,e.name)),o=[],a=n.filter(l=>!Rs(l.name,e.name));if(a.length>0&&o.push(`${si(a.map(l=>l.name))} also ${a.length===1?"holds":"hold"} ${e.key}`),i.length!==1)throw gf(e,r,[...o,`${i.length} control rows are named ${e.name}`]);let[s]=i;if(e.progress.customControlId=s.id,t&&s.id!==t.control.id&&o.push(`its row is ${s.id}, not the re-imported ${t.control.id}`),s.managed&&o.push("it is managed"),s.version!==e.checked.version&&o.push(`its version is ${s.version}, not ${e.checked.version}`),(0,Vi.pcfManifestsEquivalent)(s.manifest,e.checked.manifest)||o.push("its stored manifest is not equivalent to the one sent"),o.push(...await oT(e,s.id)),o.length>0)throw gf(e,r,o);return s}async function Q_(e,t){return(await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","solutioncomponentid"],["$filter",`_solutionid_value eq ${e.solution.solutionId} and objectid eq ${t} and componenttype eq ${f0}`]])}`,it)).length>0}async function h0(e,t){if(e.progress.phase="membership",await Q_(e,t))return"present";if(e.started=!0,await(0,d0.addSolutionComponent)(e.client,{componentId:t,componentType:f0,solutionUniqueName:e.solution.uniqueName,addRequiredComponents:!1}),!await Q_(e,t))throw new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} is not in the solution '${e.solution.uniqueName}' after AddSolutionComponent. Retrying the registration is safe.`);return"added"}function g0(e,t,r,n,i,o){return{name:r.name,customControlId:r.id,mode:t,written:i,published:o,publishedAll:t==="reimported",storedVersion:r.version,membership:n,warnings:[...e.warnings]}}async function pz(e,t,r){let n=(0,Vi.checkPcfControlPackage)(t),{target:i,publishAll:o}=Q6(r,e.solutionName),a=e.withSolutionScope(void 0),s=await(0,d0.getSolution)(a,i);if(s.isManaged||!s.publisherPrefix)throw new We.SdkError(Ne.PCF_TARGET_SOLUTION_MANAGED_CODE,`${it}: the solution '${s.uniqueName}' ${s.isManaged?"is managed; a control joins an unmanaged solution":"has a publisher without a customization prefix, which would leave the control's name unprefixed"}. Nothing was written.`);let l=(0,Vi.pcfControlName)(s.publisherPrefix,n),u={client:a,sdkClient:e,checked:n,key:`${n.namespace}.${n.constructorName}`,name:l,solution:s,publishAll:o,progress:{phase:"import",name:l,imported:"no",written:[],unconfirmed:[],published:[],publishedUnknown:[],publishAll:"not-sent",temporaries:[]},warnings:[],started:!1};try{let c=rz(u,await ez(u));switch(c.mode){case"created":return await J_(u,"created",void 0);case"reimported":return await J_(u,"reimported",c.snapshot);case"updated":return await dz(u,c.snapshot,c.changed);default:{iT(u,c.snapshot.folder);let d=await h0(u,c.snapshot.control.id);return g0(u,"unchanged",c.snapshot.control,d,[],[])}}}catch(c){throw u.started?(0,We.withPcfRegistrationProgress)(c,u.progress):c}}Ne.registerPcfControl=pz});var v0=v(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.compileGenPage=Re.legacyEnumsNeeded=Re.createGenPageTypeScriptLoader=Re.acceptGenPageTypeScript=Re.isLoadableGenPageOutput=Re.runtimeTypesImportSpans=Re.GENPAGE_RUNTIME_TYPES_END=Re.GENPAGE_RUNTIME_TYPES_BEGIN=Re.GENPAGE_TYPESCRIPT_VERSION=void 0;var Ls=Q();Re.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Re.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Re.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Ln="./RuntimeTypes",mz="'\"`",sT=/\s/;function hz(e){return e===10||e===13||e===8232||e===8233}function gz(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function dT(e){let t=[],r=Ln.length;for(let l=e.indexOf(Ln);l!==-1;l=e.indexOf(Ln,l+1)){let u=l-1;u>=0&&mz.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&sT.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&sT.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Re.runtimeTypesImportSpans=dT;var yz=/\b(?:import\s*['"]|export\s)/;function bz(e){let t=gz(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!hz(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function vz(e){return e!==void 0&&e!==""&&(yz.test(e)||bz(e))}Re.isLoadableGenPageOutput=vz;var lT=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function fT(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?lT.filter(s=>typeof n?.[s]!="function"):[...lT];if(!n||i.length>0)throw new Ls.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Re.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new Ls.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Re.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Re.acceptGenPageTypeScript=fT;function wz(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(fT).catch(r=>{throw t=void 0,r instanceof Ls.SdkError?r:new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Re.createGenPageTypeScriptLoader=wz;var pT=e=>`${e.kind}:${e.pos}:${e.end}`;function Cz(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(pT(o)),e.forEachChild(i,n)};return n(r),r}}function b0(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var Ez=2301;function uT(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:b0(e),reportDiagnostics:!0,...r?{transformers:{after:[Cz(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`-`)}});return{code:i.outputText,diagnostics:o}}var cT=e=>e.startsWith(".")||e.startsWith("/"),yf={line:1,column:1};function y0(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):yf},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return yf}}}function Az(e,t,r,n){var i,o;let a=[],s=y0(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let C=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;C===Ln?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&cT(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Ln){cT(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>m.add(C.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let C=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,O=s.element(h,C);S!==C?l(O,d,`'${S} as ${C}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(C)||l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(yf,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function mT(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`-`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===Ez&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===Ln},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function Sz(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=mT(e,t,b0(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has(pT(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function Nz(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===Ln)}function hT(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Ln).map(r=>r.getStart(t))}function _z(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=hT(e,r),i=new Set(n),o,a="",s=0;for(let l of dT(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function Tz(e,t,r){let n=new Set(hT(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return yf}function gT(e,t,r){if(!r||r.size===0)return[];let n=mT(e,t,{...b0(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Ln&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Re.legacyEnumsNeeded=gT;function Dz(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function Iz(e,t,r,n){var i;let o=new Set,a=uT(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=Dz(r,n,gT(e,l,n)),c=[...Az(e,l,s,u),...Sz(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=uT(e,u.text);if(d.diagnostics.length>0)throw new Ls.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=_z(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...Tz(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&Nz(e,m)&&c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[Re.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Re.GENPAGE_RUNTIME_TYPES_END,m].join(`+`).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}}Er.partResponse=lS;async function $G(e,t,r){let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=zh(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Gh.ensureSuccess)(lS(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Gh.ensureSuccess)(a,s),!l||l.length!==t.length)throw new oo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Er.sendChangeSet=$G});var cd=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=se(),Kn=Ho(),me=Q(),xG=Wl(),FG={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 Ze(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:MG(e,t)}}var uS=65535;function MG(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 me.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 me.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>uS)throw new me.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${uS})`);if(i.has(s))throw new me.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new me.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function mS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new me.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=mS;function zl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var cS=["None","ApplicationRequired","Recommended"];function Kh(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function dS(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new me.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function UG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,E,S,P,L,I,D,O,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new me.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new me.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:Ze((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Ze((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:(P=t.dateFormat)!==null&&P!==void 0?P:"DateAndTime"};case"choice":return fS(t,r,!1);case"multiChoice":return fS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((O=t.autoNumberFormat)===null||O===void 0)&&O.trim()))throw new me.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 me.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function fS(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 me.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:Ze(o.label,t)}))},i}var jh=new WeakMap;async function BG(e,t){var r,n;let i=(r=jh.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 me.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=jh.get(e);return l||(l=new Map,jh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=BG;async function qG(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 me.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 me.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 E=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,S=Kh(t.schemaName),P=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:P,RequiredLevel:zl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Ze((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&bS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Ze(t.displayName,E),DisplayCollectionName:Ze((a=t.pluralName)!==null&&a!==void 0?a:mS(t.displayName),E),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(bn=>Jh(bn,E))]};t.description&&(I.Description=Ze(t.description,E));let D="/EntityDefinitions",O=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=jl(O),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Re=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),qt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${P.toLowerCase()}', { required: '${b}' }).`:"",je;try{je=await hS(e,K,Re,qt)}catch(bn){throw w?(0,me.attachCause)(new me.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${bn instanceof Error?bn.message:String(bn)}).${ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),bn):bn}if(!je)throw new me.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Re} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${ge}`);let de=je.body,He={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:P.toLowerCase()};return w&&(He.primaryColumnRequired=await VG(e,t.schemaName,He,b,Re,qt)),He}ie.createTable=qG;async function hS(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 VG(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 hS(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 me.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 ES(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,me.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 Jh(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...UG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:zl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Ze(e.displayName,i)};return e.description&&(o.Description=Ze(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),gS(o,e),o}function gS(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 GG(e,t,r){var n;let i=Jh(r,(n=r.languageCode)!==null&&n!==void 0?n:Kn.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:jl(a)};if(r.visualization&&r.visualization!=="None")try{await CS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new me.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,me.attachCause)(u,l),u}return s}ie.createColumn=GG;var os="/controlconfigurations",yS="CustomRenderersConfiguration",Hh={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 bS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new me.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 vS(e){return JSON.stringify({type:Hh[e]})}function WG(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Hh).find(i=>Hh[i]===r);return n??"None"}async function wS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${os}${(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 zG(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 me.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function CS(e,t,r,n,i){let o={name:yS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:vS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(os,o),e.apiUrl(os))}async function jG(e,t,r){var n;let i=await wS(e,t,r);return WG((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=jG;async function HG(e,t,r,n){let o=(await wS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await zG(e,t,r);if(a){let u=`${os}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:yS,metadatajson:vS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await CS(e,t,r,l,n);for(let u of s){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=HG;async function KG(e,t,r){if(r.length===0)return;if(bS(r,"createColumns"),!e.supportsAtomicBatch)throw new me.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,xG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Jh(i,(o=i.languageCode)!==null&&o!==void 0?o:Kn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=KG;async function JG(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,l=Kh(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:Ze(r.displayName,s),RequiredLevel:zl((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=JG;async function YG(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Ze(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=YG;async function QG(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new me.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Kh(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:zl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Ze((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new me.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:jl(d),lookupLogicalName:u}}ie.createRelationship=QG;async function XG(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=XG;async function ES(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Kn.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=FG[(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 me.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=Ze(n.displayName,a)),n.description!==void 0&&(p.Description=Ze(n.description,a)),n.required!==void 0&&(p.RequiredLevel=zl(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 me.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 me.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),gS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=ES;async function ZG(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 me.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=ZG;async function e9(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 me.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=e9;async function pS(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 t9(e,t){var r;let n=t.name.toLowerCase(),i=await pS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Ze(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Ze(l.label,o)}))};t.description&&(a.Description=Ze(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:jl(l)}}catch(l){let u;try{u=await pS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=t9;async function r9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=r9;async function n9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Ze(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:jl(s)}}ie.createAlternateKey=n9;async function i9(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 me.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=i9;async function o9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.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 me.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=Ze(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Ze(r.pluralName,i)),r.description!==void 0&&(s.Description=Ze(r.description,i)),r.auditEnabled!==void 0&&dS(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&dS(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=o9});var so=v(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.rebuildRaw=Ar.assembleChildren=Ar.spliceChildren=Ar.mergeAttrs=Ar.rawFromNode=Ar.emptyBag=void 0;var ao=Q(),AS=1e6,fd=512;function a9(){return{a:[],c:[]}}Ar.emptyBag=a9;function SS(e,t=0){if(t>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>SS(r,t+1))}}Ar.rawFromNode=SS;function s9(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}Ar.mergeAttrs=s9;function dd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>AS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${AS}] (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}Ar.spliceChildren=dd;function l9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:dd(e.w.c,t)};return dd(e.c,[r])}return dd(e.c,t)}Ar.assembleChildren=l9;function NS(e,t,r,n=0){if(n>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);u9(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,NS(o,t,i,n+1));return i}Ar.rebuildRaw=NS;function u9(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(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.installDomShim=void 0;var _S=es(),TS=!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 d9(){if(TS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=_S.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=_S.XMLSerializer),typeof e.Node>"u"&&(e.Node=c9),TS=!0}pd.installDomShim=d9});var uo=v(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.projectElementBag=et.serializeNode=et.domEngine=et.nodeLikeFromDom=et.parseXmlRoot=et.EMPTY_FORM_SENTINEL=et.TEXT_SENTINEL=void 0;var f9=so(),as=Q(),p9=lo();et.TEXT_SENTINEL="#text";et.EMPTY_FORM_SENTINEL="#empty";var hd=new WeakSet;function m9(e,t){(0,p9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new as.InvalidArgumentError("XML source has no root element (empty or malformed input)");return h9(r),y9(n),v9(i),w9(i),A9(i,r),i}et.parseXmlRoot=m9;function h9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw IS(3)}var g9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function y9(e){var t;for(let r of g9){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 as.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var b9=new Set([1,3]);function v9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!b9.has(o.nodeType))throw new as.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 w9(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 IS(a.nodeType)}}function IS(e){return new as.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function C9(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 E9(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 OS(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function A9(e,t){let r=C9(t),n=E9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];OS(a)||hd.add(a)}}function Yh(e){let t=e.nodeType===3;return{getNodeName:()=>t?et.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:et.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 hd.has(e)&&!OS(e)&&i.push({key:et.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(Yh(o))}return r}}}et.nodeLikeFromDom=Yh;function S9(e){return{make:t=>t===et.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===et.EMPTY_FORM_SENTINEL?hd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}et.domEngine=S9;function PS(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 md(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw md(r);t+=1;continue}if(r>=56320&&r<=57343)throw md(r)}}function md(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new as.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 N9(e){return PS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function _9(e){return PS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function T9(e){return RS(e,0)}et.serializeNode=T9;var DS=512;function RS(e,t){var r;if(t>DS)throw new as.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${DS}`);if(e.nodeType===3)return _9((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+'="'+N9(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 hd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=RS(l,t+1);return i+"</"+n.tagName+">"}function D9(e){let t=Yh(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,f9.rawFromNode)(r)}))}}et.projectElementBag=D9});var en=v(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.rejectUnknownKeys=Ht.childObjects=Ht.optionalGuidId=Ht.optionalEnum=Ht.eachObject=Ht.issue=Ht.isJsonObject=void 0;function LS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Ht.isJsonObject=LS;function ss(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Ht.issue=ss;function kS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{LS(o)?i.push({node:o,index:a}):n.push(ss(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Ht.eachObject=kS;function I9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(ss(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Ht.optionalEnum=I9;var O9=/^(?:\{[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 P9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!O9.test(o)&&i.push(ss(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Ht.optionalGuidId=P9;function R9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?kS(o,a,n,i):(i.push(ss(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Ht.childObjects=R9;function L9(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(ss(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Ht.rejectUnknownKeys=L9});var wd=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 k9=es(),$9=$a(),Qh=dt(),tn=en();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 x9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Sr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),x9.test(t)?t:""}B.normGuid=Sr;function co(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Kl(e){return Ae(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Kl;function Ae(e){return Array.isArray(e)?e:[]}function ng(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function FS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function MS(e){return An(e).map(t=>t.cell)}B.typedCells=MS;function An(e){let t=[];return Ae(e?.tabs).forEach((r,n)=>{Ae(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ae(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ae(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ae(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=An;function Di(e){return Pe(e)?Sr(ng(e.bag,"uniqueid")):""}B.controlUniqueId=Di;function F9(e){let t=new Set;for(let{cell:r}of An(e)){let n=Yo(r.control)?Di(r.control):"";n&&t.add(n)}return t}function M9(e){let t=new Map;for(let{cell:r}of An(e)){let n=Pe(r.control)?Di(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function U9(e){return e!==void 0&&e.genPage===void 0&&(ag(e)!==B.CUSTOM_CONTROL_CLASS_ID||!vd(e))}function Xh(e,t){if(Pe(e)){t(e);for(let r of Ae(e.c))Xh(r,t)}}function Ko(e,t){var r;if(Pe(e)){for(let n of Ae(e.c))Xh(n?.node,t);for(let n of Ae((r=e.w)===null||r===void 0?void 0:r.c))Xh(n?.node,t)}}function yd(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(Sr(co(i,"uniqueid")))};return Ko(e?.bag,n),Ae(e?.tabs).forEach(i=>{Pe(i)&&(Ko(i.bag,n),Ae(i.columns).forEach(o=>{Pe(o)&&(Ko(o.bag,n),Ae(o.sections).forEach(a=>{Pe(a)&&(Ko(a.bag,n),Ae(a.rows).forEach(s=>{Pe(s)&&(Ko(s.bag,n),Ae(s.cells).forEach(l=>{Pe(l)&&(Ko(l.bag,n),Pe(l.control)&&(r(Di(l.control)),Ko(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=yd;function ls(e){return Ae(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ls;function Jo(e,t){var r;let n=Sr(t);if(n)return Ae((r=ls(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Sr(co(i,"forControl"))===n)}B.descriptionFor=Jo;function Jl(e){return Ae(e.c).filter(US)}B.pageEntries=Jl;function US(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function Zh(e,t){let r=Ae(e.c).find(n=>n?.n==="parameters");return Ae(r?.c).find(n=>n?.n===t)}B.entryParameter=Zh;function eg(e){return co(e,"static")==="true"}B.isStaticParameter=eg;function Yl(e){let t=Jl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Zh(t[i],"RefId");if(!o||!eg(o))return{kind:"unsupported"};let a=Sr(Kl(o));if(!a)return{kind:"unsupported"};let s=Zh(t[i],"PageInput");if(s&&!eg(s))return{kind:"unsupported"};let l=s?Kl(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=Yl;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ig(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=ig;function og(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=og;function ag(e){return FS(e.classId!==void 0?e.classId:ng(e.bag,"classid"))}B.effectiveClassId=ag;function vd(e){return!e.fieldName}B.isUnbound=vd;function sg(e,t){if(og(e)!=="Main"||!vd(t)||ag(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Di(t),n=r?Jo(e.bag,r):void 0;return n!==void 0&&Yl(n).kind==="projectable"}B.isRecognizedEmbed=sg;function B9(e){for(let t of MS(e)){let r=t.control;if(!r||!sg(e,r))continue;let n=Yl(Jo(e.bag,Di(r)));if(n.kind!=="projectable")continue;let i=ig(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=B9;var q9=new Set(["pageId","inputData"]);function Hl(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 V9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new k9.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=Sr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Hl(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Hl(l):[]){let d=Sr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Hl(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Hl(f).find(g=>g.nodeName==="parameters"),p=m?Hl(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Sr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=V9;function gd(e){return{n:`<${e}`,a:[],c:[]}}function tg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[gd(t)]}}function rg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function G9(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:[tg("RefId",t),...r===void 0?[]:[tg("PageInput",rg(r))]]}]}))}}function bd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>bd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&bd(e[n],t[n]))}return e===t}function W9(e,t,r){let n=Ae(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Sr(Kl(i))!==t&&(i.c=[gd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Kl(a):void 0;if(bd(ig(s),r))return;if(r!==void 0){a?a.c=[gd(rg(r,s))]:n.c.push(tg("PageInput",rg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[gd(JSON.stringify(l))]}function lg(e){let t=Ae(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=lg;function z9(e,t){var r;let n=e.bag,i=ls(n);if(i&&t){let o=yd(t),a=yd(e),s=F9(t),l=M9(e),u=Ae(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Jl(d).length>0?Sr(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&U9(l.get(f))&&bd(d,Jo(t.bag,f))){let m=Ae(d.c).filter(p=>!US(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 An(e)){let a=o.control;if(!Yo(a)||!Pe(a.genPage))continue;let s=Sr(a.genPage.pageId),l=a.genPage.inputData,u=Di(a);if(!u){if(Ql(a)!==void 0)continue;u=ug(a)}let c=Jo(n,u);if(c){for(let m of Jl(c))W9(m,s,l);continue}i||(i={i:lg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=ng(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(G9(f,s,l))}}B.reconcileEmbedDescriptions=z9;function j9(e,t){let r=ls(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=An(e).some(({cell:a})=>Yo(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=ls(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ae(o.bag.c),o.bag.c.push({i:lg(e.bag),node:a}))}for(let{cell:a}of An(o))Yo(a.control)&&(BS(a.control),qS(a));return o}B.commitEmbedState=j9;function H9(e){if(An(e).some(({cell:r})=>Yo(r.control)))return!0;let t=ls(e.bag);return Ae(t?.node.c).some(r=>r?.n==="controlDescription"&&Jl(r).length>0)}B.mayCommitEmbedState=H9;function BS(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=BS;function qS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=qS;function Yo(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=Yo;function $S(e){return Yo(e.control)&&(!e.control.id||!e.id||Ql(e.control)===void 0)}function Ql(e){let t=Ae(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=Ql;function K9(e){if(!An(e).some(({cell:r})=>$S(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of An(t)){if(!$S(r))continue;let n=r.control;n.id||(n.id=(0,Qh.newId)()),r.id||(r.id=(0,Qh.newId)()),Ql(n)===void 0&&ug(n)}return t}B.mintEmbedIdentity=K9;function ug(e){let t=(0,Qh.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ae(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=Ae(e.bag.c),t}B.setUniqueId=ug;function xS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function J9(e){let t=Ae(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 Y9(e){let t=[],r;for(let{cell:n,pointer:i}of An(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){Q9(e,o,a,t);continue}r=r??yd(e),X9(e,o,a,r,t)}return t}B.genPageEmbedIssues=Y9;function Q9(e,t,r,n){if(!sg(e,t))return;let i=Yl(Jo(e.bag,Di(t)));n.push((0,tn.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 X9(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,tn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${xS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Sr(s.pageId))&&i.push((0,tn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,tn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${xS(s.inputData)}`));for(let m of Object.keys(s))q9.has(m)||i.push((0,tn.issue)($9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}vd(t)||i.push((0,tn.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&&FS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,tn.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=og(e);l!=="Main"&&i.push((0,tn.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=Ql(t);u!==void 0&&!Sr(u)&&i.push((0,tn.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=Di(t);if(!c)return;let d=Jo(e.bag,c),f=d?Yl(d):void 0;d&&f?.kind==="none"?i.push((0,tn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${J9(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,tn.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,tn.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 dg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var Z9=Lt(),cg=se();fo.GENPAGE_LOOKUP_CHUNK=50;async function e5(e,t,r){let n=[...new Set(t.map(o=>(0,cg.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,cg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,Z9.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,cg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=e5});var Xl=v(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.assertSystemFormKind=Nt.readSystemFormType=Nt.decodeCode=Nt.assertSystemFormRecordKind=Nt.describeSystemFormType=Nt.systemFormKindOf=Nt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var GS=Q(),t5=ye(),VS=se();Nt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var r5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},n5={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 Cd(e){return Number.isInteger(e)?r5[e]:void 0}Nt.systemFormKindOf=Cd;function WS(e){var t;return Number.isFinite(e)?`a ${(t=n5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Nt.describeSystemFormType=WS;function zS(e,t,r,n){let i=WS(r),o=Cd(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 i5(e,t,r,n){let i=fg(e?.type);if(Cd(i)!==r)throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,i,n));return i}Nt.assertSystemFormRecordKind=i5;function fg(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}Nt.decodeCode=fg;async function o5(e,t){return await jS(e,t,!1)}Nt.readSystemFormType=o5;async function a5(e,t){return jS(e,t,!0)}async function jS(e,t,r){var n;let o=`/systemforms(${(0,VS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,VS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,t5.ensureSuccess)(a,e.apiUrl(o)),fg((n=a.body)===null||n===void 0?void 0:n.type)}async function s5(e,t,r){let n=await a5(e,t);if(!(n===void 0||Cd(n)===r))throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,n,"delete"))}Nt.assertSystemFormKind=s5});var mg=v(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.patchSystemForm=qr.assertSystemFormContentUnchanged=qr.readSystemFormRowEtag=qr.unpublishedSystemFormPath=qr.FORM_TYPE_IMMUTABLE_CODE=void 0;var rn=ye(),l5=se(),Ed=Q(),po=Xl();qr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function pg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,l5.odataQuery)([["$select",t]])}qr.unpublishedSystemFormPath=pg;function HS(e,t){return(0,rn.readRowEtag)(e,"systemforms","formid",t)}qr.readSystemFormRowEtag=HS;async function KS(e,t,r,n,i){(0,rn.requireEtag)(i,r,t);let o=(0,rn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,rn.readEtag)(o);if(s===null)throw new Ed.SdkError(rn.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 Ed.SdkError(rn.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}qr.assertSystemFormContentUnchanged=KS;async function u5(e,t,r,n,i,o){(0,rn.requireEtag)(i,r,t);let a=await HS(e,t);if(a===null)throw new Ed.SdkError(rn.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 KS(e,t,r,pg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Ed.SdkError(qr.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,rn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,rn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),c5(e,t,r,o)}qr.patchSystemForm=u5;async function c5(e,t,r,n){let i;try{let o=pg(t,n.select),a=(0,rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,rn.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 vg=v(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.getFormSecurityRoles=kt.setFormSecurityRoles=kt.formApi=kt.readPrimaryCreateRefusal=kt.FORM_GENPAGE_TARGET_UNVERIFIABLE=kt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var d5=Lt(),_t=ye(),nn=se(),Qo=Q(),hg=uo(),YS=wd(),f5=dg(),gg=mg(),Zl=Xl();kt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";kt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var QS="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",p5={select:QS,required:["name","type","objecttypecode"]},m5="formid,name,type,objecttypecode",h5=2,g5={Main:h5,QuickView:6,QuickCreate:7,Card:11},XS=new WeakMap;function y5(e){return typeof e=="object"&&e!==null?XS.get(e):void 0}kt.readPrimaryCreateRefusal=y5;kt.formApi={async get(e,t){let r=(0,nn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select",QS]]),i=(0,_t.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,Zl.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,_t.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=>g5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,nn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,nn.odataQuery)([["$select",m5],["$filter",a.join(" and ")]])}`;return(await(0,d5.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=JS(t);n!==void 0&&await ZS(e,bg(n,"payload"),[]);let i=(0,_t.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,_t.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,_t.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,_t.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&XS.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,_t.resolveCreatedId)(l,"formid","form",r),etag:(0,_t.readEtag)(l)}},async update(e,t,r,n){let i=(0,nn.normalizeGuid)(t,"id"),o=JS(r);return o!==void 0&&await v5(e,i,o,n),(0,gg.patchSystemForm)(e,i,"form",r,n,p5)},readContentThenToken(e,t){return kt.formApi.get(e,t)},async delete(e,t){let r=(0,nn.normalizeGuid)(t,"id");return await(0,Zl.assertSystemFormKind)(e,r,"form"),(0,_t.deleteRecord)(e,"systemforms",r)}};var yg="DisplayConditions";async function b5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Qo.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,nn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,_t.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,Zl.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,_t.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new Qo.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,hg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new Qo.InvalidArgumentError(`form '${s}' produced no owner document`);let h=eN(m,yg),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 Qo.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(yg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let O=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",O),r.everyone)I.appendChild(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,nn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,hg.serializeNode)(m);await(0,gg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let P=await(0,gg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,_t.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,_t.requireEtag)(P,"form",s)}}),e.apiUrl(L))}kt.setFormSecurityRoles=b5;function JS(e){let t=e?.formxml;return typeof t=="string"&&t.includes(YS.GENPAGE_CONTROL_NAME)?t:void 0}function bg(e,t){try{return(0,YS.activeEmbedBindings)(e)}catch(r){throw new Qo.SdkError(kt.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 ZS(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,f5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Qo.SdkError(kt.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 v5(e,t,r,n){var i;(0,_t.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,_t.readEtag)(a);if(s===null||s!==n)throw new Qo.SdkError(_t.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!==""?bg(l,"server"):[];await ZS(e,bg(r,"payload"),u)}function eN(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 w5(e,t){var r,n;let i=(0,nn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.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,hg.parseXmlRoot)(s,"<form/>"),u=eN(l,yg);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)}:{}}}kt.getFormSecurityRoles=w5});var wg=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 C5=Lt(),xt=ye(),ar=se(),E5=dt(),Kt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var A5=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],tN="uxagentproject",rN=new WeakMap;async function lN(e){var t;let r=rN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${tN}')${(0,ar.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,xt.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 Kt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${tN}' \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 rN.set(e,o),o}be.resolveGenPageComponentType=lN;var nN=1,iN=0;async function S5(e,t){let r=(0,ar.normalizeGuid)(t,"solutionId"),n=await lN(e),o=[nN,...A5,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ar.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,C5.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===nN){let f=c.rootcomponentbehavior;(f===iN||f===String(iN))&&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=S5;function N5(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 _5(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Kt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=N5(f)?`solutionid eq ${(0,ar.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ar.odataLiteral)(f)}'`,p=`/solutions${(0,ar.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,xt.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 Kt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Kt.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 Kt.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,ar.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,ar.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=_5;async function T5(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,xt.ensureSuccess)(await(0,xt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,xt.readCreatedId)(i,"publisherid");if(!o)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=T5;async function D5(e,t){var r;let n=(0,ar.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,xt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,xt.readCreatedId)(o,"solutionid");if(!a)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=D5;async function I5(e,t,r){let i=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=I5;async function O5(e,t){var r;let i={ComponentId:(0,ar.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,xt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=O5;async function P5(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ar.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,xt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=P5;async function R5(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,xt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Kt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=R5;async function L5(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 Kt.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:W5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ar.normalizeGuid)(t.importJobId,"importJobId"):(0,E5.newId)()};if(!n)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await uN(e,t.base64,eu,o),{parameters:s,applied:l}=z5(a,n);return i.ComponentParameters=s,(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Kt.withCleanupWarnings)(a,o)}}be.importSolution=L5;var eu="importSolution",oN="getDeploymentSettingsTemplate";async function k5(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Kt.InvalidArgumentError(`${oN}: '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 uN(e,n,oN,i),a=Ad(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=Ad(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,Kt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=k5;function Ad(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 Xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $t(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 uN(e,t,r,n){var i;let a=(i=(0,xt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return x5(a,r)}finally{await $5(e,Xo(a)?a.StageSolutionUploadId:void 0,n)}}async function $5(e,t,r){let n;try{n=(0,ar.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${$t(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,xt.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 or(e,t){return new Kt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===eu?" Nothing was imported.":""}`)}function aN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>Xo(r)&&typeof r.Message=="string"?r.Message:$t(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function x5(e,t){if(!Xo(e))throw or(t,`it holds no StageSolutionResults (${$t(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Kt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${$t(r)}). Missing dependencies: ${aN(e.MissingDependencies)}. Validation: ${aN(e.SolutionValidationResults)}.${t===eu?" 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 or(t,`StageSolutionStatus is ${$t(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw or(t,`SolutionComponentsDetails is not a list (${$t(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!Xo(l))throw or(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw or(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=F5(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw or(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw or(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 or(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=M5(f.get("type"),`${c}.type`,t),b=U5(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 or(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 F5(e,t,r){if(!Xo(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw or(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw or(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw or(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw or(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function M5(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 or(r,`${t} is not a whole number (${$t(e,40)})`)}}function U5(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 or(r,`${t} is not true or false (${$t(e,40)})`)}}var B5=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),q5=["Workflows","CanvasApps","CopilotAgents"],V5=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),G5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function ir(e,t){return new Kt.InvalidArgumentError(`${eu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function W5(e){let t="deploymentSettings";if(!Xo(e))throw ir(t,`must be an object \u2014 the settings file, parsed (it was ${$t(e,40)})`);for(let l of Object.keys(e))if(!B5.has(l))throw ir(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of q5){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw ir(`${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 ir(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw ir(`${t}.${l}`,`must be a list (it was ${$t(u,40)})`);return u.map((c,d)=>{if(!Xo(c))throw ir(`${t}.${l}[${d}]`,`must be an object (it was ${$t(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw ir(c,`must be a non-empty string (it was ${$t(d,40)})`);if(d.trim()!==d)throw ir(c,`must not begin or end with whitespace (it was ${$t(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw ir(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(!V5.has(f))throw ir(`${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 ir(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${$t(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(!G5.has(m))throw ir(`${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 ir(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${$t(f,40)})`);if(f.trim()!==f)throw ir(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${$t(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw ir(`${c}.ConnectorId`,`must be a string (it was ${$t(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function sN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function z5(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=sN(Ad(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=sN(Ad(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Kt.InvalidArgumentError(`${eu}: 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 j5(e,t){let n=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=j5});var hN=v(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.recoverFormCreate=ft.solutionMembershipProblem=ft.formWriteMismatches=ft.validateExistingForm=ft.formExistsAtId=ft.isFormRecordAt=ft.MAIN_FORM_TYPE=void 0;var us=se(),cN=Lt(),dN=wg();ft.MAIN_FORM_TYPE=2;function Sd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nd(e){return e instanceof Error?e.message:String(e)}function Cg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,us.normalizeGuid)(e,"a GUID")===(0,us.normalizeGuid)(t,"a GUID")}catch{return!1}}function Eg(e,t){return Sd(e)&&Cg(e.formid,t)}ft.isFormRecordAt=Eg;async function H5(e,t){try{return Eg((await e()).raw,t)}catch{return!1}}ft.formExistsAtId=H5;function fN(e,t){let r=e.raw;if(!Sd(r))return{problem:"it is not a record"};if(!Eg(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==ft.MAIN_FORM_TYPE)return{problem:`its type is not ${ft.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}}ft.validateExistingForm=fN;function pN(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}ft.formWriteMismatches=pN;async function mN(e,t){let r=e.solutionName;if(r)try{let n=await(0,cN.collectPages)(e,`/solutions${(0,us.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,us.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 Sd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,us.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,us.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${dN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Sd(l)&&l.componenttype===dN.SolutionComponentType.SystemForm&&Cg(l.objectid,t)&&Cg(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 (${Nd(n)})`}}ft.solutionMembershipProblem=mN;async function K5(e){try{return await J5(e)}catch(t){return{refused:`the recovery could not be completed (${Nd(t)})`}}}ft.recoverFormCreate=K5;async function J5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==ft.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 (${Nd(f)})`}}let l=fN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=pN(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 (${Nd(f)})`}}let d=await mN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Td=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.disassociateRecords=Je.associateRecords=Je.createRecordsBulk=Je.upsertRecord=Je.queryAllRecords=Je.queryRecords=Je.getRecord=Je.deleteRecord=Je.updateRecord=Je.createRecord=void 0;var Ag=Lt(),Sn=ye(),Jt=se(),cs=Q(),Jn=cd();function _d(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 Y5(e,t,r){let i=`/${await(0,Jn.resolveEntitySetName)(e,t)}`,o=(0,Sn.ensureSuccess)(await e.post(i,_d(r)),e.apiUrl(i)),a=(0,Sn.readCreatedId)(o,`${t}id`);if(!a)throw new cs.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Je.createRecord=Y5;async function Q5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${i})`;(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a))}Je.updateRecord=Q5;async function X5(e,t,r){let n=(0,Jt.normalizeGuid)(r,"id"),o=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${n})`;(0,Sn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Je.deleteRecord=X5;async function Z5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=await(0,Jn.resolveEntitySetName)(e,t),a=(0,Jt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Sn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new cs.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,Ag.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Je.getRecord=Z5;function e8(e){return e?.fetchXml?(0,Jt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Jt.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 gN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new cs.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 cs.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,Jn.resolveEntitySetName)(e,t)}${e8(r)}`;if(r?.paginate)return(0,Ag.collectPages)(e,o,"queryRecords");let a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new cs.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Ag.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Je.queryRecords=gN;async function t8(e,t,r){return gN(e,t,{...r,paginate:!0})}Je.queryAllRecords=t8;function r8(e){if("id"in e)return`(${(0,Jt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Jt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Jt.assertODataName)(e.key,"alternate key name")}=${t})`}async function n8(e,t,r,n){let i=r8(r),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}${i}`,s=(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a)),l=s.status===201,u=(0,Sn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Jt.normalizeGuid)(r.id,"id"):""),created:l}}Je.upsertRecord=n8;async function i8(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Jn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,..._d(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Sn.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 cs.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Je.createRecordsBulk=i8;async function o8(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=(0,Jt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Jn.resolveEntitySetName)(e,t),s=await(0,Jn.resolveEntitySetName)(e,n.targetEntity),l=(0,Jt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Sn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Je.associateRecords=o8;async function a8(e,t,r,n,i){let o=(0,Jt.normalizeGuid)(r,"id"),a=(0,Jt.normalizeGuid)(i,"targetId"),s=await(0,Jn.resolveEntitySetName)(e,t),l=(0,Jt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Sn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Je.disassociateRecords=a8});var Dd=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.base64ToUtf8=on.base64ToBytes=on.bytesToBase64=on.utf8ToBase64=on.utf8ToBytes=void 0;var Sg=32768,Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function tu(){return globalThis}function yN(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 s8(e){let t="";for(let r=0;r<e.length;r+=Sg)t+=String.fromCharCode(...e.subarray(r,r+Sg));return t}function l8(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+="/":Nr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function u8(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+=Nr[i>>18&63]+Nr[i>>12&63]+Nr[i>>6&63]+Nr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Nr[i>>18&63]}${Nr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Nr[i>>18&63],a=Nr[i>>12&63],s=Nr[i>>6&63];t+=`${o}${a}${s}=`}return t}function c8(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=Nr.indexOf(e[o])<<18|Nr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Nr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Nr.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 d8(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):yN(e)}on.utf8ToBytes=d8;function f8(e){let t=tu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return bN(r?new r().encode(e):yN(e))}on.utf8ToBase64=f8;function bN(e){let t=tu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(s8(e)):u8(e)}on.bytesToBase64=bN;function vN(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=l8(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return c8(r)}on.base64ToBytes=vN;function p8(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>=Sg&&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 m8(e){let t=tu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):p8(vN(e))}on.base64ToUtf8=m8});var AN=v(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.deleteWebResource=Yn.getWebResource=Yn.updateWebResource=Yn.createWebResource=void 0;var h8=Jr(),ru=ye(),Id=se(),g8=Dd(),wN=Q(),y8={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function CN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,g8.utf8ToBase64)(e.content)}async function EN(e,t){return(0,h8.publishWebResourceById)(e,t)}async function b8(e,t){var r;let n=CN(t);if(n===void 0)throw new wN.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:y8[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ru.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ru.readCreatedId)(o,"webresourceid");if(!a)throw new wN.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await EN(e,a),{id:a,name:t.name}}Yn.createWebResource=b8;async function v8(e,t,r){let n=(0,Id.normalizeGuid)(t,"id"),i={},o=CN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ru.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await EN(e,n)}Yn.updateWebResource=v8;async function w8(e,t){var r;let i=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})${(0,Id.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ru.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Yn.getWebResource=w8;async function C8(e,t){let n=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})`;(0,ru.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Yn.deleteWebResource=C8});var Od=v(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.applyAppSettings=Tt.setAppSetting=Tt.readAppSettings=Tt.resolveSettingDefinitions=Tt.APP_SETTING_UNSET=Tt.APP_SETTING_OFF=Tt.APP_SETTING_ON=Tt.HEADER_AND_NAVIGATION_REFRESH=void 0;var ds=ye(),Ii=se();Tt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Tt.APP_SETTING_ON="2";Tt.APP_SETTING_OFF="1";Tt.APP_SETTING_UNSET="0";function _N(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ii.odataQuery)([["$select",e],["$filter",t]])}async function TN(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,Ii.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,ds.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}Tt.resolveSettingDefinitions=TN;async function E8(e,t){var r,n,i,o;let a=(0,Ii.normalizeGuid)(t,"App id"),s=_N("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,ds.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Ii.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,ds.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}:{}}})}Tt.readAppSettings=E8;async function SN(e,t,r){var n,i,o;let a=_N("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ds.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function DN(e,t,r,n){let i=(0,Ii.normalizeGuid)(t,"App id"),a=(await TN(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,Ii.normalizeGuid)(s,"Setting definition id"),u=await SN(e,i,l);if(u)return NN(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 SN(e,i,l)}catch{p=void 0}if(p)return NN(e,p,n);throw f&&(0,ds.ensureSuccess)(f,e.apiUrl(c)),m}Tt.setAppSetting=DN;async function NN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Ii.normalizeGuid)(t.id,"App setting id")})`;return(0,ds.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function A8(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await DN(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}Tt.applyAppSettings=A8});var Rd=v(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.HEADER_NAV_BOOLEAN_RULE=void 0;Pd.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Tg=v(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.compileGenPage=Le.legacyEnumsNeeded=Le.createGenPageTypeScriptLoader=Le.acceptGenPageTypeScript=Le.isLoadableGenPageOutput=Le.runtimeTypesImportSpans=Le.GENPAGE_RUNTIME_TYPES_END=Le.GENPAGE_RUNTIME_TYPES_BEGIN=Le.GENPAGE_TYPESCRIPT_VERSION=void 0;var fs=Q();Le.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Le.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Le.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Nn="./RuntimeTypes",S8="'\"`",IN=/\s/;function N8(e){return e===10||e===13||e===8232||e===8233}function _8(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 LN(e){let t=[],r=Nn.length;for(let l=e.indexOf(Nn);l!==-1;l=e.indexOf(Nn,l+1)){let u=l-1;u>=0&&S8.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&&IN.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&&IN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Le.runtimeTypesImportSpans=LN;var T8=/\b(?:import\s*['"]|export\s)/;function D8(e){let t=_8(/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&&!N8(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function I8(e){return e!==void 0&&e!==""&&(T8.test(e)||D8(e))}Le.isLoadableGenPageOutput=I8;var ON=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function kN(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?ON.filter(s=>typeof n?.[s]!="function"):[...ON];if(!n||i.length>0)throw new fs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Le.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new fs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Le.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Le.acceptGenPageTypeScript=kN;function O8(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(kN).catch(r=>{throw t=void 0,r instanceof fs.SdkError?r:new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Le.createGenPageTypeScriptLoader=O8;var $N=e=>`${e.kind}:${e.pos}:${e.end}`;function P8(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add($N(o)),e.forEachChild(i,n)};return n(r),r}}function _g(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var R8=2301;function PN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:_g(e),reportDiagnostics:!0,...r?{transformers:{after:[P8(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 RN=e=>e.startsWith(".")||e.startsWith("/"),Ld={line:1,column:1};function Ng(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):Ld},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 Ld}}}function L8(e,t,r,n){var i,o;let a=[],s=Ng(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 E=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;E===Nn?l(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&RN(E)&&c(s.statement(E,"export"),E);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Nn){RN(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(E=>m.add(E.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let E=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,P=s.element(h,E);S!==E?l(P,d,`'${S} as ${E}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(E)||l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(Ld,"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 xN(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===R8&&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===Nn},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 k8(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=xN(e,t,_g(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($N(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 $8(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===Nn)}function FN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Nn).map(r=>r.getStart(t))}function x8(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=FN(e,r),i=new Set(n),o,a="",s=0;for(let l of LN(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 F8(e,t,r){let n=new Set(FN(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 Ld}function MN(e,t,r){if(!r||r.size===0)return[];let n=xN(e,t,{..._g(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===Nn&&((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))}Le.legacyEnumsNeeded=MN;function M8(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 U8(e,t,r,n){var i;let o=new Set,a=PN(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=M8(r,n,MN(e,l,n)),c=[...L8(e,l,s,u),...k8(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=PN(e,u.text);if(d.diagnostics.length>0)throw new fs.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=x8(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...Ng(e,s).statement(Nn,"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({...F8(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&&$8(e,m)&&c.push({...Ng(e,s).statement(Nn,"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:[Le.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Le.GENPAGE_RUNTIME_TYPES_END,m].join(`-`),diagnostics:c}}Re.compileGenPage=Iz});var w0=v(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.isFailureAfterPrimaryWrite=ks.failedAfterPrimaryWrite=void 0;var yT=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Oz(e){return typeof e=="object"&&e!==null&&(e[yT]=!0),e}ks.failedAfterPrimaryWrite=Oz;function Pz(e){return typeof e=="object"&&e!==null&&e[yT]===!0}ks.isFailureAfterPrimaryWrite=Pz});var Af=v(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.appApi=li.deleteAppResolvingOnce=li.mainFormSetShapeIssues=li.unpublishedAppModulesQuery=void 0;var $s=Tt(),Rz=T0(),Lz=jg(),bT=jr(),kz=tf(),$z=w0(),ge=fe(),Ae=oe(),E0=ct(),PT=Es(),_e=Q(),xz=(0,Ae.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),A0="appmoduleid,name,uniquename,description,aiappdescription";function wf(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",e],["$filter",t],["$top",r]])}li.unpublishedAppModulesQuery=wf;function S0(e,t){return wf(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Cf(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function _u(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function Fz(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Ef(e,t){if(typeof e!="string")return!1;try{return(0,Ae.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ma(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function Mz(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function RT(e,t){var r,n;let i=u=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ae.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ae.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function Uz(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,Ae.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var vT="627090ff-40a3-4053-8790-584edc5be201";function Gi(e){return e instanceof Error?e.message:String(e)}async function Bz(e,t){var r;try{let n=`/roles${(0,Ae.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${vT}`]])}`,i=await(0,$s.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${vT}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,ge.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Gi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function qz(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,$s.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Gi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ae.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ae.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ae.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ae.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ae.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var wT=new WeakMap;async function Vz(e,t){let r=wT.get(e);r||(r=new Map,wT.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Gz(e,t);return i&&r.set(t,i),i}async function CT(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function Gz(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ae.odataPathLiteral)(t)}')${(0,Ae.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function ET(e,t,r){let n=[],i=ma(t.entities),o=4,a=await CT(i,o,g=>Vz(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new _e.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of ma(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of ma(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of ma(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of ma(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await CT(i,o,g=>qz(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...ma(t.components.forms),...ma(t.components.dashboards)].map(Xr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let C of w.allowed)h.has(C)||(h.add(C),u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));else for(let C of g.forms)u.has(C)||(u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));for(let C of g.views)c.has(C)||(c.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:C}));for(let C of g.charts)d.has(C)||(d.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:C}))}),{components:n,tables:l,warnings:p}}function Xr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var _0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N0="/components/mainFormsByTable",AT=50;function LT(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function kT(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:N0,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${N0}/${LT(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!_0.test(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Xr(c))})}return r}li.mainFormSetShapeIssues=kT;async function ST(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=kT(n,t.entities);if(i.length>0)throw new _e.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Xr(h.formid)),Number(h.formactivationstate)===1&&m.add(Xr(h.formid)));let p=u.map(Xr);p.forEach((h,g)=>{let b=`${N0}/${LT(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Xr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new _e.ValidationError("app",r,o);return a}async function Wz(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(wf("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!_0.test(Xr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Xr(l)}}function bf(e,t){let r;return()=>r??(r=Wz(e,t))}async function $T(e,t,r,n=bf(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,$s.collectPages)(e,`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Xr(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>Xr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Gi(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!_0.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=AT){let p=u.slice(m,m+AT);try{let h=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Xr(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Gi(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function zz(e,t,r,n){let i=await $T(e,t,r,n);if(i.kind==="inconclusive")throw new _e.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new _e.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function jz(e,t,r,n){let i;try{i=await $T(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Gi(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function NT(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,ge.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function _T(e,t,r,n=bf(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new _e.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function Hz(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await Jz(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Gi(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Gi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Gi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:FT(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await MT(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function Kz(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function Jz(e,t,r){var n,i,o;let a=Cf(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function Yz(e,t){var r;let n;try{n=await e.get(wf("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Ef(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function xT(e,t){var r;let n=(0,Ae.normalizeGuid)(t,"id"),i=b=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${xz}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await Yz(e,n);if(b.kind!=="draft")return i(`reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,ge.readEtag)(a)},c=await RT(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ae.normalizeGuid)(c,"sitemapId"),f=await vf(e,d),m=Cf(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=_u(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Ef(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function Qz(e,t,r){let n=(0,Ae.normalizeGuid)(t,"id"),i=await xT(e,n);await r?.(i.sitemapXml),await BT(e,n,i)}li.deleteAppResolvingOnce=Qz;async function Xz(e,t){let r=await MT(e,t);if(r.kind!=="deleted")throw r.error}function FT(e,t){try{return(0,ge.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return UT(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function Zz(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,PT.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,ge.namesAppSearchIndexRace)(i.text))}async function MT(e,t){let r=`batch_${(0,E0.newId)()}`,n=`changeset_${(0,E0.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r+`),diagnostics:c}}Le.compileGenPage=U8});var Dg=v(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.isFailureAfterPrimaryWrite=ps.failedAfterPrimaryWrite=void 0;var UN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function B8(e){return typeof e=="object"&&e!==null&&(e[UN]=!0),e}ps.failedAfterPrimaryWrite=B8;function q8(e){return typeof e=="object"&&e!==null&&e[UN]===!0}ps.isFailureAfterPrimaryWrite=q8});var Ud=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.appApi=Qn.deleteAppResolvingOnce=Qn.mainFormSetShapeIssues=Qn.unpublishedAppModulesQuery=void 0;var ms=Lt(),V8=$g(),G8=dg(),BN=Jr(),W8=Od(),z8=Dg(),he=ye(),Ne=se(),Og=dt(),e_=Wl(),Se=Q(),j8=(0,Ne.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Pg="appmoduleid,name,uniquename,description,aiappdescription";function xd(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Qn.unpublishedAppModulesQuery=xd;function Rg(e,t){return xd(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Fd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function nu(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function H8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Md(e,t){if(typeof e!="string")return!1;try{return(0,Ne.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Zo(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function K8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function t_(e,t){var r,n;let i=u=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ne.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ne.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 J8(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,Ne.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let 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 qN="627090ff-40a3-4053-8790-584edc5be201";function Oi(e){return e instanceof Error?e.message:String(e)}async function Y8(e,t){var r;try{let n=`/roles${(0,Ne.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${qN}`]])}`,i=await(0,ms.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${qN}) 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,he.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 (${Oi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function Q8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,ms.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Oi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ne.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ne.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ne.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ne.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ne.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ne.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var VN=new WeakMap;async function X8(e,t){let r=VN.get(e);r||(r=new Map,VN.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Z8(e,t);return i&&r.set(t,i),i}async function GN(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 Z8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ne.odataPathLiteral)(t)}')${(0,Ne.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function WN(e,t,r){let n=[],i=Zo(t.entities),o=4,a=await GN(i,o,g=>X8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new Se.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of Zo(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of Zo(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of Zo(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of Zo(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 GN(i,o,g=>Q8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...Zo(t.components.forms),...Zo(t.components.dashboards)].map(Vr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let E of w.allowed)h.has(E)||(h.add(E),u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)u.has(E)||(u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:n,tables:l,warnings:p}}function Vr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var kg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Lg="/components/mainFormsByTable",zN=50;function r_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function n_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Lg,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=`${Lg}/${r_(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"||!kg.test(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Vr(c))})}return r}Qn.mainFormSetShapeIssues=n_;async function jN(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=n_(n,t.entities);if(i.length>0)throw new Se.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ne.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(Vr(h.formid)),Number(h.formactivationstate)===1&&m.add(Vr(h.formid)));let p=u.map(Vr);p.forEach((h,g)=>{let b=`${Lg}/${r_(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=Vr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new Se.ValidationError("app",r,o);return a}async function eW(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(xd("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"||!kg.test(Vr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Vr(l)}}function kd(e,t){let r;return()=>r??(r=eW(e,t))}async function i_(e,t,r,n=kd(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,ms.collectPages)(e,`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Vr(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=>Vr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Oi(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=>!kg.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+=zN){let p=u.slice(m,m+zN);try{let h=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.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=Vr(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 (${Oi(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 tW(e,t,r,n){let i=await i_(e,t,r,n);if(i.kind==="inconclusive")throw new Se.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new Se.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function rW(e,t,r,n){let i;try{i=await i_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Oi(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 HN(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,he.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function KN(e,t,r,n=kd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new Se.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function nW(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await oW(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Oi(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 (${Oi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Oi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,he.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:a_(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await s_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function iW(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function oW(e,t,r){var n,i,o;let a=Fd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function aW(e,t){var r;let n;try{n=await e.get(xd("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!Md(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 o_(e,t){var r;let n=(0,Ne.normalizeGuid)(t,"id"),i=b=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${j8}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await aW(e,n);if(b.kind!=="draft")return i(`reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,he.readEtag)(a)},c=await t_(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ne.normalizeGuid)(c,"sitemapId"),f=await $d(e,d),m=Fd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=nu(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Md(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function sW(e,t,r){let n=(0,Ne.normalizeGuid)(t,"id"),i=await o_(e,n);await r?.(i.sitemapXml),await u_(e,n,i)}Qn.deleteAppResolvingOnce=sW;async function lW(e,t){let r=await s_(e,t);if(r.kind!=="deleted")throw r.error}function a_(e,t){try{return(0,he.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return l_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function uW(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,e_.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,he.namesAppSearchIndexRace)(i.text))}async function s_(e,t){let r=`batch_${(0,Og.newId)()}`,n=`changeset_${(0,Og.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r-`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,ge.resendWhile)(m=>Zz(m,s),()=>e.postBatch(o,r),ge.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=FT(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,PT.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new _e.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function vf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,ge.readEtag)(r)}catch{return null}}async function TT(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,ge.ensureSuccess)(n,e.apiUrl(r)),(0,ge.readEtag)(n)}async function C0(e,t,r,n){if(!n)return null;let i=await vf(e,t);if(!i)return null;try{let o=await e.get(Cf(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=_u(o);return!a||!Ef(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function UT(e){return e>=400&&e<500&&e!==408&&e!==429}function DT(e,t,r){if(!e)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function BT(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:DT(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await ej(e,n,i);return}if(!e.supportsAtomicBatch)throw new _e.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await Xz(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:DT(r.sitemapEtag,t,"sitemap")}])}async function ej(e,t,r){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function IT(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Rz.collectGenPageIds)(t))]}catch(i){throw new _e.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Gi(i)}).`)}if(r.length===0)return;let n=await(0,Lz.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new _e.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function tj(e){var t,r;if(e.status!==400)return!1;let n=e.body;return String((r=(t=n?.error)===null||t===void 0?void 0:t.message)!==null&&r!==void 0?r:"").includes("retrieval of version numbers failed")}async function OT(e,t,r){var n;let i=(0,Ae.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await TT(e,i):null,s=S0(A0,i),l=(0,ge.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=_u(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new _e.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await RT(e,u.uniquename),d=c?(0,Ae.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await vf(e,d));let p=Cf(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,ge.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=_u(h),b=w=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Ef(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await vf(e,d))}o||(a=await TT(e,i));let m=a??Fz(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ae.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}li.appApi={get(e,t){return OT(e,t,"tokens-first")},readContentThenToken(e,t){return OT(e,t,"content-first")},async list(e,t){let r=S0(A0);return(await(0,$s.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;await IT(e,n.sitemapxml);let i=await ST(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await Uz(e),a=n.iconWebResourceId||o?.id;if(!a)throw new _e.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||Mz(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,ge.ensureSuccess)(await(0,ge.resendDeadlockVictim)(()=>e.post(c,(0,ge.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,ge.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ae.normalizeGuid)(n.sitemapId,"sitemapId"):(0,E0.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let O="/sitemaps",L=(0,ge.echoWrite)("sitemapid"),I=await e.post(`${O}${L.query}`,{sitemapid:b,sitemapnameunique:l,...C},L.options);w=UT(I.status);let D=(0,ge.ensureSuccess)(I,e.apiUrl(O));p=(0,ge.readEtag)(D),m=p??await C0(e,b,C,l);let P=await ET(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await NT(e,f,x);let K=bf(e,f);await _T(e,f,P.tables,K),i&&await zz(e,f,i,K);let Le=await Bz(e,f);Le&&h.push(Le),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,kz.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,bT.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let L=await Hz(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,$z.failedAfterPrimaryWrite)(Kz(O,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let O=await e.get(`/appmodules(${f})?$select=appmoduleid`);O.status>=200&&O.status<300&&(S=(0,ge.readEtag)(O))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,f,m,p;let h=r,g=(0,Ae.normalizeGuid)(t,"id");if(await IT(e,h.sitemapxml),!h.sitemapId)throw new _e.ValidationError("app",g,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${g}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${g}'), clear the local copy with deleteArtifact('app', '${g}'), then author the app again and push.`}]);let b=(0,Ae.normalizeGuid)(h.sitemapId,"sitemapId");if(!(0,ge.isVersionToken)(n))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"no concurrency token is held for its sitemap row"}, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the app and re-apply the change.`);let w=await ST(e,h,g),C=await ET(e,h,w),S=`/appmodules(${g})`,O=(a=o?.[g])!==null&&a!==void 0?a:null,L=!0,I;try{let Bt=S0(A0,g),Ni=await e.get(Bt);if(Ni.status>=200&&Ni.status<300){let Ha=(s=_u(Ni))!==null&&s!==void 0?s:{};I=typeof Ha.uniquename=="string"&&Ha.uniquename?Ha.uniquename:void 0,L=String((l=Ha.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ha.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((f=Ha.aiappdescription)!==null&&f!==void 0?f:"")!==String(h.appModuleAiDescription)}}catch{}let D=O;if(L){if(!(0,ge.isVersionToken)(O))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${O?`the concurrency token held for its appmodule header ('${O}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${g}', { overwrite: true })) and re-apply the change.`);let Bt=(0,ge.echoWrite)("appmoduleid",{"If-Match":O}),Ni=await e.patch(`${S}${Bt.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Bt.options);if(tj(Ni))throw new _e.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${g}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,ge.ensureSuccess)(Ni,e.apiUrl(S)),D=(0,ge.readEtag)(Ni)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},x=I||h.appModuleUniqueName||void 0,K=(0,ge.echoWrite)("sitemapid",{"If-Match":n}),Le=`/sitemaps(${b})`,lr;try{lr=(0,ge.ensureSuccess)(await e.patch(`${Le}${K.query}`,{...P},K.options),e.apiUrl(Le))}catch(Bt){throw(0,_e.withPartialTokens)(Bt,{siblingEtags:{[g]:D}})}let Ge=[...C.warnings],Ut=bf(e,g);try{await NT(e,g,C.components),await _T(e,g,C.tables,Ut)}catch(Bt){Ge.push(`App '${g}': one or more components were not pinned (${Bt.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Ge.push(...await jz(e,g,w,Ut));let de={kind:"notRequested"},Ke=D,ur=(m=(0,ge.readEtag)(lr))!==null&&m!==void 0?m:await C0(e,b,P,x);if(h.published===!0){try{await(0,bT.publishAppModule)(e,g),de={kind:"submitted"}}catch(Bt){de={kind:"failed",error:Bt},Ge.push(`App '${g}': saved, but publishing failed (${Bt.message}). The app remains unpublished; re-push to retry.`)}if(de.kind==="submitted"){Ke=null;try{let Bt=await e.get(`/appmodules(${g})?$select=appmoduleid`);Bt.status>=200&&Bt.status<300&&(Ke=(0,ge.readEtag)(Bt)),ur=(p=await C0(e,b,P,x))!==null&&p!==void 0?p:ur}catch{}}}return{id:g,etag:ur,siblingEtags:{[g]:Ke},publish:de,...Ge.length>0?{warnings:Ge}:{}}},async delete(e,t){let r=(0,Ae.normalizeGuid)(t,"id");await BT(e,r,await xT(e,r))}}});var T0=v(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.deleteAppCascade=xs.collectGenPageIds=void 0;var rj=Af(),nj=Q(),D0=oe(),ij=ys();function qT(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new ij.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new nj.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,D0.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}xs.collectGenPageIds=qT;async function oj(e,t,r){let n=(0,D0.normalizeGuid)(t,"appModuleId");(0,D0.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,rj.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...qT(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}xs.deleteAppCascade=oj});var VT={};nn(VT,{Guid:()=>U});var U,vt=k(()=>{"use strict";U=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var q,rr=k(()=>{"use strict";dt();q=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!R.IsNullOrUndefined(r))for(let i of r.getKeys())n+=" "+this.ToSnakeCase(i)+'="'+r.getValue(i)+'"';return n+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return R.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,r){return t===r?!0:!t||!r?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(r).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(n=>(n.charAt(0)!=="{"&&(n="{"+n),n.charAt(n.length-1)!=="}"&&(n=n+"}"),n)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(n=>{let i;return n.charAt(0)==="{"&&(i=n.substr(1,n.length-1)),n.charAt(n.length-1)==="}"&&(i=i.substr(0,n.length-2)),i}):t}}});var GT={};nn(GT,{ScriptUtilities:()=>R});var R,dt=k(()=>{"use strict";vt();rr();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:q.IsTrue(n)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let r=new Set;return e.getAllUniqueTagNamesHelper(t,r),r}static getAllUniqueTagNamesHelper(t,r){if(t.nodeType===Node.ELEMENT_NODE&&(r.add(t.tagName),t.hasChildNodes()))for(let n=0;n<t.children.length;n++)this.getAllUniqueTagNamesHelper(t.children.item(n),r)}}});var Sf,Nf,ha,_f,I0,Tf,O0=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Sf||(Sf={}));Nf=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ha=class extends Nf{key;oldValue;newValue;constructor(t,r,n,i){super(Sf.FormElementNodeChange,t),this.key=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},_f=class extends Nf{property;oldValue;newValue;constructor(t,r,n,i){super(Sf.FormElementAttributeChange,t),this.property=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},I0=class{changeSet;reversedChangeSet;constructor(t){this.changeSet=t,this.changeSet&&(this.reversedChangeSet=this.changeSet.slice().reverse())}length(){return this.changeSet?this.changeSet.length:0}apply(){this.changeSet&&this.changeSet.length>0&&this.changeSet.forEach(t=>{t.apply()})}revert(){this.reversedChangeSet&&this.reversedChangeSet.length>0&&this.reversedChangeSet.forEach(t=>{t.revert()})}},Tf=class{isTracking;_trackedChanges;_trackedChangeSets;constructor(t=!1){this.isTracking=t,this._trackedChanges=[],this._trackedChangeSets=[]}addChange(t){this.isTracking&&this._trackedChanges.push(t)}collectChanges(){let t=new I0(this._trackedChanges.slice());return this._trackedChanges=[],t}pushChangeSet(t){this._trackedChangeSets.push(t)}popChangeSet(){if(this._trackedChangeSets?.length>0)return this._trackedChangeSets.pop()}getChangeSets(){return this._trackedChangeSets}}});var WT={};nn(WT,{ChartGridMode:()=>hn,ColumnLayoutWidths:()=>cj,ComponentCategory:()=>If,ComponentType:()=>P0,ControlLayoutTypes:()=>M0,DisplayConditionsInfo:()=>lj,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>L0,EntityAttributeProperty:()=>k0,EventType:()=>Tu,FormActivationState:()=>F0,FormCanvasServiceScope:()=>Ej,FormDesignerSideBarTab:()=>R0,FormPresentation:()=>$0,FormState:()=>Df,FormType:()=>wt,HeaderDensityType:()=>Do,LookUpTable:()=>ui,MORE_TAB_PREFIX:()=>fj,NavBarChildElementType:()=>x0,PREVIEW_ID_HEADER_FLYOUT:()=>gj,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>bj,PREVIEW_ID_NAVIGATION_AREA:()=>mj,PREVIEW_ID_QUICKCREATE_ROOT:()=>wj,PREVIEW_ID_TAB:()=>vj,PREVIEW_ID_TAB_LIST:()=>yj,PREVIEW_ID_TAB_PANEL:()=>hj,PropertyModelKeys:()=>q0,PropertyModelSectionKeys:()=>dj,RELATED_TAB_ID:()=>V0,RELATED_TAB_PREFIX:()=>pj,SectionDefaultProperties:()=>uj,SectionLayoutTypes:()=>je,TabContentType:()=>U0,TabDefaultProperties:()=>Io,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>Cj,UnboundControlPropertyKeys:()=>B0,compositeAddressFields:()=>sj,compositeFieldNames:()=>Zr,compositeFields:()=>aj});var wt,P0,R0,E,y,L0,Zr,aj,sj,k0,ui,Df,Do,$0,lj,x0,F0,ze,uj,Io,je,M0,U0,cj,B0,q0,dj,Tu,hn,V0,fj,pj,mj,hj,gj,yj,bj,vj,wj,Cj,If,Ej,le=k(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(wt||(wt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(P0||(P0={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(R0||(R0={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(E||(E={}));y={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})(L0||(L0={}));Zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},aj=[Zr.fullname,Zr.yomifullname,Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto],sj=[Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(k0||(k0={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(ui||(ui={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Df||(Df={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Do||(Do={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})($0||($0={}));lj={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(x0||(x0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(F0||(F0={}));(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN_EQUAL=1]="TWO_COLUMN_EQUAL",e[e.TWO_COLUMN_WIDER_LEFT=2]="TWO_COLUMN_WIDER_LEFT",e[e.TWO_COLUMN_WIDER_RIGHT=3]="TWO_COLUMN_WIDER_RIGHT",e[e.TWO_COLUMN_CUSTOM_LAYOUT=4]="TWO_COLUMN_CUSTOM_LAYOUT",e[e.THREE_COLUMN_EQUAL=5]="THREE_COLUMN_EQUAL",e[e.THREE_COLUMN_WIDER_MID=6]="THREE_COLUMN_WIDER_MID",e[e.THREE_COLUMN_CUSTOM_LAYOUT=7]="THREE_COLUMN_CUSTOM_LAYOUT"})(ze||(ze={}));uj={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},Io={namePrefix:"tab_",ShowLabel:"true",LockLevel:"0",IsUserDefined:"0"};(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN=1]="TWO_COLUMN",e[e.THREE_COLUMN=2]="THREE_COLUMN",e[e.FOUR_COLUMN=3]="FOUR_COLUMN",e[e.REFERENCE_PANEL=4]="REFERENCE_PANEL"})(je||(je={}));(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.NOTES=8]="NOTES",e[e.SOCIAL_INSIGHTS=9]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=10]="KB_SEARCH",e[e.INTERACTION_WALL=11]="INTERACTION_WALL",e[e.ACI_CONTROL=12]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=13]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=14]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=15]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=16]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=17]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=18]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=19]="PRED_LEAD_SCORING"})(M0||(M0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(U0||(U0={}));cj={ONE_COLUMN:"100",TWO_COLUMN:"50",THREE_COLUMN:"33.33",FOUR_COLUMN:"25"};(function(e){e.minValue="MinValue",e.maxValue="MaxValue",e.precision="Precision",e.maxLength="MaxLength",e.entityLogicalName="EntityLogicalName",e.defaultViewId="DefaultViewId",e.optionSetDefaultValue="DefaultValue",e.optionSetId="OptionSetId"})(B0||(B0={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(q0||(q0={}));dj={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})(Tu||(Tu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(hn||(hn={}));V0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",fj="more_tab_",pj="related_tab_",mj="preview_id_navigation_area",hj="tab-section",gj="headerFieldsFlyout",yj="tablist",bj="header_overflowButton",vj="tab",wj="quickCreateRoot",Cj={defaultVisibility:"Default visibility"};(function(e){e.input="input",e.layout="layout",e.grid="grid",e.relatedData="relatedData",e.display="display",e.powerbi="powerbi",e.artificialIntelligence="artificialIntelligence",e.media="media",e.collaboration="collaboration",e.more="more",e.test="test",e.popular="popular"})(If||(If={}));Ej="CellCanvasServiceScope"});var zT={};nn(zT,{Attribute:()=>Of,FormElementNode:()=>re});var Of,re,kt=k(()=>{"use strict";dt();rr();O0();le();vt();Of=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${U.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(E.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Of(t,r))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let r=this.properties.findIndex(n=>n.key===t);r>-1&&this.properties.splice(r,1)})}trackPropertyCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.properties.slice();t(),r.addChange(new ha(this,"properties",n,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.childrenNodes.slice();t(),r.addChange(new ha(this,"childrenNodes",n,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.parentNode;if(t(),n===this.parentNode)return;r.addChange(new ha(this,"parentNode",n,this.parentNode))}else t()}trackAttributeValueChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=t.value;if(i===r)return;t.value=r,n.addChange(new _f(this,t,i,r))}else t.value=r}trackObjectPropertyChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=this[t];if(i===r)return;this[t]=r,n.addChange(new ha(this,t,i,r))}else this[t]=r}setProperty(t,r){if(!t)throw new Error("Invalid property key");let n=this.properties.find(i=>i.key===t);n?this.trackAttributeValueChange(n,r):this.addProperty(t,r)}addProperty(t,r){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,r)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,r){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.IsNullOrUndefined(t))return-1;for(let r=0;r<this.childrenNodes.length;r++)if(this.childrenNodes[r]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1)}),r;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:q.EmptyString}updateChild(t,r){let n=this.childrenNodes.indexOf(t);return n>-1?(r.trackParentNodeChange(()=>{r.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1,r)}),!0):!1}getAncestor(t){let r=this.getParent(),n=this.getParentType();for(;r;){if(n===t)return r;n=r.getParentType(),r=r.getParent()}return null}deleteFirstGrandChildOfName(t,r){return this.getChildren(t)[0].deleteChild(r)}deleteChildren(t,r){r=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case E.formCell:let t=this.getAncestor(E.formSection);return t||(t=this.getAncestor(E.formHeader),t)||(t=this.getAncestor(E.formFooter),t)?t:null;case E.formSection:return this.getAncestor(E.formTab);case E.formTab:return this.getAncestor(E.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(E.form);return t?t.changeTracker():null}}});var jT={};nn(jT,{ControlClassId:()=>N,ControlNamePrefixes:()=>Pf,getControlDisplayNames:()=>Aj});function Aj(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Pf,ga=k(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(N||(N={}));Pf={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ya=v((Ade,KT)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),HT=function(){return Du};Object.setPrototypeOf(HT,Du);KT.exports=HT});var hr,Wi,JT,YT,Fs=k(()=>{"use strict";hr="cds-designer-models",Wi="FormCustomControl",JT="FormCell",YT="Form"});var ba,G0=k(()=>{"use strict";su();le();ba=class e{static lockedFieldCount=new dr;static dependencyFieldCount=new dr;static getNecessaryLookUpTable(t){switch(t){case ui.DependencyFieldTable:return e.dependencyFieldCount;case ui.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case ui.DependencyFieldTable:e.dependencyFieldCount=new dr;case ui.LockedFieldTable:e.lockedFieldCount=new dr}}}});var Rf,QT=k(()=>{"use strict";vt();dt();le();kt();Rf=class extends re{constructor(t){super(E.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(E.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});function zi(){return ci||(ci=window._makerConfig,ci&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ci={...ci,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ci?.region==="prod"&&(ci={endpoints:{eu:{ch:{graphql:"https://graph-make.ch-cm001.gateway.prod.cm.powerapps.com/"},de:{graphql:"https://graph-make.de-cm001.gateway.prod.cm.powerapps.com/"},fr:{graphql:"https://graph-make.fr-cm001.gateway.prod.cm.powerapps.com/"},no:{graphql:"https://graph-make.no-cm001.gateway.prod.cm.powerapps.com/"},default:{graphql:"https://graph-make.eu-cm001.gateway.prod.cm.powerapps.com/"}}},...ci}),ci||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ci,Lf=k(()=>{"use strict";});function XT(e,t,r){if(!e)return kf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),kf.add("")),!1;if(e){if(e=e.toLowerCase(),kf.has(e))return!1;if(!(e in t))return window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoNonExistent",eventInfo:{missinggeo:e,parent:r}}),kf.add(e),!1}return!0}function Sj(e){return XT(e,W0,"Location dictionary")?W0[e.toLowerCase()]:"us"}function Nj(){let e=zi().location.toLowerCase();return XT(e,W0,"Current location dictionary")?e:"us"}var kf,W0,xde,ZT=k(()=>{"use strict";Lf();kf=new Set,W0={cae:"ae",nae:"ae",eas:"as",seas:"as",eau:"au",seau:"au",sbr:"br",cca:"ca",eca:"ca",nch:"ch",wch:"ch",nde:"de",wcde:"de",neu:"eu",weu:"eu",cfr:"fr",sfr:"fr",cin:"in",sin:"in",ejp:"jp",wjp:"jp",suk:"uk",wuk:"uk",eus:"us",wus:"us",cus:"us",ude:"us",udc:"us",ugtx:"us",ugva:"us",eus2:"us",wus2:"us",nza:"za",wza:"za",cne2:"cn",cnn2:"cn",skr:"kr",ckr:"kr",eno:"no",wno:"no",wrx:"us",erx:"us",wex:"us",eex:"us",unitedstates:"us",europe:"eu",asia:"as",australia:"au",japan:"jp",canada:"ca",india:"in",italy:"it",unitedstatesfirstrelease:"us",unitedkingdom:"uk",southamerica:"br",france:"fr",unitedarabemirates:"ae",germany:"de",sweden:"se",switzerland:"ch",korea:"kr",norway:"no",usgov:"us",usgovhigh:"us",usdod:"us",china:"cn",usnat:"us",ussec:"us",southafrica:"za",singapore:"sg",newzealand:"nz",poland:"pl",qatar:"qa",as:"as",au:"au",ca:"ca",in:"in",jp:"jp",kr:"kr",nz:"nz",ae:"ae",qa:"qa",us:"us",uk:"uk",eu:"eu",de:"de",ch:"ch",no:"no",fr:"fr",se:"se",it:"it",pl:"pl",be:"eu",bel:"eu",gr:"eu",grc:"eu",lt:"eu",ltu:"eu",pt:"eu",prt:"eu",bg:"eu",bgr:"eu",es:"eu",esp:"eu",lu:"eu",lux:"eu",ro:"eu",rou:"eu",cz:"eu",cze:"eu",hu:"eu",hun:"eu",si:"eu",svn:"eu",dk:"eu",dnk:"eu",hr:"eu",hrv:"eu",mt:"eu",mlt:"eu",sk:"eu",svk:"eu",nit:"it",nl:"eu",nld:"eu",fi:"eu",fin:"eu",ee:"eu",est:"eu",cy:"eu",cyp:"eu",at:"eu",aut:"eu",swe:"se",cse:"se",ie:"eu",irl:"eu",lv:"eu",lva:"eu",cpl:"pl",nnz:"nz",cqa:"qa",sg:"sg",br:"br",za:"za",sa:"za"};xde=Sj(Nj())});var Y,Mde,eD=k(()=>{"use strict";Y={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},Mde={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var tD=k(()=>{"use strict";Lf();});var Iu=k(()=>{"use strict";Lf();ZT();eD();tD();});function Ou(e,t){return rD?rD.isOverridden(e,t):{overridden:!1}}var rD,Pu=k(()=>{"use strict";});var z0=k(()=>{"use strict";Iu();Pu();});function _j(e,t){let{region:r}=zi();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Ou(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Tj(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function Tj(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function Dj(e){let t=e.packageName;if($f.has(t)){let r=`settings has already been created for this package ${t}`;throw console.error(r),new Error(r)}if(Object.keys(e.settings).some(r=>H0(t,r))){let r=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.settings).forEach(r=>{if(Object.keys(e.settings[r].values).filter(i=>i!=="default").some(i=>!Ff(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Ru(e){Dj(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:_j(e,r)}}),$f.set(e.packageName,e),Object.defineProperties({},t)}function j0(e,t){return $f.has(e)?!!$f.get(e).settings[t]:!1}var $f,xf=k(()=>{"use strict";Iu();Pu();K0();Lu();$f=new Map});function nD(e,t){let{region:r}=zi();return()=>{let n=Ou(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function Ij(e){let t=e.packageName;if(Mf.has(t)){let r="feature gates has already been created for this package";throw console.error(r),new Error(r)}if(Object.keys(e.features).some(r=>j0(t,r))){let r=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.features).forEach(r=>{if(Object.keys(e.features[r].enabledFor).some(i=>!Ff(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function J0(e){Ij(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:nD(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:nD(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Mf.set(e.packageName,e),Object.defineProperties(r,t)}function H0(e,t){return Mf.has(e)?!!Mf.get(e).features[t]:!1}var Mf,K0=k(()=>{"use strict";Iu();Lu();Pu();xf();Mf=new Map});var oD=v((ufe,iD)=>{"use strict";iD.exports=function(t,r){if(r=r.split(":")[0],t=+t,!t)return!1;switch(r){case"http":case"ws":return t!==80;case"https":case"wss":return t!==443;case"ftp":return t!==21;case"gopher":return t!==70;case"file":return!1}return t!==0}});var lD=v(Y0=>{"use strict";var Oj=Object.prototype.hasOwnProperty,Pj;function aD(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function sD(e){try{return encodeURIComponent(e)}catch{return null}}function Rj(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=aD(n[1]),o=aD(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function Lj(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(Oj.call(e,i)){if(n=e[i],!n&&(n===null||n===Pj||isNaN(n))&&(n=""),i=sD(i),n=sD(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Y0.stringify=Lj;Y0.parse=Rj});var Z0=v((dfe,mD)=>{"use strict";var cD=oD(),Uf=lD(),dD=/[\n\r\t]/g,kj=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,$j=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,xj=/^[a-zA-Z]:/,Fj=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function X0(e){return(e||"").toString().replace(Fj,"")}var Q0=[["#","hash"],["?","query"],function(t,r){return di(r.protocol)?t.replace(/\\/g,"/"):t},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],uD={hash:1,query:1};function fD(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,o;if(e.protocol==="blob:")n=new fi(unescape(e.pathname),{});else if(i==="string"){n=new fi(e,{});for(o in uD)delete n[o]}else if(i==="object"){for(o in e)o in uD||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=kj.test(e.href))}return n}function di(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function pD(e,t){e=X0(e),e=e.replace(dD,""),t=t||{};var r=$j.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):di(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&di(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||di(n),slashesCount:a,rest:s}}function Mj(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function fi(e,t,r){if(e=X0(e),e=e.replace(dD,""),!(this instanceof fi))return new fi(e,t,r);var n,i,o,a,s,l,u=Q0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Uf.parse),t=fD(t),i=pD(e||"",t),n=!i.protocol&&!i.slashes,d.slashes=i.slashes||n&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||xj.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!di(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=Mj(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&di(d.protocol)&&(d.pathname="/"+d.pathname),cD(d.port,d.protocol)||(d.host=d.hostname,d.port=""),d.username=d.password="",d.auth&&(s=d.auth.indexOf(":"),~s?(d.username=d.auth.slice(0,s),d.username=encodeURIComponent(decodeURIComponent(d.username)),d.password=d.auth.slice(s+1),d.password=encodeURIComponent(decodeURIComponent(d.password))):d.username=encodeURIComponent(decodeURIComponent(d.auth)),d.auth=d.password?d.username+":"+d.password:d.username),d.origin=d.protocol!=="file:"&&di(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function Uj(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Uf.parse)(t)),n[e]=t;break;case"port":n[e]=t,cD(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<Q0.length;a++){var s=Q0[a];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&di(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function Bj(e){(!e||typeof e!="function")&&(e=Uf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||di(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&di(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}fi.prototype={set:Uj,toString:Bj};fi.extractProtocol=pD;fi.location=fD;fi.trimLeft=X0;fi.qs=Uf;mD.exports=fi});var qj,hD=k(()=>{"use strict";qj=Ce(Z0());});function ey(e,t,r){let n=Object.keys(r).sort();if(n.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return n.length===1?`${i}.${n[0]}`:`${i}.{${n.join(";")}}`}var Bf=k(()=>{"use strict";});var ty,ry,ny=k(()=>{"use strict";Bf();ty=class{features=new Map;register(t,r){let n=ey(r,t.teamName,t.fallback),i={clientName:r,teamName:t.teamName,fullName:n,description:t.description,owners:t.owners,ecsURL:t.ecsURL,createdOn:t.createdOn,fallbackConfig:t.fallback,feature:t,displayTeam:t.displayTeam,tags:t.tags,category:t.category};this.features.set(n,i)}getAll(){return Array.from(this.features.values())}get(t){return this.features.get(t)}has(t){return this.features.has(t)}getByClient(t){return this.getAll().filter(r=>r.clientName===t)}getByTeam(t){return this.getAll().filter(r=>r.teamName===t)}search(t){let r=t.toLowerCase();return this.getAll().filter(n=>n.fullName.toLowerCase().includes(r)||n.description?.toLowerCase().includes(r)||n.teamName.toLowerCase().includes(r)||n.clientName.toLowerCase().includes(r))}getClientNames(){let t=new Set;return this.features.forEach(r=>t.add(r.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(r=>t.add(r.teamName)),Array.from(t)}clear(){this.features.clear()}},ry=new ty});var iy=k(()=>{"use strict";});function Ff(e){return Vj.has(e)}var Vj,Lu=k(()=>{"use strict";z0();K0();xf();Pu();z0();hD();ny();Bf();iy();Vj=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var Gj,gD=k(()=>{"use strict";Lu();Gj=Ru({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var wD,ay,Ms,va,oy,qf,Us,ji,qe,yD,bD,vD,kn=k(()=>{"use strict";wD={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},ay={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(Ms||(Ms={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(va||(va={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(oy||(oy={}));qf=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})(Us||(Us={}));ji=class{static StartTag="<"},qe={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:va.Left,labelPosition:Us.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(yD||(yD={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(bD||(bD={}));(function(e){e.IsHeader="IsHeader",e.IsFooter="IsFooter",e.ContainedInHeader="ContainedInHeader",e.ContainedInFooter="ContainedInFooter",e.NoElementFound="NoElementFound",e.NoTarget="NoTarget",e.CannotAddControlToHeader="CannotAddControlToHeader",e.CannotAddControlToFooter="CannotAddControlToFooter"})(vD||(vD={}))});var sy,CD=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(sy||(sy={}))});var SD,Wj,ED,ape,spe,ku,AD,lpe,upe,ND=k(()=>{"use strict";SD=Ce(ya());dt();Fs();gD();vs();kn();oa();le();Wj=Ce(lo());CD();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(ED||(ED={}));ape={Read:go.Read,Edit:go.Edit,Both:go.Both,Container:go.Container},spe={input:ia.Input,bound:ia.Bound,output:ia.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(ku||(ku={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(AD||(AD={}));lpe=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),upe={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var $n,Vf,_D=k(()=>{"use strict";$n=Ce(ya());vt();dt();rr();Fs();oa();ND();vs();le();kt();kn();Vf=class extends re{constructor(t){super(E.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(Xt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===Xt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Xt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Xt.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.formFactor,t)}async toJSON(t){if(this.id)return null;let r=await this.parametersToJSON(t),n=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(n)?-1:n,Name:this.name,Version:null,Parameters:r,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(ji.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:hg.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===ku.dataset?o.get(Xt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===ku.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,$n.trackInfoTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"Custom Control Manifest Property Info not available"}},new Error(`Custom Control Manifest Property Info not available for custom control : ${this.name}.`));else(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===Xt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!Od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Mi.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(mg.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableViewPicker))}}return{Name:t,Usage:l,Static:u,Primary:c,Value:this.getParameterValue(t)}}else{let l=new Error(`No lookup manifest info for ${t}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,$n.trackWarningTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return Od.includes(t)}isNumberTypeProperty(t,r){return Pd.includes(r)||t.ofTypeGroup.some(n=>Pd.includes(n))}isDataSet(t){return Xt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,ly=k(()=>{"use strict";ee=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var TD={};nn(TD,{CustomControlUniqueId:()=>wa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>ft,mapFieldTypeToControl:()=>zj});function zj(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,wa,ft,$u=k(()=>{"use strict";vt();su();dt();rr();vs();ga();ly();kn();G=class{static get TextBoxControl(){return"4273EDBD-AC1D-40d3-9FB2-095C621B552D"}static get TickerControl(){return"1E1FC551-F7A8-43af-AC34-A8DC35C7B6D4"}static get UrlControl(){return"71716B6C-711E-476c-8AB8-5D11542BFB47"}static get PhoneNumberControl(){return"8C10015A-B339-4982-9474-A95FE05631A5"}static get EmailAddressControl(){return"ADA2203E-B4CD-49be-9DDF-234642B43B52"}static get RadioControl(){return"67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED"}static get LookupControl(){return"270BD3DB-D9AF-4782-9025-509E298DEC0A"}static get DateTimeControl(){return"5B773807-9FB2-42db-97C3-7A91EFF8ADFF"}static get IntegerControl(){return"C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F"}static get MoneyControl(){return"533B9E00-756B-4312-95A0-DC888637AC78"}static get FloatControl(){return"0D2C745A-E5A8-4c8f-BA63-C6D3BB604660"}static get DecimalControl(){return"C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E"}static get TextAreaControl(){return"E0DECE4B-6FC8-4a8f-A065-082708572369"}static get PicklistControl(){return"3EF39988-22BB-4f0b-BBBE-64B5A3748AEE"}static get HiddenInputControl(){return"5546E6CD-394C-4BEE-94A8-4425E17EF6C6"}static get GridControl(){return"E7A81278-8635-4D9E-8D4D-59480B391C5B"}static get CheckBoxControl(){return"B0C6723A-8503-4fd7-BB28-C8A06AC933C2"}static get IframeControl(){return"FD2A7985-3187-444e-908D-6624B21F69C0"}static get SocialInsightControl(){return"86B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get OrgInsightsControl(){return"76B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get DurationControl(){return"AA987274-CE4E-4271-A803-66164311A958"}static get RegardingControl(){return"F3015350-44A2-4aa0-97B5-00166532B5E9"}static get PartyListControl(){return"CBFB742C-14E7-4a17-96BB-1A13F7F64AA2"}static get TimeLineControl(){return"06375649-c143-495e-a496-c962e5b4488e"}static get TimeLineControlUC(){return"06375649-C143-495E-A496-C962E5B4488E"}static get TimeZonePicklistControl(){return"7C624A0B-F59E-493d-9583-638D34759266"}static get LanguagePickerControl(){return"671A9387-CA5A-4d1e-8AB7-06E39DDCF6B5"}static get AccessTeamTablePickerControl(){return"3F4E2A56-F102-4B4D-AB9C-F1574CA5BFDA"}static get KBViewerControl(){return"A62B6FA9-169E-406C-B1AA-EAB828CB6026"}static get PicklistStatusControl(){return"5D68B988-0661-4db2-BC3E-17598AD3BE6C"}static get EmailBodyControl(){return"6F3FB987-393B-4d2d-859F-9D0F0349B6AD"}static get PicklistLookupControl(){return"2305E33A-BAD3-4022-9E15-1856CF218333"}static get RelationshipRolePicklistControl(){return"5F986642-5961-4D9F-AB5E-643D71E231E9"}static get RelatedInformationControl(){return"163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8"}static get CoverPagePicklistControl(){return"4168A05C-D857-46AF-8457-5BB47EB04EA1"}static get MailMergeLanguagePickerControl(){return"B634828E-C390-444A-AFE6-E07315D9D970"}static get ConnectionControl(){return"3246F906-1F71-45F7-B11F-D7BE0F9D04C9"}static get ConnectionRoleObjectTypeListControl(){return"821ACF1A-7E46-4A0C-965D-FE14A57D78C7"}static get MapsControl(){return"62B0DF79-0464-470F-8AF7-4483CFEA0C7D"}static get MapLinkControl(){return"91DC0675-C8B9-4421-B1E0-261CEBF02BAC"}static get WebResourceHtmlControl(){return"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"}static get WebResourceImageControl(){return"587CDF98-C1D5-4BDE-8473-14A0BC7644A7"}static get WebResourceSilverlightControl(){return"080677DB-86EC-4544-AC42-F927E74B491F"}static get ReportControl(){return"A28F441B-916C-4865-87FD-0C5D53BD59C9"}static get ArticleContentControl(){return"F02EF977-2564-4B9A-B2F0-DF083D8A019B"}static get ProcessControl(){return"06E9F7AF-1F54-4681-8EEC-1E21A1CEB465"}static get ActivitiesWallControl(){return"6636847D-B74D-4994-B55A-A6FAF97ECEA2"}static get QuickFormControl(){return"69AF7DCA-2E3B-4EE7-9201-0DA731DD2413"}static get QuickFormCollectionControl(){return"5C5600E0-1D6E-4205-A272-BE80DA87FD42"}static get LinkControl(){return"DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"}static get CompositionLinkControl(){return"DB1284EF-9FFC-4E99-B382-0CC082FE2364"}static get ErrorStatusControl(){return"F4C16ECA-CA81-4E39-9448-834B8378721E"}static get ActivitiesContainerControl(){return"C72511AB-84E5-4FB7-A543-25B4FC01E83E"}static get AccessPrivilegeControl(){return"F93A31B2-99AC-4084-8EC2-D4027C31369A"}static get TimerControl(){return"9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E"}static get DynamicPropertyListControl(){return"6896F004-B17A-4202-861E-8B7EA2080E0B"}static get ButtonControl(){return"00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20"}static get SearchWidgetControl(){return"E616A57F-20E0-4534-8662-A101B5DDF4E0"}static get EmailRecipientActivityControl(){return"26E9760F-7454-40DE-BB07-F6DCCCB82040"}static get LabelControl(){return"39354E4A-5015-4D74-8031-EA9EB73A1322"}static get CustomControl(){return"F9A8A302-114E-466A-B582-6771B2AE0D92"}static get EditFilterControl(){return"1479835F-F852-4679-B864-C6892A2844C9"}static get RichEditorControl(){return"F94DB24F-263D-44A7-B38E-A35E9854812B"}static get PowerBIControl(){return"8C54228C-1B25-4909-A12A-F2B968BB0D62"}static get EmailEngagementActionsControl(){return"F454228D-1D25-4319-E12F-D27968BC0234"}static get ACIControl(){return"C8BFBBEF-6851-4401-A0CC-7450062FE085"}static get ChoicesControl(){return"4AA28AB7-9C13-4F57-A73D-AD894D048B5F"}static get ReferencePanelSubgridControl(){return"02D4264B-47E2-4B4C-AA95-F439F3F4D458"}static get ReferencePanelSearchWidget(){return"7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F"}static get ReferencePanelQuickFormCollectionControl(){return"B68B05F0-A46D-43F8-843B-917920AF806A"}static get SpacerControl(){return"E4BAB03A-A9A5-4C23-CC3B-54AA680150E2"}};wa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},ft=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new dr;static initializeFieldControls(){let t=new dr,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.Text);t.add(O,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Le=e.getControlName($.TwoOptions,"Radio");t.add(Le,new U(G.RadioControl));let lr=e.getControlName($.TwoOptions,"CheckBox");t.add(lr,new U(G.CheckBoxControl));let Ge=e.getControlName($.TwoOptions,"List");t.add(Ge,new U(G.PicklistControl));let Ut=e.getControlName($.State,W.None);t.add(Ut,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let Ke=e.getControlName($.OwnerType,W.None);t.add(Ke,new U(G.LookupControl));let ur=e.getControlName($.PartyListType,W.None);t.add(ur,new U(G.PartyListControl));let Bt=e.getControlName($.LookupType,W.Regarding);t.add(Bt,new U(G.RegardingControl));let Ni=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(Ni,new U(G.ChoicesControl)),t}static getControlName(t,r){return t+"_"+r}static getControlIdByTypeAndFormat(t,r){let n=e.getControlName(t.toString(),r.toString());return e.FieldControlIds.containsKey(n)?e.FieldControlIds.getValue(n):null}static getTypeAndFormatByControlOrUniqueId(t){for(let r in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[r]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[r]}static getControlDataTypeByControlOrUniqueId(t){if(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new dr;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(wa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new dr;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new bs;return t.add(Ms.IFRAME,!0),t.add(Ms.SPACER,!0),t.add(Ms.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(qe.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===wa.RelationshipAssistant||t.guidString===wa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===wa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Gf,DD=k(()=>{"use strict";Gf=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let r=this.listeners.indexOf(t);r>-1&&this.listeners.splice(r,1)}emit(t){this.listeners.forEach(r=>r(t)),this.listenersOncer.forEach(r=>r(t)),this.listenersOncer=[]}pipe(t){return this.on(r=>t.emit(r))}}});var Ca,Bs,ID,OD,Oo,PD,RD,uy=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Ca||(Ca={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Bs||(Bs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(ID||(ID={}));(function(e){e[e.None=0]="None",e[e.Create=1]="Create",e[e.Existing=2]="Existing",e[e.ReadOnly=3]="ReadOnly",e[e.Disabled=4]="Disabled",e[e.BulkEdit=6]="BulkEdit",e[e.Merge=7]="Merge",e[e.Print=8]="Print",e[e.FollowUp=9]="FollowUp"})(OD||(OD={}));(function(e){e[e.None=-1]="None",e[e.AppointmentBook=0]="AppointmentBook",e[e.Hardcoded=1]="Hardcoded",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.Dashboard=5]="Dashboard",e[e.Quick=6]="Quick",e[e.Mobile=7]="Mobile",e[e.Read=8]="Read",e[e.QuickCreate=9]="QuickCreate",e[e.Dialog=10]="Dialog",e[e.Card=11]="Card",e[e.TaskBasedForm=12]="TaskBasedForm",e[e.InteractionCentricDashboard=13]="InteractionCentricDashboard"})(Oo||(Oo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(PD||(PD={}));(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(RD||(RD={}))});var qs,LD=k(()=>{"use strict";Lu();qs=J0({packageName:"cds-designer-models",features:{showAllPCFControls:{owner:"anchoudh",description:"Do not only show the controls that exist on the whitelist",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},showTestControls:{owner:"lucorre",description:"Show advanced custom controls for testing (designated in Authoring Manifest with isTestOnly=true)",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},enablePrefetchGetMoreComponentsLocalization:{owner:"vajagarl",description:"Enables prefetching the localization files for controls displayed in custom control picker",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0}},showMapControl:{owner:"vayilavarapu",createdDate:"07/19/2022",description:"Show map control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableFallbackFormTemplate:{owner:"vajagarl",createdDate:"01/03/2023",description:"Enable default form template as fallback if unable to retrieve a form template from Dataverse",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableAutoInsertionOfCellInRow:{owner:"debeshd",createdDate:"09/01/2023",description:"Enable the auto insertion of cell in a row when a section is initialized",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableOneGridEvents:{owner:"aansu",createdDate:"08/21/2024",description:"Enable OneGrid events in form designer",enabledFor:{test:!0,preprod:!0,prod:!0,preview:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},disablePBIComponents:{owner:"adekulkarni",createdDate:"02/13/2025",description:"Disables PBI components and cleans them up from the form",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableAgentResponse:{owner:"jennietu",createdDate:"04/24/2025",description:"Enables agent response in form designer",enabledFor:{test:!0,preprod:!0,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableDelayedLocalizationForCustomControls:{owner:"aansu",createdDate:"06/08/2025",description:"Enables delayed localization of custom control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}}}})});function kD(e){return{...e,extractConfig:t=>jj(t,Object.keys(e.fallback))}}function jj(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var cy=k(()=>{"use strict";});var dy=v((xpe,xD)=>{var xu=new Proxy(function(){return xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xu},apply:function(){return xu},construct:function(){return{}}}),$D=function(){return xu};Object.setPrototypeOf($D,xu);xD.exports=$D});var UD=v((Fpe,MD)=>{var Fu=new Proxy(function(){return Fu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fu},apply:function(){return Fu},construct:function(){return{}}}),FD=function(){return Fu};Object.setPrototypeOf(FD,Fu);MD.exports=FD});var fy=v((Mpe,qD)=>{var Mu=new Proxy(function(){return Mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Mu},apply:function(){return Mu},construct:function(){return{}}}),BD=function(){return Mu};Object.setPrototypeOf(BD,Mu);qD.exports=BD});var GD=v((Upe,VD)=>{function Hj(){this.__data__=[],this.size=0}VD.exports=Hj});var Vs=v((Bpe,WD)=>{function Kj(e,t){return e===t||e!==e&&t!==t}WD.exports=Kj});var Uu=v((qpe,zD)=>{var Jj=Vs();function Yj(e,t){for(var r=e.length;r--;)if(Jj(e[r][0],t))return r;return-1}zD.exports=Yj});var HD=v((Vpe,jD)=>{var Qj=Uu(),Xj=Array.prototype,Zj=Xj.splice;function e7(e){var t=this.__data__,r=Qj(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Zj.call(t,r,1),--this.size,!0}jD.exports=e7});var JD=v((Gpe,KD)=>{var t7=Uu();function r7(e){var t=this.__data__,r=t7(t,e);return r<0?void 0:t[r][1]}KD.exports=r7});var QD=v((Wpe,YD)=>{var n7=Uu();function i7(e){return n7(this.__data__,e)>-1}YD.exports=i7});var ZD=v((zpe,XD)=>{var o7=Uu();function a7(e,t){var r=this.__data__,n=o7(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}XD.exports=a7});var Bu=v((jpe,eI)=>{var s7=GD(),l7=HD(),u7=JD(),c7=QD(),d7=ZD();function Gs(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Gs.prototype.clear=s7;Gs.prototype.delete=l7;Gs.prototype.get=u7;Gs.prototype.has=c7;Gs.prototype.set=d7;eI.exports=Gs});var rI=v((Hpe,tI)=>{var f7=Bu();function p7(){this.__data__=new f7,this.size=0}tI.exports=p7});var iI=v((Kpe,nI)=>{function m7(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}nI.exports=m7});var aI=v((Jpe,oI)=>{function h7(e){return this.__data__.get(e)}oI.exports=h7});var lI=v((Ype,sI)=>{function g7(e){return this.__data__.has(e)}sI.exports=g7});var py=v((Qpe,uI)=>{var y7=typeof global=="object"&&global&&global.Object===Object&&global;uI.exports=y7});var xn=v((Xpe,cI)=>{var b7=py(),v7=typeof self=="object"&&self&&self.Object===Object&&self,w7=b7||v7||Function("return this")();cI.exports=w7});var qu=v((Zpe,dI)=>{var C7=xn(),E7=C7.Symbol;dI.exports=E7});var hI=v((eme,mI)=>{var fI=qu(),pI=Object.prototype,A7=pI.hasOwnProperty,S7=pI.toString,Vu=fI?fI.toStringTag:void 0;function N7(e){var t=A7.call(e,Vu),r=e[Vu];try{e[Vu]=void 0;var n=!0}catch{}var i=S7.call(e);return n&&(t?e[Vu]=r:delete e[Vu]),i}mI.exports=N7});var yI=v((tme,gI)=>{var _7=Object.prototype,T7=_7.toString;function D7(e){return T7.call(e)}gI.exports=D7});var Ea=v((rme,wI)=>{var bI=qu(),I7=hI(),O7=yI(),P7="[object Null]",R7="[object Undefined]",vI=bI?bI.toStringTag:void 0;function L7(e){return e==null?e===void 0?R7:P7:vI&&vI in Object(e)?I7(e):O7(e)}wI.exports=L7});var Hi=v((nme,CI)=>{function k7(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}CI.exports=k7});var Wf=v((ime,EI)=>{var $7=Ea(),x7=Hi(),F7="[object AsyncFunction]",M7="[object Function]",U7="[object GeneratorFunction]",B7="[object Proxy]";function q7(e){if(!x7(e))return!1;var t=$7(e);return t==M7||t==U7||t==F7||t==B7}EI.exports=q7});var SI=v((ome,AI)=>{var V7=xn(),G7=V7["__core-js_shared__"];AI.exports=G7});var TI=v((ame,_I)=>{var my=SI(),NI=(function(){var e=/[^.]+$/.exec(my&&my.keys&&my.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function W7(e){return!!NI&&NI in e}_I.exports=W7});var hy=v((sme,DI)=>{var z7=Function.prototype,j7=z7.toString;function H7(e){if(e!=null){try{return j7.call(e)}catch{}try{return e+""}catch{}}return""}DI.exports=H7});var OI=v((lme,II)=>{var K7=Wf(),J7=TI(),Y7=Hi(),Q7=hy(),X7=/[\\^$.*+?()[\]{}|]/g,Z7=/^\[object .+?Constructor\]$/,eH=Function.prototype,tH=Object.prototype,rH=eH.toString,nH=tH.hasOwnProperty,iH=RegExp("^"+rH.call(nH).replace(X7,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function oH(e){if(!Y7(e)||J7(e))return!1;var t=K7(e)?iH:Z7;return t.test(Q7(e))}II.exports=oH});var RI=v((ume,PI)=>{function aH(e,t){return e?.[t]}PI.exports=aH});var Po=v((cme,LI)=>{var sH=OI(),lH=RI();function uH(e,t){var r=lH(e,t);return sH(r)?r:void 0}LI.exports=uH});var zf=v((dme,kI)=>{var cH=Po(),dH=xn(),fH=cH(dH,"Map");kI.exports=fH});var Gu=v((fme,$I)=>{var pH=Po(),mH=pH(Object,"create");$I.exports=mH});var MI=v((pme,FI)=>{var xI=Gu();function hH(){this.__data__=xI?xI(null):{},this.size=0}FI.exports=hH});var BI=v((mme,UI)=>{function gH(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}UI.exports=gH});var VI=v((hme,qI)=>{var yH=Gu(),bH="__lodash_hash_undefined__",vH=Object.prototype,wH=vH.hasOwnProperty;function CH(e){var t=this.__data__;if(yH){var r=t[e];return r===bH?void 0:r}return wH.call(t,e)?t[e]:void 0}qI.exports=CH});var WI=v((gme,GI)=>{var EH=Gu(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e){var t=this.__data__;return EH?t[e]!==void 0:SH.call(t,e)}GI.exports=NH});var jI=v((yme,zI)=>{var _H=Gu(),TH="__lodash_hash_undefined__";function DH(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=_H&&t===void 0?TH:t,this}zI.exports=DH});var KI=v((bme,HI)=>{var IH=MI(),OH=BI(),PH=VI(),RH=WI(),LH=jI();function Ws(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Ws.prototype.clear=IH;Ws.prototype.delete=OH;Ws.prototype.get=PH;Ws.prototype.has=RH;Ws.prototype.set=LH;HI.exports=Ws});var QI=v((vme,YI)=>{var JI=KI(),kH=Bu(),$H=zf();function xH(){this.size=0,this.__data__={hash:new JI,map:new($H||kH),string:new JI}}YI.exports=xH});var ZI=v((wme,XI)=>{function FH(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}XI.exports=FH});var Wu=v((Cme,eO)=>{var MH=ZI();function UH(e,t){var r=e.__data__;return MH(t)?r[typeof t=="string"?"string":"hash"]:r.map}eO.exports=UH});var rO=v((Eme,tO)=>{var BH=Wu();function qH(e){var t=BH(this,e).delete(e);return this.size-=t?1:0,t}tO.exports=qH});var iO=v((Ame,nO)=>{var VH=Wu();function GH(e){return VH(this,e).get(e)}nO.exports=GH});var aO=v((Sme,oO)=>{var WH=Wu();function zH(e){return WH(this,e).has(e)}oO.exports=zH});var lO=v((Nme,sO)=>{var jH=Wu();function HH(e,t){var r=jH(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}sO.exports=HH});var jf=v((_me,uO)=>{var KH=QI(),JH=rO(),YH=iO(),QH=aO(),XH=lO();function zs(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}zs.prototype.clear=KH;zs.prototype.delete=JH;zs.prototype.get=YH;zs.prototype.has=QH;zs.prototype.set=XH;uO.exports=zs});var dO=v((Tme,cO)=>{var ZH=Bu(),eK=zf(),tK=jf(),rK=200;function nK(e,t){var r=this.__data__;if(r instanceof ZH){var n=r.__data__;if(!eK||n.length<rK-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new tK(n)}return r.set(e,t),this.size=r.size,this}cO.exports=nK});var gy=v((Dme,fO)=>{var iK=Bu(),oK=rI(),aK=iI(),sK=aI(),lK=lI(),uK=dO();function js(e){var t=this.__data__=new iK(e);this.size=t.size}js.prototype.clear=oK;js.prototype.delete=aK;js.prototype.get=sK;js.prototype.has=lK;js.prototype.set=uK;fO.exports=js});var mO=v((Ime,pO)=>{var cK="__lodash_hash_undefined__";function dK(e){return this.__data__.set(e,cK),this}pO.exports=dK});var gO=v((Ome,hO)=>{function fK(e){return this.__data__.has(e)}hO.exports=fK});var bO=v((Pme,yO)=>{var pK=jf(),mK=mO(),hK=gO();function Hf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new pK;++t<r;)this.add(e[t])}Hf.prototype.add=Hf.prototype.push=mK;Hf.prototype.has=hK;yO.exports=Hf});var wO=v((Rme,vO)=>{function gK(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}vO.exports=gK});var EO=v((Lme,CO)=>{function yK(e,t){return e.has(t)}CO.exports=yK});var yy=v((kme,AO)=>{var bK=bO(),vK=wO(),wK=EO(),CK=1,EK=2;function AK(e,t,r,n,i,o){var a=r&CK,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&EK?new bK:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!vK(t,function(b,w){if(!wK(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}AO.exports=AK});var by=v(($me,SO)=>{var SK=xn(),NK=SK.Uint8Array;SO.exports=NK});var _O=v((xme,NO)=>{function _K(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}NO.exports=_K});var DO=v((Fme,TO)=>{function TK(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}TO.exports=TK});var LO=v((Mme,RO)=>{var IO=qu(),OO=by(),DK=Vs(),IK=yy(),OK=_O(),PK=DO(),RK=1,LK=2,kK="[object Boolean]",$K="[object Date]",xK="[object Error]",FK="[object Map]",MK="[object Number]",UK="[object RegExp]",BK="[object Set]",qK="[object String]",VK="[object Symbol]",GK="[object ArrayBuffer]",WK="[object DataView]",PO=IO?IO.prototype:void 0,vy=PO?PO.valueOf:void 0;function zK(e,t,r,n,i,o,a){switch(r){case WK:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case GK:return!(e.byteLength!=t.byteLength||!o(new OO(e),new OO(t)));case kK:case $K:case MK:return DK(+e,+t);case xK:return e.name==t.name&&e.message==t.message;case UK:case qK:return e==t+"";case FK:var s=OK;case BK:var l=n&RK;if(s||(s=PK),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=LK,a.set(e,t);var c=IK(s(e),s(t),n,i,o,a);return a.delete(e),c;case VK:if(vy)return vy.call(e)==vy.call(t)}return!1}RO.exports=zK});var $O=v((Ume,kO)=>{function jK(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}kO.exports=jK});var Ro=v((Bme,xO)=>{var HK=Array.isArray;xO.exports=HK});var MO=v((qme,FO)=>{var KK=$O(),JK=Ro();function YK(e,t,r){var n=t(e);return JK(e)?n:KK(n,r(e))}FO.exports=YK});var BO=v((Vme,UO)=>{function QK(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}UO.exports=QK});var VO=v((Gme,qO)=>{function XK(){return[]}qO.exports=XK});var zO=v((Wme,WO)=>{var ZK=BO(),eJ=VO(),tJ=Object.prototype,rJ=tJ.propertyIsEnumerable,GO=Object.getOwnPropertySymbols,nJ=GO?function(e){return e==null?[]:(e=Object(e),ZK(GO(e),function(t){return rJ.call(e,t)}))}:eJ;WO.exports=nJ});var HO=v((zme,jO)=>{function iJ(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}jO.exports=iJ});var Lo=v((jme,KO)=>{function oJ(e){return e!=null&&typeof e=="object"}KO.exports=oJ});var YO=v((Hme,JO)=>{var aJ=Ea(),sJ=Lo(),lJ="[object Arguments]";function uJ(e){return sJ(e)&&aJ(e)==lJ}JO.exports=uJ});var wy=v((Kme,ZO)=>{var QO=YO(),cJ=Lo(),XO=Object.prototype,dJ=XO.hasOwnProperty,fJ=XO.propertyIsEnumerable,pJ=QO((function(){return arguments})())?QO:function(e){return cJ(e)&&dJ.call(e,"callee")&&!fJ.call(e,"callee")};ZO.exports=pJ});var tP=v((Jme,eP)=>{function mJ(){return!1}eP.exports=mJ});var Kf=v((zu,Hs)=>{var hJ=xn(),gJ=tP(),iP=typeof zu=="object"&&zu&&!zu.nodeType&&zu,rP=iP&&typeof Hs=="object"&&Hs&&!Hs.nodeType&&Hs,yJ=rP&&rP.exports===iP,nP=yJ?hJ.Buffer:void 0,bJ=nP?nP.isBuffer:void 0,vJ=bJ||gJ;Hs.exports=vJ});var Jf=v((Yme,oP)=>{var wJ=9007199254740991,CJ=/^(?:0|[1-9]\d*)$/;function EJ(e,t){var r=typeof e;return t=t??wJ,!!t&&(r=="number"||r!="symbol"&&CJ.test(e))&&e>-1&&e%1==0&&e<t}oP.exports=EJ});var Cy=v((Qme,aP)=>{var AJ=9007199254740991;function SJ(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=AJ}aP.exports=SJ});var lP=v((Xme,sP)=>{var NJ=Ea(),_J=Cy(),TJ=Lo(),DJ="[object Arguments]",IJ="[object Array]",OJ="[object Boolean]",PJ="[object Date]",RJ="[object Error]",LJ="[object Function]",kJ="[object Map]",$J="[object Number]",xJ="[object Object]",FJ="[object RegExp]",MJ="[object Set]",UJ="[object String]",BJ="[object WeakMap]",qJ="[object ArrayBuffer]",VJ="[object DataView]",GJ="[object Float32Array]",WJ="[object Float64Array]",zJ="[object Int8Array]",jJ="[object Int16Array]",HJ="[object Int32Array]",KJ="[object Uint8Array]",JJ="[object Uint8ClampedArray]",YJ="[object Uint16Array]",QJ="[object Uint32Array]",xe={};xe[GJ]=xe[WJ]=xe[zJ]=xe[jJ]=xe[HJ]=xe[KJ]=xe[JJ]=xe[YJ]=xe[QJ]=!0;xe[DJ]=xe[IJ]=xe[qJ]=xe[OJ]=xe[VJ]=xe[PJ]=xe[RJ]=xe[LJ]=xe[kJ]=xe[$J]=xe[xJ]=xe[FJ]=xe[MJ]=xe[UJ]=xe[BJ]=!1;function XJ(e){return TJ(e)&&_J(e.length)&&!!xe[NJ(e)]}sP.exports=XJ});var cP=v((Zme,uP)=>{function ZJ(e){return function(t){return e(t)}}uP.exports=ZJ});var fP=v((ju,Ks)=>{var eY=py(),dP=typeof ju=="object"&&ju&&!ju.nodeType&&ju,Hu=dP&&typeof Ks=="object"&&Ks&&!Ks.nodeType&&Ks,tY=Hu&&Hu.exports===dP,Ey=tY&&eY.process,rY=(function(){try{var e=Hu&&Hu.require&&Hu.require("util").types;return e||Ey&&Ey.binding&&Ey.binding("util")}catch{}})();Ks.exports=rY});var Yf=v((ehe,hP)=>{var nY=lP(),iY=cP(),pP=fP(),mP=pP&&pP.isTypedArray,oY=mP?iY(mP):nY;hP.exports=oY});var Ay=v((the,gP)=>{var aY=HO(),sY=wy(),lY=Ro(),uY=Kf(),cY=Jf(),dY=Yf(),fY=Object.prototype,pY=fY.hasOwnProperty;function mY(e,t){var r=lY(e),n=!r&&sY(e),i=!r&&!n&&uY(e),o=!r&&!n&&!i&&dY(e),a=r||n||i||o,s=a?aY(e.length,String):[],l=s.length;for(var u in e)(t||pY.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||cY(u,l)))&&s.push(u);return s}gP.exports=mY});var Qf=v((rhe,yP)=>{var hY=Object.prototype;function gY(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||hY;return e===r}yP.exports=gY});var Sy=v((nhe,bP)=>{function yY(e,t){return function(r){return e(t(r))}}bP.exports=yY});var wP=v((ihe,vP)=>{var bY=Sy(),vY=bY(Object.keys,Object);vP.exports=vY});var EP=v((ohe,CP)=>{var wY=Qf(),CY=wP(),EY=Object.prototype,AY=EY.hasOwnProperty;function SY(e){if(!wY(e))return CY(e);var t=[];for(var r in Object(e))AY.call(e,r)&&r!="constructor"&&t.push(r);return t}CP.exports=SY});var Ku=v((ahe,AP)=>{var NY=Wf(),_Y=Cy();function TY(e){return e!=null&&_Y(e.length)&&!NY(e)}AP.exports=TY});var NP=v((she,SP)=>{var DY=Ay(),IY=EP(),OY=Ku();function PY(e){return OY(e)?DY(e):IY(e)}SP.exports=PY});var TP=v((lhe,_P)=>{var RY=MO(),LY=zO(),kY=NP();function $Y(e){return RY(e,kY,LY)}_P.exports=$Y});var OP=v((uhe,IP)=>{var DP=TP(),xY=1,FY=Object.prototype,MY=FY.hasOwnProperty;function UY(e,t,r,n,i,o){var a=r&xY,s=DP(e),l=s.length,u=DP(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:MY.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var C=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(C===void 0?b===w||i(b,w,r,n,o):C)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,O=t.constructor;S!=O&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof O=="function"&&O instanceof O)&&(h=!1)}return o.delete(e),o.delete(t),h}IP.exports=UY});var RP=v((che,PP)=>{var BY=Po(),qY=xn(),VY=BY(qY,"DataView");PP.exports=VY});var kP=v((dhe,LP)=>{var GY=Po(),WY=xn(),zY=GY(WY,"Promise");LP.exports=zY});var xP=v((fhe,$P)=>{var jY=Po(),HY=xn(),KY=jY(HY,"Set");$P.exports=KY});var MP=v((phe,FP)=>{var JY=Po(),YY=xn(),QY=JY(YY,"WeakMap");FP.exports=QY});var jP=v((mhe,zP)=>{var Ny=RP(),_y=zf(),Ty=kP(),Dy=xP(),Iy=MP(),WP=Ea(),Js=hy(),UP="[object Map]",XY="[object Object]",BP="[object Promise]",qP="[object Set]",VP="[object WeakMap]",GP="[object DataView]",ZY=Js(Ny),eQ=Js(_y),tQ=Js(Ty),rQ=Js(Dy),nQ=Js(Iy),Aa=WP;(Ny&&Aa(new Ny(new ArrayBuffer(1)))!=GP||_y&&Aa(new _y)!=UP||Ty&&Aa(Ty.resolve())!=BP||Dy&&Aa(new Dy)!=qP||Iy&&Aa(new Iy)!=VP)&&(Aa=function(e){var t=WP(e),r=t==XY?e.constructor:void 0,n=r?Js(r):"";if(n)switch(n){case ZY:return GP;case eQ:return UP;case tQ:return BP;case rQ:return qP;case nQ:return VP}return t});zP.exports=Aa});var eR=v((hhe,ZP)=>{var Oy=gy(),iQ=yy(),oQ=LO(),aQ=OP(),HP=jP(),KP=Ro(),JP=Kf(),sQ=Yf(),lQ=1,YP="[object Arguments]",QP="[object Array]",Xf="[object Object]",uQ=Object.prototype,XP=uQ.hasOwnProperty;function cQ(e,t,r,n,i,o){var a=KP(e),s=KP(t),l=a?QP:HP(e),u=s?QP:HP(t);l=l==YP?Xf:l,u=u==YP?Xf:u;var c=l==Xf,d=u==Xf,f=l==u;if(f&&JP(e)){if(!JP(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new Oy),a||sQ(e)?iQ(e,t,r,n,i,o):oQ(e,t,l,r,n,i,o);if(!(r&lQ)){var m=c&&XP.call(e,"__wrapped__"),p=d&&XP.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new Oy),i(h,g,r,n,o)}}return f?(o||(o=new Oy),aQ(e,t,r,n,i,o)):!1}ZP.exports=cQ});var iR=v((ghe,nR)=>{var dQ=eR(),tR=Lo();function rR(e,t,r,n,i){return e===t?!0:e==null||t==null||!tR(e)&&!tR(t)?e!==e&&t!==t:dQ(e,t,r,n,rR,i)}nR.exports=rR});var aR=v((yhe,oR)=>{var fQ=iR();function pQ(e,t){return fQ(e,t)}oR.exports=pQ});var Py=v((bhe,sR)=>{var mQ=Po(),hQ=(function(){try{var e=mQ(Object,"defineProperty");return e({},"",{}),e}catch{}})();sR.exports=hQ});var Zf=v((vhe,uR)=>{var lR=Py();function gQ(e,t,r){t=="__proto__"&&lR?lR(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}uR.exports=gQ});var Ry=v((whe,cR)=>{var yQ=Zf(),bQ=Vs();function vQ(e,t,r){(r!==void 0&&!bQ(e[t],r)||r===void 0&&!(t in e))&&yQ(e,t,r)}cR.exports=vQ});var fR=v((Che,dR)=>{function wQ(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}dR.exports=wQ});var mR=v((Ehe,pR)=>{var CQ=fR(),EQ=CQ();pR.exports=EQ});var vR=v((Ju,Ys)=>{var AQ=xn(),bR=typeof Ju=="object"&&Ju&&!Ju.nodeType&&Ju,hR=bR&&typeof Ys=="object"&&Ys&&!Ys.nodeType&&Ys,SQ=hR&&hR.exports===bR,gR=SQ?AQ.Buffer:void 0,yR=gR?gR.allocUnsafe:void 0;function NQ(e,t){if(t)return e.slice();var r=e.length,n=yR?yR(r):new e.constructor(r);return e.copy(n),n}Ys.exports=NQ});var ER=v((Ahe,CR)=>{var wR=by();function _Q(e){var t=new e.constructor(e.byteLength);return new wR(t).set(new wR(e)),t}CR.exports=_Q});var SR=v((She,AR)=>{var TQ=ER();function DQ(e,t){var r=t?TQ(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}AR.exports=DQ});var _R=v((Nhe,NR)=>{function IQ(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}NR.exports=IQ});var IR=v((_he,DR)=>{var OQ=Hi(),TR=Object.create,PQ=(function(){function e(){}return function(t){if(!OQ(t))return{};if(TR)return TR(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();DR.exports=PQ});var Ly=v((The,OR)=>{var RQ=Sy(),LQ=RQ(Object.getPrototypeOf,Object);OR.exports=LQ});var RR=v((Dhe,PR)=>{var kQ=IR(),$Q=Ly(),xQ=Qf();function FQ(e){return typeof e.constructor=="function"&&!xQ(e)?kQ($Q(e)):{}}PR.exports=FQ});var kR=v((Ihe,LR)=>{var MQ=Ku(),UQ=Lo();function BQ(e){return UQ(e)&&MQ(e)}LR.exports=BQ});var FR=v((Ohe,xR)=>{var qQ=Ea(),VQ=Ly(),GQ=Lo(),WQ="[object Object]",zQ=Function.prototype,jQ=Object.prototype,$R=zQ.toString,HQ=jQ.hasOwnProperty,KQ=$R.call(Object);function JQ(e){if(!GQ(e)||qQ(e)!=WQ)return!1;var t=VQ(e);if(t===null)return!0;var r=HQ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&$R.call(r)==KQ}xR.exports=JQ});var ky=v((Phe,MR)=>{function YQ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}MR.exports=YQ});var $y=v((Rhe,UR)=>{var QQ=Zf(),XQ=Vs(),ZQ=Object.prototype,eX=ZQ.hasOwnProperty;function tX(e,t,r){var n=e[t];(!(eX.call(e,t)&&XQ(n,r))||r===void 0&&!(t in e))&&QQ(e,t,r)}UR.exports=tX});var qR=v((Lhe,BR)=>{var rX=$y(),nX=Zf();function iX(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?nX(r,s,l):rX(r,s,l)}return r}BR.exports=iX});var GR=v((khe,VR)=>{function oX(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}VR.exports=oX});var zR=v(($he,WR)=>{var aX=Hi(),sX=Qf(),lX=GR(),uX=Object.prototype,cX=uX.hasOwnProperty;function dX(e){if(!aX(e))return lX(e);var t=sX(e),r=[];for(var n in e)n=="constructor"&&(t||!cX.call(e,n))||r.push(n);return r}WR.exports=dX});var xy=v((xhe,jR)=>{var fX=Ay(),pX=zR(),mX=Ku();function hX(e){return mX(e)?fX(e,!0):pX(e)}jR.exports=hX});var KR=v((Fhe,HR)=>{var gX=qR(),yX=xy();function bX(e){return gX(e,yX(e))}HR.exports=bX});var e2=v((Mhe,ZR)=>{var JR=Ry(),vX=vR(),wX=SR(),CX=_R(),EX=RR(),YR=wy(),QR=Ro(),AX=kR(),SX=Kf(),NX=Wf(),_X=Hi(),TX=FR(),DX=Yf(),XR=ky(),IX=KR();function OX(e,t,r,n,i,o,a){var s=XR(e,r),l=XR(t,r),u=a.get(l);if(u){JR(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=QR(l),m=!f&&SX(l),p=!f&&!m&&DX(l);c=l,f||m||p?QR(s)?c=s:AX(s)?c=CX(s):m?(d=!1,c=vX(l,!0)):p?(d=!1,c=wX(l,!0)):c=[]:TX(l)||YR(l)?(c=s,YR(s)?c=IX(s):(!_X(s)||NX(s))&&(c=EX(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),JR(e,r,c)}ZR.exports=OX});var Fy=v((Uhe,r2)=>{var PX=gy(),RX=Ry(),LX=mR(),kX=e2(),$X=Hi(),xX=xy(),FX=ky();function t2(e,t,r,n,i){e!==t&&LX(t,function(o,a){if(i||(i=new PX),$X(o))kX(e,t,a,r,t2,n,i);else{var s=n?n(FX(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),RX(e,a,s)}},xX)}r2.exports=t2});var My=v((Bhe,n2)=>{function MX(e){return e}n2.exports=MX});var o2=v((qhe,i2)=>{function UX(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}i2.exports=UX});var l2=v((Vhe,s2)=>{var BX=o2(),a2=Math.max;function qX(e,t,r){return t=a2(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=a2(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),BX(e,this,s)}}s2.exports=qX});var c2=v((Ghe,u2)=>{function VX(e){return function(){return e}}u2.exports=VX});var p2=v((Whe,f2)=>{var GX=c2(),d2=Py(),WX=My(),zX=d2?function(e,t){return d2(e,"toString",{configurable:!0,enumerable:!1,value:GX(t),writable:!0})}:WX;f2.exports=zX});var h2=v((zhe,m2)=>{var jX=800,HX=16,KX=Date.now;function JX(e){var t=0,r=0;return function(){var n=KX(),i=HX-(n-r);if(r=n,i>0){if(++t>=jX)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}m2.exports=JX});var y2=v((jhe,g2)=>{var YX=p2(),QX=h2(),XX=QX(YX);g2.exports=XX});var v2=v((Hhe,b2)=>{var ZX=My(),eZ=l2(),tZ=y2();function rZ(e,t){return tZ(eZ(e,t,ZX),e+"")}b2.exports=rZ});var C2=v((Khe,w2)=>{var nZ=Vs(),iZ=Ku(),oZ=Jf(),aZ=Hi();function sZ(e,t,r){if(!aZ(r))return!1;var n=typeof t;return(n=="number"?iZ(r)&&oZ(t,r.length):n=="string"&&t in r)?nZ(r[t],e):!1}w2.exports=sZ});var Uy=v((Jhe,E2)=>{var lZ=v2(),uZ=C2();function cZ(e){return lZ(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&uZ(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}E2.exports=cZ});var S2=v((Yhe,A2)=>{var dZ=Fy(),fZ=Uy(),pZ=fZ(function(e,t,r,n){dZ(e,t,r,n)});A2.exports=pZ});var gn,Yu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(gn||(gn={}))});function _2(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${N2.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var N2,mZ,T2=k(()=>{"use strict";N2=Ce(fy()),mZ=Ce(dy());});var By,D2=k(()=>{"use strict";xf();By=Ru({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var O2,P2,R2,L2,qy,hZ,ep,I2,Vy=k(()=>{"use strict";O2=Ce(dy()),P2=Ce(UD()),R2=Ce(fy()),L2=Ce(aR()),qy=Ce(S2());Yu();T2();D2();hZ=60*1e3,ep=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=gn.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,r,n="PROD"){this.clientName=t,this.logger=r,this.endpointType=n,this.ecsEndpoint=n==="PROD"?By.prodEcsEndpoint:By.integrationEcsEndpoint}client=new P2.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=O2.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[R2.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:_2(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===gn.NotLoaded&&(this._status=gn.Initialized)}catch(s){this._status=gn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*hZ)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,qy.default)({},t.fallback,n,t.override,I2)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,L2.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,qy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,I2);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=gn.ConfigsLoaded;let{ConfigIDs:r,Headers:n}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:r,ETag:n?.ETag})};logEvent=(t,r)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...r})}},I2=(e,t)=>{if(Array.isArray(t))return t}});var $2=v((oge,k2)=>{"use strict";var gZ=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};k2.exports=gZ});var Gy=v((age,F2)=>{var Qu=new Proxy(function(){return Qu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Qu},apply:function(){return Qu},construct:function(){return{}}}),x2=function(){return Qu};Object.setPrototypeOf(x2,Qu);F2.exports=x2});var B2=v((sge,U2)=>{var Xu=new Proxy(function(){return Xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Xu},apply:function(){return Xu},construct:function(){return{}}}),M2=function(){return Xu};Object.setPrototypeOf(M2,Xu);U2.exports=M2});var H2=v((lge,j2)=>{"use strict";var Wy=B2(),yZ={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},bZ={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},vZ={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},W2={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},zy={};zy[Wy.ForwardRef]=vZ;zy[Wy.Memo]=W2;function q2(e){return Wy.isMemo(e)?W2:zy[e.$$typeof]||yZ}var wZ=Object.defineProperty,CZ=Object.getOwnPropertyNames,V2=Object.getOwnPropertySymbols,EZ=Object.getOwnPropertyDescriptor,AZ=Object.getPrototypeOf,G2=Object.prototype;function z2(e,t,r){if(typeof t!="string"){if(G2){var n=AZ(t);n&&n!==G2&&z2(e,n,r)}var i=CZ(t);V2&&(i=i.concat(V2(t)));for(var o=q2(e),a=q2(t),s=0;s<i.length;++s){var l=i[s];if(!bZ[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=EZ(t,l);try{wZ(e,l,u)}catch{}}}}return e}j2.exports=z2});function J2(e,t,r){let[n,i]=(0,Qs.useState)(e.getConfig(t));return(0,Qs.useEffect)(()=>{if(!r?.subscribe&&e.status===gn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function Y2(e){return function(t,r){return J2(e,t,r)}}function Q2(e,t,r,n){let i=o=>{let a=J2(e,t,n),s={...o,...a};return Qs.default.createElement(r,{...s})};return(0,K2.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function X2(e,t,r,n){return t.reduce((i,o)=>Q2(e,o,i,n),r)}function Z2(e){return function(t,r,n){return Q2(e,t,r,n)}}var K2,Qs,jy=k(()=>{"use strict";K2=Ce(H2()),Qs=Ce(Gy());Yu();});var t1=v((dge,e1)=>{var SZ=Fy(),NZ=Uy(),_Z=NZ(function(e,t,r){SZ(e,t,r)});e1.exports=_Z});var tp=v((fge,r1)=>{var TZ=Ea(),DZ=Lo(),IZ="[object Symbol]";function OZ(e){return typeof e=="symbol"||DZ(e)&&TZ(e)==IZ}r1.exports=OZ});var i1=v((pge,n1)=>{var PZ=Ro(),RZ=tp(),LZ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,kZ=/^\w*$/;function $Z(e,t){if(PZ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||RZ(e)?!0:kZ.test(e)||!LZ.test(e)||t!=null&&e in Object(t)}n1.exports=$Z});var s1=v((mge,a1)=>{var o1=jf(),xZ="Expected a function";function Hy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(xZ);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Hy.Cache||o1),r}Hy.Cache=o1;a1.exports=Hy});var u1=v((hge,l1)=>{var FZ=s1(),MZ=500;function UZ(e){var t=FZ(e,function(n){return r.size===MZ&&r.clear(),n}),r=t.cache;return t}l1.exports=UZ});var d1=v((gge,c1)=>{var BZ=u1(),qZ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,VZ=/\\(\\)?/g,GZ=BZ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(qZ,function(r,n,i,o){t.push(i?o.replace(VZ,"$1"):n||r)}),t});c1.exports=GZ});var p1=v((yge,f1)=>{function WZ(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}f1.exports=WZ});var v1=v((bge,b1)=>{var m1=qu(),zZ=p1(),jZ=Ro(),HZ=tp(),KZ=1/0,h1=m1?m1.prototype:void 0,g1=h1?h1.toString:void 0;function y1(e){if(typeof e=="string")return e;if(jZ(e))return zZ(e,y1)+"";if(HZ(e))return g1?g1.call(e):"";var t=e+"";return t=="0"&&1/e==-KZ?"-0":t}b1.exports=y1});var C1=v((vge,w1)=>{var JZ=v1();function YZ(e){return e==null?"":JZ(e)}w1.exports=YZ});var A1=v((wge,E1)=>{var QZ=Ro(),XZ=i1(),ZZ=d1(),eee=C1();function tee(e,t){return QZ(e)?e:XZ(e,t)?[e]:ZZ(eee(e))}E1.exports=tee});var N1=v((Cge,S1)=>{var ree=tp(),nee=1/0;function iee(e){if(typeof e=="string"||ree(e))return e;var t=e+"";return t=="0"&&1/e==-nee?"-0":t}S1.exports=iee});var D1=v((Ege,T1)=>{var oee=$y(),aee=A1(),see=Jf(),_1=Hi(),lee=N1();function uee(e,t,r,n){if(!_1(e))return e;t=aee(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=lee(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=_1(c)?c:see(t[i+1])?[]:{})}oee(s,l,u),s=s[l]}return e}T1.exports=uee});var O1=v((Age,I1)=>{var cee=D1();function dee(e,t,r){return e==null?e:cee(e,t,r)}I1.exports=dee});function k1(e){let{query:t}=(0,L1.default)(window.location.href,!0);return pee(e,t),e}function pee(e,t){let r=fee+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+$1,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,R1.default)(u,c,s)}(0,P1.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var P1,R1,L1,$1,fee,x1=k(()=>{"use strict";P1=Ce(t1()),R1=Ce(O1()),L1=Ce(Z0());$1=".",fee="ecs"+$1});function np(e,t,r){let n=k1(new ep(e,t,r));function i(o){(0,rp.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:hee(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>X2(n,o,a,s)}}function hee(e){let t=Y2(e),r=Z2(e);return function(i){let o=kD(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===gn.ConfigsLoaded,ry.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var mee,rp,Ky=k(()=>{"use strict";mee=Ce($2()),rp=Ce(Gy());cy();Vy();Yu();jy();x1();ny();});var F1=k(()=>{"use strict";cy();Vy();Ky();Yu();jy();Bf();iy();});function ip(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Xs.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Xs.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Xs.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Xs,Jy=k(()=>{"use strict";Xs=Ce(ya());});var Gge,Wge,zge,M1=k(()=>{"use strict";F1();Jy();({featuresClient:Gge,createFeature:Wge,useFeaturesClientInitParams:zge}=np("PowerApps-Shell-Test",ip("shell-features")))});var q1=v((Hge,B1)=>{var Zu=new Proxy(function(){return Zu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Zu},apply:function(){return Zu},construct:function(){return{}}}),U1=function(){return Zu};Object.setPrototypeOf(U1,Zu);B1.exports=U1});var gee,yee,V1=k(()=>{"use strict";Iu();gee=Ce(q1()),yee=Ce(ya());});var G1=k(()=>{"use strict";M1();Jy();V1();});var r0e,Zs,n0e,W1=k(()=>{"use strict";G1();Ky();({featuresClient:r0e,createFeature:Zs,useFeaturesClientInitParams:n0e}=np("PowerApps-MakerPortal",ip("powerapps-features")))});var z1,j1,s0e,l0e,u0e,c0e,Yy=k(()=>{"use strict";LD();W1();({feature:z1}=Zs({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:qs.enableAutoInsertionOfCellInRow}})),{feature:j1}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:qs.enableOneGridEvents}}),{feature:s0e}=Zs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:qs.disablePBIComponents}}),{feature:l0e}=Zs({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:qs.enableAgentResponse}}),{feature:u0e,useFeature:c0e}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:qs.enableDelayedLocalizationForCustomControls}})});var J1=v((f0e,K1)=>{var ec=new Proxy(function(){return ec},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ec},apply:function(){return ec},construct:function(){return{}}}),H1=function(){return ec};Object.setPrototypeOf(H1,ec);K1.exports=H1});var nr,ko=k(()=>{"use strict";vt();dt();rr();$u();le();kt();nr=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(E.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(E.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(E.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(E.formControl);if(t&&t.ClassId){let r=ft.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&ft.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===E.formSection||this.NodeName===E.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(E.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(E.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var el,Qy=k(()=>{"use strict";rr();le();kt();el=class extends re{constructor(t,r){super(E.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var Y1,tl,Xy=k(()=>{"use strict";dt();Qy();le();kt();ko();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(Y1||(Y1={}));tl=class extends nr{constructor(t,r){super(E.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(E.EventHandlers);return t&&t.length?t[0].getChildren(E.handler):[]}getAllDependencies(){let t=this.getChildren(E.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(E.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(E.formDependencies,this)),r=this.getFirstChild(E.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new el(r,n.toString()))}}}});var Fn,tc=k(()=>{"use strict";vt();su();dt();ga();le();kt();kn();Fn=class extends re{previewVersion;constructor(t){super(E.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new dr,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(ji.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(E.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let o=i.getNodeName();return o.charAt(0)===ji.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new dr;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===wt.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:n,ControlLayout:0,RequiredLevel:0,Type:this.getAttributeTypeFromClassId(this.ClassId.guidString),IsUnbound:this.getIsUnbound(),IsRequired:this.isRequired,DataFieldName:this.dataFieldName,UniqueId:this.UniqueId&&this.UniqueId.guidString,Id:this.previewVersion?this.id+this.previewVersion:this.id,Label:r.getDisplayName(t.langCode),LabelId:r.labelId&&r.labelId.guidString,Name:null,ShowLabel:r.showlabel,PreviewId:r&&r.id.guidString,Visible:r.visible||t.formModelService.showHiddenElements}}}});var rl,Zy=k(()=>{"use strict";rr();oa();tc();le();kt();rl=class extends Fn{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case hn.Chart:return hn.Chart;case hn.Grid:return hn.Grid;default:return hn.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=hn.Chart:this.chartGridMode=this.enableChartPicker?hn.All:hn.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.dataset)?n[i].getParameters().get(Xt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var nl,eb=k(()=>{"use strict";rr();oa();tc();le();nl=class extends Fn{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.value)?n[i].getParameters().get(Xt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Q1,tb,kr,rc=k(()=>{"use strict";Q1=Ce(J1());ko();le();dt();vt();Xy();tc();$u();ly();G0();kn();ga();Fs();Zy();eb();rb();vs();tb="_",kr=class e extends nr{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(E.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof Fn?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!ba.dependencyFieldCount.containsKey(this.control.id):!ba.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new tl(this,Tu.onLoad))}get dependencies(){let t=this.getChildren(E.formEvents);for(let r of t){let n=r.getChildren(E.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Pf[i])o=Pf[i].replace(/ /g,tb)+tb;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,Q1.trackErrorTrace)(hr,{eventName:`${JT}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===yn.Grid?(l=new rl(this),l.indicationOfSubgrid=!0):o===yn.Lookup?l=new nl(this):l=new Fn(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=ft.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(ft.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!ft.isUnboundFormControlByIdentifier(d)?o!==yn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=ft.GetRowSpan(l),(ft.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||ft.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(ft.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||ft.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||ft.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===E.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(E.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(ay.ONE_COLUMN),n=Number(ay.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(E.formRow)}getParentSection(){return this.getAncestor(E.formSection)}getParentTab(){return this.getAncestor(E.formTab)}getParentForm(){return this.getAncestor(E.form)}isInHeader(){let t=this.getAncestor(E.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(E.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(E.formHeader):this.isInFooter()?this.getAncestor(E.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.FOUR_COLUMN:r="1111";break;default:r="1"}return r}findRowIndexByCellId(t){let r=this.getParentRow().cells.indexOf(this);for(let n=0;n<t.rows.length;n++)if(!R.IsNullOrUndefined(t.rows[n].cells[r])&&this.id.ToString()===t.rows[n].cells[r].id.ToString())return n;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();R.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===yo.ApplicationRequired||a===yo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?yo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??yo.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===E.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===E.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===tb&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var il,nb=k(()=>{"use strict";rr();le();kt();il=class extends re{isInternal;constructor(t,r,n,i){super(E.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var Sa,ib=k(()=>{"use strict";dt();rc();le();kt();Sa=class extends re{isRowAddedOnDragOver;constructor(t){super(E.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(E.formSection)}insertPaddingCellAtIndex(t){let r=new kr(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(E.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function bee(e){switch(e){case va.Left:return Ca.Left;case va.Right:return Ca.Right;case va.Center:return Ca.Center;default:return Ca.Left}}function vee(e){switch(e){case Us.Left:return Bs.Left;case Us.Top:return Bs.Top;default:return Bs.Left}}function X1(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var wee,pi,nc=k(()=>{"use strict";uy();vt();dt();rr();Yy();rc();le();kn();ko();ib();wee=115,pi=class e extends nr{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=je.ONE_COLUMN;break;case 11:t=je.TWO_COLUMN;break;case 111:t=je.THREE_COLUMN;break;case 1111:t=je.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=qe.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+qe.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===je.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${qe.referencePanelNamePrefix}${U.NewGuid()}${qe.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,qe.IsUserDefined),this.addProperty(y.locklevel,qe.LockLevel),this.addProperty(y.showlabel,qe.ShowLabel),this.addProperty(y.showbar,qe.ShowBar),this.addProperty(y.layout,qe.Layout),this.addProperty(y.Fieldlabelalignment,qe.labelAlignment),this.addProperty(y.Fieldlabelposition,qe.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,qe.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,qe.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.FOUR_COLUMN:r="1111";break;default:r="1"}return r}getNumberOfColumns(){return e.getNumericColumnLayoutValue(this.columns)}static getNumericColumnLayoutValue(t){switch(t){case 1:return 1;case 11:return 2;case 111:return 3;case 1111:return 4;default:throw new Error("Unexpected Section Layout Value.")}}getColumnCountValue(){let t=0;return R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Sa(null);if(this.addGrandChild(E.formRows,r),z1.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new kr(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===je.REFERENCE_PANEL&&(n=je.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(E.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(E.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(E.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(E.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(E.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(E.formRows);return t.length===0?[]:t[0].getChildren(E.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return X1(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(E.formColumn)}getParentTab(){return this.getAncestor(E.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=qe.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?qe.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?wee:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.LabelWidth,t.toString())}async getRowsJSON(t){let r=[],n=[];if(this.rows){for(let i of this.rows)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this.id&&this.id.guidString,Rows:await this.getRowsJSON(t),CellLabel:{Width:this.labelwidth,Alignment:bee(this.fieldLabelAlignment),Position:vee(this.fieldLabelPosition)},Columns:X1(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===E.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(qe.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===E.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===E.formFooter||this.NodeName===E.formHeader}}});var $o,op=k(()=>{"use strict";le();kt();nc();$o=class e extends re{constructor(t){super(E.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new pi(E.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}initialize(t,r,n,i=je.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(E.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(E.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(E.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var ap,Z1=k(()=>{"use strict";vt();le();kn();nc();ap=class extends pi{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,qe.columns),this.setDisplayName(r,t)}}});var sp,eL=k(()=>{"use strict";op();le();Z1();sp=class extends $o{addAndIntializeNavBarSection(t,r,n,i){let o=new ap(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var Ki,lp=k(()=>{"use strict";vt();dt();rr();op();le();kt();ko();Ki=class extends nr{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(E.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(E.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=ze.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=ze.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=ze.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=ze.TWO_COLUMN_WIDER_RIGHT;break}t=ze.TWO_COLUMN_CUSTOM_LAYOUT;break;case 3:if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===33&&parseInt(this.columns[2].width,10)===33){t=ze.THREE_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===28&&parseInt(this.columns[1].width,10)===44&&parseInt(this.columns[2].width,10)===28){t=ze.THREE_COLUMN_WIDER_MID;break}t=ze.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,Io.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Io.IsUserDefined),this.addProperty(y.locklevel,Io.LockLevel),this.addProperty(y.showlabel,Io.ShowLabel),this.setDisplayName(n,r)}get TotalSectionsCount(){let t=0;for(let r of this.columns)t+=r.sections.length;return t}initializeColumns(t,r,n,i=je.ONE_COLUMN,o=!0,a){let s=this.getChildren(E.formColumns)[0],l=[];switch(t){case ze.ONE_COLUMN:l.push(100);break;case ze.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case ze.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case ze.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case ze.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case ze.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new $o(s);c.initialize(u,r,n,i),this.addGrandChild(E.formColumns,c)}}initialize(t,r,n,i,o,a=je.ONE_COLUMN,s=!0,l){this.addChild(new re(E.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(E.formColumns);return t.length!==1?[]:t[0].getChildren(E.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(E.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(E.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(E.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===E.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Na,ob=k(()=>{"use strict";vt();le();kt();kn();eL();lp();Na=class extends Ki{constructor(t,r,n){super(t,ze.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(E.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(E.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<qf.FIVE_COLUMN;t++){let r=new sp(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(wD.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function Eee(e){switch(e){case wt.Main:return Oo.Main;case wt.QuickCreate:return Oo.QuickCreate;case wt.QuickViewForm:return Oo.Quick;case wt.Dialog:return Oo.Dialog;default:return Oo.None}}function Aee(e,t){if(t===wt.Main){if(e)switch(e.toLowerCase()){case"low":return Do.Low;case"highreadonlyvalues":return Do.HighReadOnlyValues;default:return Do.HighWithControls}return Do.Low}}var cp,Cee,up,tL=k(()=>{"use strict";DD();cp=Ce(ya());uy();dt();rr();Fs();Yy();le();oa();O0();ga();rc();le();ko();nb();ob();lp();Cee="1920";up=class e extends nr{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(E.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Tf,this._metadataChangeEvent=new Gf}get FormLibraries(){let t=this.getFirstChild(E.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof kr).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof kr){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===E.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new il(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,cp.trackErrorTrace)(YT,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:n.attribute,EventName:n.eventName}}),i}}),r}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?Cee:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===wt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==wt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===wt.Main||this.formType===wt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(E.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(E.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(E.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(E.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Ki(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new Ki(null,ze.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(ze.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(E.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===Io.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(E.formTabs);return t.length!==1?[]:t[0].getChildren(E.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Na)return t}return null}get NavigationNode(){let t=this.getChildren(E.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(E.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(E.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(E.formFooter).length>0}get displayCondition(){let t=this.getChildren(E.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(E.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(E.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(E.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(E.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof kr))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof kr&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Mi.EditableGridControl)||j1.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Mi.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Mi.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===E.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof Na)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,cp.getSessionId)(),EntityLogicalName:this._entityName,FormId:this._formId.guidString,TabAttributes:{},Tabs:await this.getTabsJSON(t),HiddenFields:[],Header:this.header&&await this.header.toJSON(t),Footer:this.footer&&await this.footer.toJSON(t),...this.formType===wt.Main?{HeaderDensity:Aee(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Eee(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:r,BusinessLogic:void 0,FormLibraries:[],Navigation:n,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var dp,ab,rL=k(()=>{"use strict";vt();dt();le();kt();ko();dp=class extends nr{constructor(t){super(E.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(E.formEveryOne)&&this.getChildren(E.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new ab(this))}},ab=class extends re{constructor(t){super(E.formEveryOne,t)}}});var fp,nL=k(()=>{"use strict";le();kt();fp=class extends re{constructor(t,r){super(E.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var ol,sb=k(()=>{"use strict";le();nc();ol=class extends pi{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(E.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var ic,iL=k(()=>{"use strict";le();sb();ic=class extends ol{_customFooter;constructor(t,r){super(E.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var oc,oL=k(()=>{"use strict";le();sb();oc=class extends ol{_customHeader;constructor(t,r){super(E.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var $r,_a=k(()=>{"use strict";vt();rr();le();ko();$r=class e extends nr{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(E.Titles);return t.length===0?[]:t[0].getChildren(E.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(E.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(E.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var ac,aL=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(ac||(ac={}))});var pp,sL=k(()=>{"use strict";dt();le();_a();aL();pp=class extends $r{constructor(t){super(E.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return R.IsNullOrUndefined(r)?ac.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):ac.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var Fe,See,lL,tve,al,lb=k(()=>{"use strict";vt();le();_a();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(Fe||(Fe={}));See=new Map([[Fe.Info,"Info"],[Fe.Sales,"Sales"],[Fe.Service,"Service"],[Fe.Marketing,"Marketing"],[Fe.ProcessCenter,"ProcessCenter"]]),lL=new Map([["Info",Fe.Info],["Sales",Fe.Sales],["Service",Fe.Service],["Marketing",Fe.Marketing],["ProcessCenter",Fe.ProcessCenter]]),tve=new Map([[Fe.Info,9e3],[Fe.Sales,9200],[Fe.Service,9400],[Fe.Marketing,9600],[Fe.ProcessCenter,9800],[Fe.InternetMarketing,1e4],[Fe.Async,10200]]),al=class extends $r{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=See.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var sl,ub=k(()=>{"use strict";le();_a();sl=class extends $r{constructor(t,r){super(E.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(E.formNavBarArea)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var mp,uL=k(()=>{"use strict";dt();le();_a();mp=class extends $r{RelationshipNameUCIRuntime;constructor(t){super(E.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.TitleResourceId)}async toJSON(t){return{Area:this.Area,Show:this.Show||t.formModelService.showHiddenElements,Id:this.Id,Titles:[{Name:t.langCode.toString(),Value:this.getTitle(t.langCode)}],Sequence:this.Sequence.toString(),Privileges:[],TooltipTitles:[],AvailableOffline:!0,PreviewId:this.Id,RelationshipName:this.RelationshipNameUCIRuntime??this.RelationshipName,Icon:null,ViewId:null,Client:null,TitleResourceId:null}}}});var hp,cL=k(()=>{"use strict";le();_a();hp=class extends $r{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var gp,dL=k(()=>{"use strict";vt();le();lb();ub();_a();gp=class extends $r{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(E.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Fe.Info,Fe.Sales,Fe.Service,Fe.Marketing,Fe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>lL.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new sl(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new al(E.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(E.formNavBar)}get id(){return new U(V0,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(E.formNavBarAreas,r),this.addGrandChildAtIndex(E.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var fL={};nn(fL,{ControlType:()=>yn,DeserializationService:()=>fb,DeserializationServiceScope:()=>db,DeserializedFormElementNode:()=>xr});var cb,xr,db,yn,fb,rb=k(()=>{"use strict";cb=Ce(ya());vt();dt();rr();Fs();G0();ga();QT();_D();$u();tL();rc();op();tc();Qy();le();le();rL();kt();kn();Xy();nL();iL();Zy();eb();oL();nb();ib();nc();lp();sL();lb();ub();uL();cL();dL();xr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},db="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(yn||(yn={}));fb=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let m="";throw d.length===0?m="FormXml has no form node.":m="FormXml has multiple form nodes.",(0,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==wt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=ba.getNecessaryLookUpTable(r),i=1;n.containsKey(t)&&(i+=n.getValue(t)),n.upsert(t,i)}appendDefaultDisplayCondition(t){let r='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new up(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===wt.Main&&(this.insertHeaderFooterElementProperties(E.formHeader,d,d.header),this.insertHeaderFooterElementProperties(E.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===E.formHeader?new oc(r,!0):new ic(r,!0);xr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),xr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),xr.prototype.insertProperty.call(i,y.columnName,qe.MarginalControlColumns),xr.prototype.insertProperty.call(i,y.LabelWidth,qe.LabelWidth),xr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new Sa(o);for(let s=0;s<i.maxColumns;s++){let l=new kr(a);xr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),xr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===E.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new xr(`<${t.nodeValue}`,r);if(t.nodeType===Node.COMMENT_NODE)return;let n=this.createModelNode(t,r);return this.populateElementProperties(n,t.attributes),this.populateElementChildren(n,t.childNodes),n}populateElementProperties(t,r){if(!r){let n="attributes is undefined for element: "+t.getNodeName();throw(0,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(xr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===E.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&xr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case E.form:throw new Error("Form node shouldn't be created using this method");case E.formTab:return new Ki(r);case E.formColumn:return new $o(r);case E.formHeader:return new oc(r,!1);case E.formFooter:return new ic(r,!1);case E.formSection:return new pi(E.formSection,r);case E.formRow:return new Sa(r);case E.formCell:return new kr(r);case E.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=yn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=yn.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=yn.Lookup)}return o===yn.Grid?new rl(r):o===yn.Lookup?new nl(r):new Fn(r);case E.formEvent:return new tl(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new el(r,q.EmptyString);case E.Handler:let a=[];return new fp(a,r);case E.formNavigation:return new gp(t.nodeName,r);case E.formNavBarArea:return new al(t.nodeName,r);case E.formNavBarAreas:return new sl(t.nodeName,r);case E.formNavBar:return new pp(r);case E.formNavBarByRelationshipItem:return new mp(r);case E.formNavBarItem:return new hp(r);case E.formDisplayConditions:return new dp(r);case E.library:return new il(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new Rf(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new Vf(r);default:return new xr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,ui.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);ft.CustomControlIdMap.upsert(l,o);break}}break}}}}});var pL={};nn(pL,{SerializationService:()=>pb,SerializationServiceScope:()=>Nee,SerializedFormElementNode:()=>ll});var Nee,ll,pb,mL=k(()=>{"use strict";rr();kt();kn();ob();Nee="SerializationService",ll=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},pb=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=ll.prototype.fetchNodeName.call(t);if(r.charAt(0)===ji.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=ll.prototype.enumerateProperties.call(t),i=ll.prototype.enumerateChildren.call(t);if(!(t instanceof Na)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var yb=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.completeRecordAsStored=ul.completeLabelsAsStored=void 0;var mb=Eo(),_ee="E7A81278-8635-4D9E-8D4D-59480B391C5B",Tee=new Set(["tab","section","cell"]);function Mn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function xo(e,t){return Mn(e).find(r=>r.tagName===t)}function gL(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function hb(e){let t=xo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===_ee:!1}function gb(e,t){var r,n;let i=((r=xo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=xo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function Dee(e,t){if(xo(e,"labels"))return;let r=Mn(e),n=Mn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!gL(r,n.slice(1)))return;let o=Mn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&hb(e)&&gb(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function Iee(e,t){let r=Oee(e.ownerDocument,t),n=Mn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function Oee(e,t){let r=e.createElement("labels");for(let n of Mn(t))r.appendChild(yL(e,n));return r}function yL(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function hL(e,t){let r=xo(e,"labels");return r?Mn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function Pee(e,t,r){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return!1;let n=hL(e,r),i=hL(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function Ree(e,t){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return;let r=xo(e,"labels"),n=xo(t,"labels");if(!r||!n)return;let i=Mn(r),o=Mn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function bL(e,t,r,n){if(e.tagName!==t.tagName)return;if(Tee.has(e.tagName)){let a=Dee(e,t);a&&(Iee(e,a),n.changed=!0),Pee(e,t,r)&&(n.changed=!0);let s=Ree(e,t),l=xo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=yL(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Mn(e),o=Mn(t);gL(i,o)&&i.forEach((a,s)=>bL(a,o[s],r,n))}function vL(e,t,r){if(e===t)return e;let n,i;try{n=(0,mb.parseXmlRoot)(e,""),i=(0,mb.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return bL(n,i,r,o),o.changed?(0,mb.serializeNode)(n):e}ul.completeLabelsAsStored=vL;function Lee(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=vL(n,i,r);return o===n?e:{...e,formxml:o}}ul.completeRecordAsStored=Lee});var UL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var kee=($u(),zr(TD)),$ee=Q(),wL=ct(),V=zd(),xee=cu(),we=cn(),Qi=["web","phone","tablet"],sc={web:"2",phone:"0",tablet:"1"},NL=new Map([["2","web"],["0","phone"],["1","tablet"]]),Fee=["phone","web","tablet"];function bp(e){let t=new Set(e),r=Fee.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Qi.filter(n=>t.has(n))}}ue.pcfEntryLayout=bp;function gr(e){return Array.isArray(e)?e:[]}function pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function lc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vb(e){return{n:`<${e}`,a:[],c:[]}}function _L(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function CL(e){let t=gr(e.c);return t.length===1&&_L(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function vn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function TL(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function wb(e){try{let t=(0,kee.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?TL(String(t)):void 0}catch{return}}ue.nativeClassFor=wb;var Cb=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),DL=new Set(["TwoOptions","Boolean"]),IL=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),Mee=new Map([...[...IL].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),Uee=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function OL(e){return Uee.test(e)&&e!=="__proto__"}function Eb(e){return e!==void 0&&(e==="Enum"||Cb.has(e)||DL.has(e)||IL.has(e))}function PL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function uc(e,t){let r=e!==void 0?Cb.get(e):void 0;if(r&&typeof t!="boolean"){let n=PL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=uc;function Bee(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&lc(r,a)?s=uc(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[vb(s)]})}return i}function RL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Qi.filter(d=>Ab(i).has(d)),l=bp(s),u=Bee(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[vb(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=RL;function Ab(e){return new Set(Qi.filter(t=>e.availableOn[t]))}function yp(e){var t;let r=gr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||gr(r[0].a).length>0)return;let n=gr(r[0].c);return n.every(i=>pt(i)&&!_L(i))?n:void 0}function Ta(e){let t=gr(e?.c);if(t.length===0||!t.every(p=>pt(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=gr(p.a),g=h.length===2?NL.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=bp(o);if(!vn(a.named,o)||i==="")return;let s=yp(n[0]);if(!s||!n.every(p=>vn(yp(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",sc[h]]],b=yp(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&gr(b[0].a).length===0?CL(b[0]):void 0;if(!u||!vn(gr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=gr(p.a),g=CL(p),b=h.map(w=>w[0]);if(g===void 0||!OL(p.n)||lc(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||vn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(vn(b,["static"])||vn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Qi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=Ta;function LL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===uc(r,e))}function kL(e){let t=e.formFactors;return t===void 0?[...Qi]:Array.isArray(t)?Qi.filter(r=>t.includes(r)):[]}function bb(e,t){var r,n,i;if(e.name!==t.binding.name||!vn(kL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Qi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>lc(a,l)&&LL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=bb;function Ct(e){return pt(e)&&e.customControl!==void 0}ue.hasCustomControl=Ct;function Yi(e,t){var r;return t?gr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Sb(e,t){let r=Yi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?Ta(r[0]):void 0}ue.storedBindingOf=Sb;function Nb(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Nb;function qee(e){if(!Nb(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!pt(n)||!n.fieldName||!Ji(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Sb(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=qee;function Ji(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var bn=(e,t)=>({kind:"refused",rule:e,message:t});function Vee(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!Ji(e)}function EL(e,t,r){var n,i;let o=Ta(r);if(!o)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return bn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=pt(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!vn(l,Object.keys(s).sort()))return bn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!LL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>uc(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return bn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=kL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Qi],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!Eb(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return bn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!Vee(o.nativeClass)?bn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function Gee(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>Ct(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Yi(e.bag,t)}:void 0}function $L(e,t){let r=new Map,n=Wee(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:Hee(u),uid:(0,V.controlUniqueId)(c),bound:Ct(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;pt(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!pt(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let P=m.findIndex(D);return P<0?void 0:m.splice(P,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(P=>P.bound&&P.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let P=D.cell?l(c,D.cell):void 0;return!P||!l(d,D.cell)||!m.includes(P)?!0:(m.splice(m.indexOf(P),1),f.includes(P)&&D.uid!==P.uid&&AL(D.control)&&r.set(D.control,SL(P.uid)),!1)}),b=[],w=(D,P)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!P||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&AL(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let L=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?SL(O[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function Wee(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=pt(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||Ct(a)||o>1)&&n.add(i)}return n}function AL(e){return Ct(e)||e.genPage===void 0&&Ji((0,V.effectiveClassId)(e))}function zee(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!pt(l)||Ct(l)||l.genPage!==void 0||!Ji((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Yi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var jee="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function SL(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function Hee(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function cc(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Yi(e.bag,o),s=r?$L(e,r).get(t):void 0;if(s!==void 0)return bn("pcf-binding-unique-id",s);let l=r?Gee(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?Ta(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&vn(c[0],a[0]))return EL(t,i,a[0]);let f=a.length===1?Ta(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&bb(i,d)&&bb(i,f)?{kind:"unchanged"}:bn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=EL(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:bn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=cc;function xL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function Kee(e){let t=n=>Ct(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,wL.newId)()),n.id||(n.id=(0,wL.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=Kee;function Jee(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!Ct(o)||!pt(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=cc(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):xL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=Jee;function Yee(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!Ct(p)||!pt(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Yi(u,h).length>0&&c.set(p,{plan:cc(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=pt(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!Ct(g))continue;let b=(0,V.controlUniqueId)(g),w=Yi(t.bag,b),C=Yi(u,b);if(w.length!==1||C.length!==1||!vn(w[0],C[0])||!Ta(C[0]))continue;let S=p.get(b);if(S&&!Ct(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=Ta(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),Qee(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=gr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!Ct(m)||!pt(m.customControl))continue;Ji(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new $ee.ValidationError("form",e.id,[(0,we.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&Xee(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?wb(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let C=((l=(s=gr((a=m.bag)===null||a===void 0?void 0:a.a).find(O=>O[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=C.startsWith("{")?C:`{${p}}`;d.node.c.push(RL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=Yee;function Qee(e,t){pt(e.bag)&&(e.bag.a=gr(e.bag.a).filter(r=>r[0]!==t))}function Xee(e,t){var r,n;let i=gr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=yp(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[vb(uc(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=NL.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=bp(e.factors),p=m.defaults.map(g=>{let b=a.find(C=>c(C)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",sc[g]]],w}),h=m.named.map(g=>{let b=s.find(C=>c(C)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",sc[g]]],w});e.description.c=[...p,...h]}function Zee(e){return(0,V.typedCellSites)(e).some(({cell:t})=>Ct(t.control))}ue.mayCommitPcfState=Zee;function ete(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!Ct(a))continue;let s=Sb(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=gr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Ji(a.classId)||a.type!==l||u!==void 0&&!Ji(u[1])||!vn(a.customControl,s.binding))&&(Ji(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Ji(u[1])&&(u[1]=TL(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=ete;var tte=new Set(["name","parameters","formFactors"]);function rte(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;Ct(s)&&ite(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&ote(e,t,n),n}ue.pcfBindingIssues=rte;function nte(e,t,r){let n=r.length;if(!pt(e))return r.push((0,we.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))tte.has(i)||r.push((0,we.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,we.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!pt(e.parameters))r.push((0,we.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,we.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Qi.includes(a))&&new Set(i).size===i.length||r.push((0,we.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function ite(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=nte(t.customControl,l,i);t.fieldName||i.push((0,we.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,we.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Nb(e)||i.push((0,we.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,we.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=cc(e,t,o,a);f.kind==="refused"&&i.push((0,we.issue)(l,f.rule,f.message))}function ote(e,t,r){var n;let i=new Map,o=$L(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=pt(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),pt(l.control)&&!Ct(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,we.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!Ct(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||Ct(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,we.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):vn(Yi(t.bag,u),Yi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,we.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,we.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of zee(e,t))s.has(l)||r.push((0,we.issue)(l,"pcf-binding-unique-id",jee))}var ate=new Set(["Form.Card"]),ste="MscrmControls.ModelForm.ModelFormControl";function FL(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!OL(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===ste||n.some(s=>s.defaultType!==void 0&&ate.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Eb(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function lte(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function ML(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Cb.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:PL(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&DL.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?Mee.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function ute(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!Ct(d)||!d.fieldName)continue;let f=d.customControl;if(!pt(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=cc(e,d,r,!0);if(p.kind==="edit"){xL(p)&&fte(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,we.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=FL(h.value,f.name);if(b){l.push((0,we.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),C=g.kind==="found"?g.value:void 0,S=C?(a=(0,xee.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&wb(C)!==void 0&<e(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,we.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,we.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=pt(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Le=L.get(x);if(!Le){l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let lr=ML(Le,K);lr&&l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${lr}`))}for(let x of L.values())x.required&&!lc(I,x.name)&&!x.defaultValue&&l.push((0,we.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Ab(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,we.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=ute;function cte(e,t){return t===void 0||!Eb(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function dte(e,t,r){var n,i;let o=FL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!lc(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function fte(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,we.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=dte(u.value,t.name,e.stored);if(c){l.push((0,we.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];cte(d.get(h),g)||l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=ML(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Ab(u.value);e.added.some(h=>!p.has(h))&&l.push((0,we.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var tk=v(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.classIdForAttributeType=Mr.QUICK_VIEW_CLASS_ID=Mr.NOTES_CLASS_ID=Mr.SUBGRID_CLASS_ID=Mr.formRegistration=Mr.FormAdapter=void 0;var Xi=(vt(),zr(VT)),BL=(dt(),zr(GT)),pte=(kt(),zr(zT)),Et=(le(),zr(WT)),ot=(ga(),zr(jT)),mte=(rb(),zr(fL)),hte=(mL(),zr(pL)),At=wo(),qL=jr(),Fr=cn(),gte=e0(),dl=ct(),yte=yb(),ir=zd(),mi=UL(),cl=Q(),Pb=oe(),_b=Co(),HL=sa(),bte={[Et.FormType.Main]:"Main",[Et.FormType.QuickCreate]:"QuickCreate",[Et.FormType.QuickViewForm]:"QuickView",[Et.FormType.Card]:"Card"},vp={Main:Et.FormType.Main,QuickCreate:Et.FormType.QuickCreate,QuickView:Et.FormType.QuickViewForm,Card:Et.FormType.Card},vte=new Map(Object.entries(ot.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Rb(e){var t;return e&&(t=vte.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function dc(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Da(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function KL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Lb(e,t){var r,n;let i=KL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>Da(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=Da(a).get("description"))!==null&&n!==void 0?n:""}function wte(e){let t=KL(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function JL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Tb(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function fc(e){return String(e??"").replace(/[{}]/g,"")}function Db(e){return`{${fc(e)}}`}function Ib(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Cp(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,At.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:dc(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,At.rawFromNode)(u)})}),{modeled:s,bag:{a:dc(e),c:o,w:{n:a.getNodeName(),a:dc(a),c:l}}}}function YL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,At.rawFromNode)(o)})}),{modeled:n,bag:{a:dc(e),c:i}}}function VL(e,t){let{modeled:r,bag:n}=Cp(e,"tabs","tab");return{tabs:r.map(i=>Cte(i,t)),bag:n}}function Cte(e,t){var r,n;let i=Da(e),{modeled:o,bag:a}=Cp(e,"columns","column");return{id:(r=i.get("id"))!==null&&r!==void 0?r:"",name:(n=i.get("name"))!==null&&n!==void 0?n:"",label:Lb(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>Ete(s,t)),bag:a}}function Ete(e,t){let r=Da(e),{modeled:n,bag:i}=Cp(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>Ate(o,t)),bag:i}}function Ate(e,t){var r,n,i;let o=Da(e),{modeled:a,bag:s}=Cp(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:Lb(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:JL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>Ste(l,t)),bag:s}}function Ste(e,t){let{modeled:r,bag:n}=YL(e,"cell",!1);return{cells:r.map(i=>Nte(i,t)),bag:n}}function Nte(e,t){var r;let n=Da(e),{modeled:i,bag:o}=YL(e,"control",!0),a=Lb(e,t),s=n.get("showlabel")==="true",l=i[0]?_te(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Ib(n.get("colspan"),1),rowspan:Ib(n.get("rowspan"),1),control:l,bag:o}}function _te(e,t,r){var n,i;let o=Da(e),a=fc((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Rb(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:wte(e),bag:{a:dc(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,At.rawFromNode)(l)}))}}}function Uo(e){return e.a.length===0&&e.c.length===0&&!e.w}function QL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Ia(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=Uo(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=QL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,At.mergeAttrs)(e.a,o)}var Fo=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Mo=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),GL=(e,t,r=1)=>({key:e,matches:n=>Ib(n,r)===t,render:()=>String(t),absentDefault:String(r)});function kb(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Ob(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Pb.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function Tte(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function Dte(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function $b(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||Uo(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:kb(t,r)},...a]}}if(Tte(e.c[n].node,r)===t)return e;let i=Dte(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function Ite(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function Ote(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function Pte(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function Rte(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||Uo(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Ob(t)}]}}if(Ote(Ite(e.c[r].node),t))return e;let n=Ob(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Ep(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,At.spliceChildren)(e.w.c,r)};return(0,At.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,At.spliceChildren)(e.c,[...i,o])}function Lte(e,t){let r=e.tabs.map(n=>kte(n,t));return{n:"form",a:Ia(e.bag,[]),c:e.tabs.length===0&&Uo(e.bag)?[]:Ep(e.bag,"tabs",r,()=>[])}}function XL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[kb(t,r)]:[]}function kte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("expanded",e.expanded),Mo("visible",e.visible,!0)],n=e.columns.map(o=>$te(o,t)),i=$b(e.bag,e.label,t);return{n:"tab",a:Ia(i,r),c:Ep(i,"columns",n,()=>XL(i,e.label,t))}}function $te(e,t){let r=e.width!==void 0?[Fo("width",e.width)]:[],n=e.sections.map(i=>xte(i,t));return{n:"column",a:Ia(e.bag,r),c:Ep(e.bag,"sections",n,()=>[])}}function xte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("showlabel",e.showLabel),Mo("visible",e.visible,!0),{key:"columns",matches:o=>JL(o)===e.columns,render:()=>Tb(e.columns),absentDefault:Tb(1)}],n=e.rows.map(o=>Fte(o,t)),i=$b(e.bag,e.label,t);return{n:"section",a:Ia(i,r),c:Ep(i,"rows",n,()=>XL(i,e.label,t))}}function Fte(e,t){let r=e.cells.map(n=>Mte(n,t));return{n:"row",a:Ia(e.bag,[]),c:Uo(e.bag)?r:(0,At.assembleChildren)(e.bag,r)}}function Mte(e,t){let r=e.control?e.control.showLabel:QL(e.bag,"showlabel")==="true",n=[Fo("id",e.id),Mo("showlabel",r),Mo("visible",e.visible,!0),GL("colspan",e.colspan),GL("rowspan",e.rowspan)],i=e.control?[Ute(e.control)]:[],o;if(Uo(e.bag))o=[...e.control&&e.control.label?[kb(e.control.label,t)]:[],...i];else{let a=e.control?$b(e.bag,e.control.label,t):e.bag;o=(0,At.assembleChildren)(a,i)}return{n:"cell",a:Ia(e.bag,n),c:o}}function Ute(e){let t=[Fo("id",e.id),{key:"classid",matches:i=>fc(i)===e.classId,render:()=>Db(e.classId||String(ot.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Fo("datafieldname",e.fieldName)),t.push(Mo("disabled",e.isReadOnly)),t.push(Mo("isrequired",e.isRequired));let r=e.fieldName===null?Pte(e.bag,"datafieldname"):e.bag,n;return Uo(r)?n=Object.keys(e.parameters).length>0?[Ob(e.parameters)]:[]:n=(0,At.assembleChildren)(Rte(r,e.parameters),[]),{n:"control",a:Ia(r,t),c:n}}var Bte={make:(e,t)=>new pte.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function WL(e,t,r,n){(0,_b.installDomShim)();let i=Vte(e,r);(0,ir.reconcileEmbedDescriptions)(i,n),(0,mi.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,At.rebuildRaw)(Lte(i,t),Bte,null);return new hte.SerializationService(t).serializeFormXmlNode(o)}function qte(e){return JSON.parse(JSON.stringify(e))}function Vte(e,t){let r=qte(e);r.bag||(r.bag=(0,At.emptyBag)()),r.tabs||(r.tabs=[]),Yte(r.bag),t&&Gte(r,t);for(let n of r.tabs)Wte(n);return r}function Gte(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";xb(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=ek(s.attributeType)))})}function zL(e){let t=[];return xb(e,r=>t.push(r)),t}function xb(e,t){var r,n,i,o,a;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function Wte(e){e.id||(e.id=Xi.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.expanded===void 0&&(e.expanded=!0),e.visible===void 0&&(e.visible=!0),e.columns||(e.columns=[]);for(let t of e.columns)zte(t);e.bag||(e.bag=(0,At.emptyBag)())}function zte(e){e.sections||(e.sections=[]);for(let t of e.sections)jte(t);e.bag||(e.bag=(0,At.emptyBag)()),e.width===void 0&&Uo(e.bag)&&(e.width="100%")}function jte(e){e.id||(e.id=Xi.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.showLabel===void 0&&(e.showLabel=!1),e.visible===void 0&&(e.visible=!0),e.columns===void 0&&(e.columns=1),e.rows||(e.rows=[]);for(let t of e.rows)Hte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Hte(e){e.cells||(e.cells=[]);for(let t of e.cells)Kte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Kte(e){(0,ir.hasGenPage)(e.control)&&(0,ir.applyEmbedCellDefaults)(e),e.id||(e.id=Xi.Guid.NewGuid()),e.visible===void 0&&(e.visible=!0),e.colspan===void 0&&(e.colspan=1),e.rowspan===void 0&&(e.rowspan=1),e.control===void 0&&(e.control=null),e.control&&Jte(e.control),e.bag||(e.bag=(0,At.emptyBag)())}function Jte(e){var t;(0,ir.hasGenPage)(e)&&(0,ir.applyEmbedControlDefaults)(e),e.id||(e.id=Xi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(ot.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Rb(String(e.classId))),e.isRequired===void 0&&(e.isRequired=!1),e.isReadOnly===void 0&&(e.isReadOnly=!1),e.label===void 0&&(e.label=(t=e.fieldName)!==null&&t!==void 0?t:""),e.showLabel===void 0&&(e.showLabel=!0),(e.parameters===void 0||e.parameters===null)&&(e.parameters={});for(let r of Object.keys(e.parameters))(0,Pb.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,At.emptyBag)())}function Yte(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!jL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Db(Xi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!jL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Db(Xi.Guid.NewGuid())])}}var wp=class{constructor(t=HL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=VL(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=bte[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,ir.projectGenPageEmbeds)(l),(0,mi.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:WL(t,this.lcid),formid:t.id||(0,dl.newId)(),objecttypecode:t.entityLogicalName,type:vp[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:t.status==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,dl.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,_b.installDomShim)();let f=BL.ScriptUtilities.ParseXml(c),m=Qte(f),p=this.deserializeDocument(d,f);return Xte(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,ir.genPageEmbedIssues)(t);if(i.length>0)throw new cl.ValidationError("form",t.id,i);let o=(0,mi.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new cl.ValidationError("form",t.id,o);let a=(0,mi.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,cl.attachCause)(new cl.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new cl.ValidationError("form",t.id,a.issues);return{formxml:WL(t,this.lcid,n,r),name:t.name,type:vp[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return xb(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,mi.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,ir.genPageEmbedIssues)(t),...(0,mi.pcfBindingIssues)(t)];if(p.length>0)throw new cl.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:lre(this.lcid),g=h!==void 0?h:t.tabs.map(C=>Zte(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,dl.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:vp[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(Et.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=zL(t);zL(w).forEach((S,O)=>{C[O]&&C[O].label===void 0&&delete S.label,C[O]&&C[O].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(C[O].genPage))),C[O]&&C[O].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(C[O].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,dl.assignMissingIds)(t)}completeAsStored(t,r){return(0,yte.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,mi.mintPcfIdentity)((0,ir.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,ir.mayCommitEmbedState)(t)||(0,mi.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,dl.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:vp[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:Et.FormActivationState.Active}),{bag:d}=VL(c,this.lcid),f=(0,mi.commitPcfState)((0,ir.commitEmbedState)(t,(l=(0,ir.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Rb);return{artifact:f,baseline:f}}validate(t){return yre(t)}deserialize(t){return(0,_b.installDomShim)(),this.deserializeDocument(t,BL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new mte.DeserializationService(this.lcid).deSerializeFormXml(r,new Xi.Guid(t.formid),t.objecttypecode,Et.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!n)throw new Error("FormXml could not be deserialized into a Form model.");return n}readActivationStatus(t){return t.formactivationstate===Et.FormActivationState.InActive?"Inactive":"Active"}};Mr.FormAdapter=wp;var ZL=["header","footer","DisplayConditions"];function Qte(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&ZL.includes(i.nodeName)&&n.add(i.nodeName);return n}function Xte(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=ZL.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Un(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Fb(e,t){return e?`<labels><label description="${Un(e)}" languagecode="${t}" /></labels>`:""}function Mb(e){return e&&e.length>0?fc(e):(0,dl.newId)()}function Zte(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[sre()]).map(l=>ere(l,t)).join("");return`<tab id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${Fb(e.label,t)}<columns>${s}</columns></tab>`}function ere(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>tre(o,t)).join("");return`<column width="${Un((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function tre(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>rre(l,t)).join("");return`<section id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${Tb((a=e.columns)!==null&&a!==void 0?a:1)}">${Fb(e.label,t)}<rows>${s}</rows></section>`}function rre(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>nre(n,t)).join("")}</row>`}function nre(e,t){var r,n,i,o,a;let s=ire(e),l=s.control,u=l?Fb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?ore(l):"";return`<cell id="{${Un(Mb(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function ire(e){if(!(0,ir.hasGenPage)(e.control))return e;let t={...e.control};(0,ir.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,ir.applyEmbedCellDefaults)(r),r}function ore(e){var t,r,n;let i=e.fieldName?` datafieldname="${Un(e.fieldName)}"`:"",o=are(e.parameters),a=e.classId?fc(e.classId):String(ot.ControlClassId.TextboxControl);return`<control id="${Un((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Un(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function are(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Pb.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Un(e[n])}</${n}>`).join("")}</parameters>`)}function sre(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function lre(e){return`<tab id="{${Xi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Xi.Guid.NewGuid()}}" name="section_general" showlabel="false" visible="true" columns="1"><labels><label description="General" languagecode="${e}" /></labels><rows></rows></section></sections></column></columns></tab>`}function ure(e=HL.DEFAULT_LCID){return{adapter:new wp(e),api:gte.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,qL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,qL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Mr.formRegistration=ure;var cre=new Set(["id","name","label","expanded","visible","columns","bag"]),dre=new Set(["id","width","sections","bag"]),fre=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),pre=new Set(["id","cells","bag"]),mre=new Set(["id","visible","colspan","rowspan","control","bag"]),hre=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),gre={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function yre(e){let t=[];return(0,Fr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Fr.rejectUnknownKeys)(n,cre,o,"tab",t),(0,Fr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Fr.rejectUnknownKeys)(s,dre,u,"column",t),(0,Fr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Fr.rejectUnknownKeys)(d,fre,m,"section",t),(0,Fr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Fr.rejectUnknownKeys)(h,pre,b,"row",t),(0,Fr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Fr.rejectUnknownKeys)(C,mre,O,"cell",t,gre);let L=C.control;L!=null&&!(0,Fr.isJsonObject)(L)?t.push((0,Fr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Fr.isJsonObject)(L)&&(0,Fr.rejectUnknownKeys)(L,hre,`${O}/control`,"control",t)})})})})}),t.push(...(0,ir.genPageEmbedIssues)(e)),t.push(...(0,mi.pcfBindingIssues)(e)),t}Mr.SUBGRID_CLASS_ID=ot.ControlClassId.SubgridControl;Mr.NOTES_CLASS_ID=ot.ControlClassId.TimelineControl;Mr.QUICK_VIEW_CLASS_ID=ot.ControlClassId.QuickViewControl;var bre={Lookup:String(ot.ControlClassId.LookupControl),Customer:String(ot.ControlClassId.LookupControl),Owner:String(ot.ControlClassId.LookupControl),PartyList:String(ot.ControlClassId.PartyListControl),Boolean:String(ot.ControlClassId.BooleanControl),DateTime:String(ot.ControlClassId.DateTimeControl),Decimal:String(ot.ControlClassId.DecimalControl),Double:String(ot.ControlClassId.FloatingNumberControl),Money:String(ot.ControlClassId.CurrencyControl),Integer:String(ot.ControlClassId.IntegerControl),BigInt:String(ot.ControlClassId.IntegerControl),Memo:String(ot.ControlClassId.TextAreaControl),String:String(ot.ControlClassId.TextboxControl)},vre="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function ek(e){return e==="Picklist"||e==="State"||e==="Status"?vre:e&&bre[e]||String(ot.ControlClassId.TextboxControl)}Mr.classIdForAttributeType=ek;function jL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Ub=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.viewApi=fl.findDefaultViews=void 0;var ok=Tt(),yr=fe(),Bn=oe(),wre=ys(),rk="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",Cre="savedqueryid,name,returnedtypecode,querytype,isdefault",Ere=60*1e3;function Ap(e){return(e.localName||e.nodeName).toLowerCase()}function pc(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function Are(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new wre.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Ap(n)==="fetch"?n:void 0}function Sre(e){for(let t=e.parentNode;t;t=t.parentNode)if(Ap(t)==="link-entity")return!0;return!1}function nk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=Are(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Ap(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Ap(u)==="link-entity").every(u=>{var c;return((c=pc(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!Sre(l)&&pc(l,"entityname")===void 0&&((n=pc(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=pc(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&pc(l,"value")===String(t)}function Nre(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function _re(e){var t,r;let n=e.filter(a=>nk(a,0)),i=e.filter(a=>nk(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=Ere&&Nre(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function Tre(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Bn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Bn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,ok.collectPages)(e,a,`findDefaultViews('${t}')`),l=_re(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}fl.findDefaultViews=Tre;async function Dre(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Bn.odataPathLiteral)(t)}')${(0,Bn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function ik(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await Dre(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}fl.viewApi={async get(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]);return{raw:(0,yr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]),i=(0,yr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Bn.odataQuery)([["$select",Cre],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Bn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,ok.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,yr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await ik(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,yr.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,yr.ensureSuccess)(await(0,yr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,yr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,yr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Bn.normalizeGuid)(t,"id"),a=(0,yr.echoWrite)("savedqueryid",{"If-Match":(0,yr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await ik(e,i.layoutxml,i.returnedtypecode),u=(0,yr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,yr.readEtag)(u)}},delete(e,t){return(0,yr.deleteRecord)(e,"savedqueries",t)}}});var Ck=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.viewRegistration=pl.ViewAdapter=void 0;var fk=Q(),en=cn(),Bb=wo(),Oa=Eo(),ak=jr(),Ire=Ub(),qb=Co(),Ore=ct(),pk=100,Np=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,qb.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,Oa.parseXmlRoot)(c,"<fetch/>"),m=(0,Oa.parseXmlRoot)(d,"<grid/>"),p=hk(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:Rre(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:mk(m,f),filters:yk(f),sort:gk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,Oa.projectElementBag)(f):void 0,layoutBag:d?(0,Oa.projectElementBag)(m):void 0}}fromArtifact(t){(0,qb.installDomShim)();let{fetchxml:r,layoutxml:n}=sk(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a;(0,qb.installDomShim)();let{fetchxml:s,layoutxml:l}=sk(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,Ore.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,en.childObjects)(n,"columns","","column",r),(0,en.childObjects)(n,"sort","","sort",r),(0,en.childObjects)(n,"linkEntities","","linkEntity",r),Pre(n.linkEntities,r);let i=n.filters;return i!=null&&((0,en.isJsonObject)(i)?Vb(i,"/filters",r):r.push((0,en.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};pl.ViewAdapter=Np;function Pre(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,en.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,en.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,en.isJsonObject)(i)?Vb(i,`/linkEntities/${n}/filters`,t):t.push((0,en.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Vb(e,t,r){(0,en.childObjects)(e,"conditions",t,"condition",r),(0,en.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Vb(i,`${t}/groups/${o}`,r))}function Rre(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function mk(e,t){var r;let n=_p(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?pk:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function _p(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function hk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Wt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Wt(n,"filter").find(c=>!Tp(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Gb(u)}:{}})}return r}function gk(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function yk(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Wt(t,"filter").filter(i=>!Tp(i)).map(Gb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Tp(e){if(e.getAttribute("isquickfindfields")==="1"||bk(e))return!0;if(Wt(e,"filter").length>0)return!1;let t=Wt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Wt(r,"value").length>0||kre(r))}function bk(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?bk(n):n.tagName!=="condition"))return!0}return!1}var Lre=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function kre(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!Lre.has(i))return!0}return!1}function Gb(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(Gb(l))}return{type:n,conditions:i,groups:o}}function Wt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var Wb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function $re(e,t){let r=_p(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Wb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function xre(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Wb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new fk.ValidationError("view",e.id,a.map(s=>(0,en.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function sk(e){var t,r;let n=Fre(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!lk(e.fetchBag)||!lk(e.layoutBag))return{fetchxml:Yre({...e,columns:n,sort:i,filters:o}),layoutxml:Qre({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=uk(e.fetchBag,"fetch",a),l=uk(e.layoutBag,"grid",a),u=mk(l,s),c=!Sp(n,u),d=!Sp(i,gk(s)),f=!Sp(o,yk(s)),m=e.linkEntities,p=m!==void 0&&!Sp(m,hk(s)),h=p?$re(s,u):void 0;return p&&Hre(a,s,m),p&&(Jre(e,s,n,h),xre(e,s,n,h)),c?(ck(a,s,n,u),Vre(a,l,n)):p&&ck(a,s,n,u),d&&zre(a,s,i),f&&jre(a,s,o),{fetchxml:(0,Oa.serializeNode)(s),layoutxml:(0,Oa.serializeNode)(l)}}function Fre(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:pk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function lk(e){return!!e&&(e.c.length>0||e.a.length>0)}function uk(e,t,r){let n={n:t,a:(0,Bb.mergeAttrs)(e.a,[]),c:(0,Bb.spliceChildren)(e.c,[])};return(0,Bb.rebuildRaw)(n,(0,Oa.domEngine)(r),null)}function ck(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=_p(t);for(let p of n)u.has(l(p))||(Ure(s,p),p.relatedEntity&&c.has(p.name)&&Mre((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=_p(t),m=new Set(Wt(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!wk(s,p.relatedEntity)))continue;let g=Bre(e,s,p.relatedEntity),b=e.createElement("attribute");vk(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),qre(s,h),m.add(p.name)}}function vk(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function Mre(e,t){if(e){for(let r of Wt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function Ure(e,t){if(t.relatedEntity){for(let r of Wt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Wt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Wt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function wk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Wt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function Bre(e,t,r){let n=wk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function qre(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function Vre(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=Gre(n);if(Wre(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function Gre(e){return Wt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Wre(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].getAttribute("name")!==t[r].name)return!1;return!0}function zre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Wt(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function jre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Wt(n,"filter"))Tp(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(mc(e,r))}}function Sp(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Hre(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Wt(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,O)=>O!==g&&!s[O]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){dk(e,g,p);return}let b=e.createElement("link-entity");dk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var Kre=new Set(["inner","outer"]);function Jre(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Wb(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new fk.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,en.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function dk(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):Kre.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Wt(t,"filter").find(o=>!Tp(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?mc(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function Yre(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(mc(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){vk(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(mc(r,e.filters)),new XMLSerializer().serializeToString(r)}function mc(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(mc(e,n));return r}function Qre(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function Xre(){return{adapter:new Np,api:Ire.viewApi,publish:(e,t,r)=>(0,ak.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,ak.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}pl.viewRegistration=Xre});function Dp(e,t){return e==="SetFieldValue"&&t!==void 0&&Zre.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Zre,zb=k(()=>{"use strict";Zre=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function Ek(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function jb(e){return e==="AllForms"||Ek(e)?1:2}function Hb(e){return Ek(e)?e:null}function Ak(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:ml.WorkflowCategory.BusinessRule,type:ml.WorkflowTypeCode.Definition,mode:1,scope:ml.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:jb(e.scope),processtriggerformid:Hb(e.scope)}}var ml,Sk=k(()=>{"use strict";ml=Ce(lo());});function Nk(e,t=0){return(zt[e[t+0]]+zt[e[t+1]]+zt[e[t+2]]+zt[e[t+3]]+"-"+zt[e[t+4]]+zt[e[t+5]]+"-"+zt[e[t+6]]+zt[e[t+7]]+"-"+zt[e[t+8]]+zt[e[t+9]]+"-"+zt[e[t+10]]+zt[e[t+11]]+zt[e[t+12]]+zt[e[t+13]]+zt[e[t+14]]+zt[e[t+15]]).toLowerCase()}var zt,_k=k(()=>{zt=[];for(let e=0;e<256;++e)zt.push((e+256).toString(16).slice(1))});function Kb(){return Ip>Op.length-16&&((0,Tk.randomFillSync)(Op),Ip=0),Op.slice(Ip,Ip+=16)}var Tk,Op,Ip,Dk=k(()=>{Tk=require("crypto"),Op=new Uint8Array(256),Ip=Op.length});var Ik,Jb,Ok=k(()=>{Ik=require("crypto"),Jb={randomUUID:Ik.randomUUID}});function ene(e,t,r){if(Jb.randomUUID&&!t&&!e)return Jb.randomUUID();e=e||{};let n=e.random??e.rng?.()??Kb();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Nk(n)}var br,Pk=k(()=>{Ok();Dk();_k();br=ene});var Yb=k(()=>{Pk()});var Rk=k(()=>{"use strict";});function Lk(e){return e!=null&&tne.has(e)}function Pp(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var tne,Qb=k(()=>{"use strict";tne=new Set(["Picklist","State","Status"])});var Rp=v(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.WorkflowConditionOperator=wn.WorkflowAttributeType=wn.SystemStep=wn.FieldRequiredLevelTypes=wn.AttributeDateTimeBehavior=void 0;wn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};wn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};wn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};wn.WorkflowAttributeType={Boolean:"0",Customer:"1",DateTime:"2",Decimal:"3",Float:"4",Integer:"5",Lookup:"6",Money:"7",Owner:"8",PartyList:"9",Picklist:"10",Key:"11",State:"12",Status:"13",String:"14",UniqueIdentifier:"15",EntityNameReference:"16",Entity:"17",EntityCollection:"18",BpfProcess:"19",BpfStageCategory:"20",BpfStage:"21",EntityReferenceCollection:"22",MultiSelectPicklist:"23",BigType:"24"};wn.WorkflowConditionOperator={IsNull:"0",NotNull:"1",LogicalAnd:"2",LogicalOr:"3",IN:"4",NotIn:"5",NotInNull:"51",Equal:"6",NotEqual:"7",Contains:"8",DoesNotContain:"9",BeginsWith:"10",DoesNotBeginWith:"11",EndsWith:"12",DoesNotEndWith:"13",GreaterThan:"14",GreaterThanOrEqual:"15",LessThan:"16",LessThanOrEqual:"17",EqualUserId:"18",NotEqualUserId:"19",On:"20",NotOn:"21",OnOrAfter:"22",OnOrBefore:"23",Yesterday:"24",Today:"25",Tomorrow:"26",NextSevenDays:"27",LastSevenDays:"28",NextWeek:"29",LastWeek:"30",ThisWeek:"31",NextMonth:"32",LastMonth:"33",ThisMonth:"34",NextYear:"35",LastYear:"36",ThisYear:"37",Anytime:"38",LastXHours:"39",NextXHours:"40",LastXDays:"41",NextXDays:"42",LastXWeeks:"43",NextXWeeks:"44",LastXMonths:"45",NextXMonths:"46",LastXYears:"47",NextXYears:"48",Under:"49",NotUnder:"50"}});function Lp(e){return e!=null&&$k.includes(e)}function Xb(e){return e===ae.WorkflowAttributeType.Integer}function Zb(e,t){return t===ae.WorkflowConditionOperator.Equal||t===ae.WorkflowConditionOperator.NotEqual?e:rne.includes(t)?$k.includes(e)||e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:t===ae.WorkflowConditionOperator.On||t===ae.WorkflowConditionOperator.NotOn?e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:ae.WorkflowAttributeType.String}function xk(e){let t=e.leftWorkflowType??e.valueWorkflowType??ae.WorkflowAttributeType.String,r=hc[e.operator]??ae.WorkflowConditionOperator.Equal;return Zb(t,r)}function Fk(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!kk.test(o)||!kk.test(a)||o.length>1&&o.startsWith("0")||o.length>nne?!1:t!==ae.WorkflowAttributeType.Integer||i.length===1}var ae,hc,$k,rne,kk,nne,ev=k(()=>{"use strict";ae=Ce(Rp());hc={Equals:ae.WorkflowConditionOperator.Equal,DoesNotEqual:ae.WorkflowConditionOperator.NotEqual,IsGreaterThan:ae.WorkflowConditionOperator.GreaterThan,IsLessThan:ae.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:ae.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:ae.WorkflowConditionOperator.LessThanOrEqual,Contains:ae.WorkflowConditionOperator.Contains,DoesNotContain:ae.WorkflowConditionOperator.DoesNotContain,BeginsWith:ae.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:ae.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:ae.WorkflowConditionOperator.EndsWith,DoesNotEndWith:ae.WorkflowConditionOperator.DoesNotEndWith,On:ae.WorkflowConditionOperator.On,NotOn:ae.WorkflowConditionOperator.NotOn,ContainsData:ae.WorkflowConditionOperator.NotNull,DoesNotContainData:ae.WorkflowConditionOperator.IsNull},$k=[ae.WorkflowAttributeType.Decimal,ae.WorkflowAttributeType.Float,ae.WorkflowAttributeType.Integer,ae.WorkflowAttributeType.Money],rne=[ae.WorkflowConditionOperator.GreaterThan,ae.WorkflowConditionOperator.GreaterThanOrEqual,ae.WorkflowConditionOperator.LessThan,ae.WorkflowConditionOperator.LessThanOrEqual];kk=/^\d*$/,nne=28});var Mk=k(()=>{"use strict";});function qn(e){return!ine.has(e)}function tv(e){return e==="Equals"||e==="DoesNotEqual"}function kp(e){return Bk.has(e)?one:cne.has(e)?ane:qk.has(e)?sne:fne.has(e)?une:lne}function Vk(e){return kp(e)[0]}function Gk(e,t){return kp(t).includes(e)}function Uk(e){return Bk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":qk.has(e)?"date":dne.has(e)?"boolean":"other"}function $p(e,t){let r=Uk(e),n=Uk(t);return r==="other"||n==="other"?e===t:r===n}var ine,one,ane,sne,lne,une,Bk,cne,qk,dne,fne,xp=k(()=>{"use strict";Mk();ine=new Set(["ContainsData","DoesNotContainData"]);one=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],ane=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],sne=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],lne=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],une=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Bk=new Set(["String","Memo","EntityName"]),cne=new Set(["Integer","BigInt","Money","Decimal","Double"]),qk=new Set(["DateTime"]),dne=new Set(["Boolean"]),fne=new Set(["Lookup","Owner","Customer"])});function Hk(e){switch(e){case"Boolean":return Me.WorkflowAttributeType.Boolean;case"Customer":return Me.WorkflowAttributeType.Customer;case"DateTime":return Me.WorkflowAttributeType.DateTime;case"Decimal":return Me.WorkflowAttributeType.Decimal;case"Double":return Me.WorkflowAttributeType.Float;case"Integer":return Me.WorkflowAttributeType.Integer;case"Lookup":return Me.WorkflowAttributeType.Lookup;case"Money":return Me.WorkflowAttributeType.Money;case"Owner":return Me.WorkflowAttributeType.Owner;case"Picklist":return Me.WorkflowAttributeType.Picklist;case"State":return Me.WorkflowAttributeType.State;case"Status":return Me.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Me.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Me.WorkflowAttributeType.BigType;default:return Me.WorkflowAttributeType.String}}function e$(e){return e&&e!==Me.WorkflowAttributeType.String?e:void 0}function hne(e){return{__class:Zk,parameterName:"primaryEntity",entityName:e}}function Wk(e){return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Kk,parameters:[e]}}function zk(e,t,r=Me.WorkflowAttributeType.String){return{__class:Yk,type:r,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,entity:hne(t),attributeName:e}}function gne(e,t=Me.WorkflowAttributeType.String){return{__class:Qk,type:t,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function yne(e){return{__class:Xk,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function t$(e,t){let r=pne[e.operator],n=Wk(zk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=yne(e.right.value??"0"):e.right.kind==="field"?i=zk(e.right.field??"",t,e.right.workflowType):i=gne(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=Wk(i);return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Jk,parameters:[r,n,o]}}function r$(e){return typeof e=="object"&&e.__class===nv}function bne(e){return typeof e=="object"&&e.__class===Xk}function Fp(e){return r$(e)&&e.method===Kk&&e.parameters.length>0?Fp(e.parameters[0]):e}function jk(e){if(typeof e!="object"||e.__class!==Yk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Zk)return null;let r=e.attributeName;return r?{field:r,workflowType:e$(e.type)}:null}function n$(e){if(!e)return null;let t=Fp(e);if(!r$(t)||t.method!==Jk||t.parameters.length!==3)return null;let r=t.parameters[0],n=mne[String(r)];if(!n)return null;let i=jk(Fp(t.parameters[1]));if(!i)return null;let o=Fp(t.parameters[2]);if(bne(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=jk(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===Qk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:e$(o.type)}}}return null}function ov(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=iv&&r<=hl}function Pa(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!ov(t)?"invalidDayCount":null}function gl(e){return Pa(e)===null}var Me,Kk,Jk,rv,Yk,Qk,nv,Xk,Zk,pne,mne,iv,hl,gc=k(()=>{"use strict";Me=Ce(Rp());xp();Kk="0",Jk="3",rv="0",Yk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",Qk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",nv="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Xk="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Zk="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";pne={"+":0,"-":1,"*":2,"/":3},mne={0:"+",1:"-",2:"*",3:"/"};iv=0,hl=2147483647});function wne(e){return e.startsWith("__")&&!vne.has(e)}function Cne(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{wne(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function y$(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function La(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Mp(e){return y$(e)||La(e)}function Ene(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function yc(){return{list:[]}}function av(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:br(),languageCode:r,description:t}]}}function lv(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function Vp(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:lv(t),attributeName:e}}function Ra(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Nne(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?w$:v$:b$}function C$(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function _ne(e,t){let r=C$(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${o$}_${i$}`,entityName:i$,relatedAttributeName:o$},attributeName:Sne}:Vp(Ane,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:dv,parameters:[Nne(e),n]}}function E$(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==dv)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===v$?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===w$?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===b$?{bpfField:"ProcessName"}:null}function Up(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===dv){let r=(t.parameters??[])[0];if(typeof r=="string"&&Tne.has(r.replace(/^"+|"+$/g,"")))return!0}return La(e)?Up(e.operand):y$(e)?Up(e.left)||(e.right??[]).some(Up):!1}function A$(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Dne(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function a$(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return A$(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Ine(e){let t=cv[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(La(e))return r&&s$(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:s$(e.left,r,n[0])}function s$(e,t,r){return E$(e)||A$(e)?t||a$(r):!1}function uv(e){if(!e||!Mp(e))return!1;let t=e.conditionOperatoroperator;if(!La(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&uv(e.left)&&r.every(uv)}return Ine(e)}function l$(e){return!e||Dne(e)?!1:Up(e)||!uv(e)}function S$(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??z.WorkflowAttributeType.Lookup,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ra(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Pne(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Rne(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Pne(t)}function Lne(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function $ne(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function Gne(e){let t=Vne.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=qne.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Bne.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function Wne(e){let t=Gne(e.trim());return t!==void 0&&N$(t)?t:e}function N$(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!xne.test(i)||o.length>0&&!Fne.test(o)&&!Mne.test(o)&&!Une.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function zne(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||kne.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=$ne(e);return n==null?r:{value:n,type:t}}return One.includes(t)?Pp(e)?{value:e.trim(),type:t}:r:Lp(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&N$(e)?{value:e.trim(),type:t}:r}function u$(e){return e==="ContainsData"||e==="DoesNotContainData"}function c$(e){return jne.has(e)}function d$(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function f$(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=hc[e.operator]??z.WorkflowConditionOperator.Equal,i=Rne(e,r),o=Zb(r,n);if(e.source==="BusinessProcess"){let l=_ne(e,t);if(u$(e.operator))return d$(l,n);let u=C$(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ra(e.value??"",u)]}}let a=Vp(e.field,t,r,i);if(u$(e.operator))return d$(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=c$(o)&&c$(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[Vp(e.valueField,t,l,Lne(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[S$(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ra(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[qp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=zne(e.value??"",o);s=[Ra(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function Hne(){return Ra(!0,z.WorkflowAttributeType.Boolean)}function Kne(e,t,r){if(e.length===0)return null;let n=f$(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[f$(e[i],r)]}}return n}function Bp(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:Wne(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=n$(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Jne(e){let t=cv[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=La(e)?e.operand:e.left,i=La(e)?[]:e.right??[],o=E$(n);if(o){let g=i[0];return{id:br(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:Bp(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:br(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function p$(e){if(!e||!Mp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(La(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...Jne(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Mp(o.left)&&r(o.left,a),(o.right??[]).filter(Mp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function qp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return Vp(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return t$(i,n);if(o!=null)return o}return e==="Lookup"&&a?S$(a):e==="Clear"?Ra(null,s??z.WorkflowAttributeType.String):Ra(t??"",z.WorkflowAttributeType.String)}function sv(e,t){return{propertyName:e,propertyValueExpr:t}}function yl(e){return`Step_${e.value++}`}function Cn(e,t){let r=(t.counts[e]??0)+1,n=`${e}${r}`;for(;t.used.has(n);)r+=1,n=`${e}${r}`;return t.counts[e]=r,t.used.add(n),n}function m$(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Cn(t,r)}function Yne(e){return e===g$.StateCode.Activated?"Active":"Draft"}function Qne(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function Xne(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function _$(e,t=1033){return new bl({languageCode:t}).serialize(e)}function T$(e){return new bl().deserialize(e)}var g$,z,vne,cv,dv,b$,v$,w$,Ane,Sne,i$,o$,Tne,One,kne,xne,Fne,Mne,Une,Bne,qne,Vne,jne,fv,bl,pv=k(()=>{"use strict";Yb();g$=Ce(lo());Rk();Qb();ev();gc();z=Ce(Rp());vne=new Set(["__class"]);cv={};for(let e of Object.keys(hc))cv[hc[e]]=e;dv="23",b$="BpfProcess",v$="ActiveStageCategory",w$="SelectedStageCategory",Ane="processid",Sne="stagecategory",i$="processstage",o$="stageid";Tne=new Set(["ActiveStage","SelectedStage","Stage"]);One=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];kne=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];xne=/^\d{4}-\d{2}-\d{2}$/,Fne=/^\d{2}:\d{2}$/,Mne=/^\d{2}:\d{2}:\d{2}$/,Une=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Bne=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],qne=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Vne=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;jne=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);fv={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};bl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>fv[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??br(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:yc(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??yl(this.stepCounter),stepLabels:{list:[]},specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:lv(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=av(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:m$(n?.id,"ActionStep",this.idCounter),name:n?.name??yl(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??br(),uniqueName:n?.uniqueName??`id_${br().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=lv(this.entityName),n=t.stepName??yl(this.stepCounter),i=t.stepLabels??yc(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:Cn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:Cn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:Cn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:Cn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:Cn("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=av(t.stepLabels,s,this.languageCode);return{...o,id:Cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,name:s,controlId:t.field,entity:r,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,l=av(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:Cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??yl(this.stepCounter),n=Cn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Kne(o.clauses,o.logic,this.entityName),l=a?o.branchName??yl(this.stepCounter):yl(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?m$(o.branchId,"ConditionBranchStep",this.idCounter):Cn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:yc(),conditionExpression:s??(a?Hne():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:yc(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:yc(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??br():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:Cne(o)};let s=(o.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:Xne(r,i?.formId),status:Yne(t.statecode),rootCondition:n,wfomRoot:i,...Qne(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Ene);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=p$(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??br(),displayName:c,clauses:a,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...l$(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=p$(n.conditionExpression);return i.length===0&&!l$(n.conditionExpression)?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},o=n.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||br(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Bp(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bp(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetFieldValue",displayName:t.description||t.name||this.label("setFieldValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bp(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==z.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var D$=k(()=>{"use strict";});function nie(e){return typeof e=="object"&&e!==null?e:null}function vl(e){let t=nie(e);if(!t)return!1;if(t.__class===tie){let r=t;return String(r.method)===rie?!0:Array.isArray(r.parameters)&&r.parameters.some(vl)}if(t.__class===eie)return vl(t.operand);if(t.__class===Zne){let r=t;return vl(r.left)||Array.isArray(r.right)&&r.right.some(vl)}return!1}var Zne,eie,tie,rie,I$=k(()=>{"use strict";D$();Zne="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",eie="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",tie="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",rie="23"});function yv(e){return iie.has(e.type)}function mv(e,t,r,n,i,o,a){let s=i.get(r);!s||!R$.has(s.attributeType)||n!=="Value"||a?.operator&&!tv(a.operator)||o.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function oie(e,t){let r=t.get(e.field);return!!r&&R$.has(r.attributeType)&&tv(e.operator)}function hv(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function gv(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${hl}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:hl}}}function O$(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Dp(r,l)||a.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function Wp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(yv(t))return!0}else if(Wp(t))return!0;return!1}function bv(e,t){if(e.id===t)return e;for(let r of[...e.trueBranch,...e.falseBranch]){if(r.id===t)return r;if(r.kind==="condition"){let n=bv(r,t);if(n)return n}}return null}function aie(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function sie(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||aie(e.rawConditionExpression))}function uie(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||vl(e.rawConditionExpression)}function wl(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=wl(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=wl(n,t);if(i)return i}}return null}function vv(e,t){return{...e,trueBranch:P$(e.trueBranch,t),falseBranch:P$(e.falseBranch,t)}}function P$(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?vv(r,t):r)}function Bo(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n)}}function Gp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n)}}function L$(e,t,r,n){return Bo(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function wv(e){return e.length===1&&e[0].kind==="condition"}function die(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(wv(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function fie(e){return!!e&&die(e)<cie}function pie(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(wv(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function k$(e,t,r){let n=pie(e,t);return!n||!fie(n)?e:Bo(e,t,i=>$$(i,r))}function $$(e,t){if(wv(e.falseBranch))return{...e,falseBranch:[$$(e.falseBranch[0],t)]};let r=Cv(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function x$(e,t){let r=wl(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return Bo(e,r.node.id,o=>({...o,falseBranch:i}))}function F$(e,t,r){let n=wl(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return Bo(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Cv(e){return{kind:"condition",id:br(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function M$(e,t){let r={kind:"action",id:br(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:br(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...r,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...r,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...r,type:"SetVisibility",field:"",visible:!0};default:return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function U$(e){if(!e)return[];let t=[];return B$(e,t),[...new Set(t)]}function B$(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?B$(r,t):"field"in r&&r.field&&t.push(r.field)})}function q$(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return G$(e,n,i,!0),r==="Entity"&&V$(e,n),Wp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function V$(e,t){uie(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&V$(r,t)})}function G$(e,t,r,n=!1){let i=n&&sie(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?Pa(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&!a.value&&!oie(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else qn(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!gl(a.expression)?t.push(s==="invalidDayCount"?gv(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):qn(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});qn(a.operator)&&a.valueType==="Value"&&a.value&&Lk(r.get(a.field)?.attributeType)&&!Pp(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=xk(a);qn(a.operator)&&a.valueType==="Value"&&a.value&&Lp(l)&&!Fk(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:Xb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:Xb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),qn(a.operator)&&a.valueType==="Lookup"&&(hv(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),qn(a.operator)&&mv(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&lie.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")G$(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!$p(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:Pa(a.expression);!a.rawExpression&&!gl(a.expression)&&t.push(s==="invalidDayCount"?gv(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!hv(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(mv(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),O$(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:Pa(l.expression);!l.rawExpression&&!gl(l.expression)&&t.push(u==="invalidDayCount"?gv(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?hv(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(mv(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),O$(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var iie,R$,lie,cie,Ev=k(()=>{"use strict";Yb();zb();xp();gc();I$();ev();Qb();iie=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);R$=new Set(["Lookup","Customer","Owner"]);lie=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);cie=10});var W$={};nn(W$,{DAY_COUNT_MAX:()=>hl,DAY_COUNT_MIN:()=>iv,DEFAULT_DESERIALIZE_LABELS:()=>fv,WorkflowJsonMapper:()=>bl,addElseIfInTree:()=>k$,appendToBranch:()=>L$,areFieldKindsCompatible:()=>$p,attributeTypeToWorkflowType:()=>Hk,buildWorkflowEntity:()=>Ak,collectUsedFields:()=>U$,createEmptyAction:()=>M$,createEmptyCondition:()=>Cv,deserializeWorkflowJson:()=>T$,findNode:()=>bv,findParent:()=>wl,getDefaultOperatorForFieldType:()=>Vk,getExpressionModelIssue:()=>Pa,getOperatorsForFieldType:()=>kp,hasAnyTriggerGeneratingAction:()=>Wp,isDayCountValid:()=>ov,isExpressionModelComplete:()=>gl,isOperatorCompatible:()=>Gk,isTriggerGeneratingAction:()=>yv,moveBranchItemInTree:()=>F$,operatorNeedsValue:()=>qn,processTriggerFormIdFromScope:()=>Hb,processTriggerScopeFromScope:()=>jb,removeElseIfInTree:()=>x$,removeNodeFromTree:()=>vv,serializeToWorkflowJson:()=>_$,supportsClearForActionType:()=>Dp,updateActionInTree:()=>Gp,updateConditionInTree:()=>Bo,validateBusinessRule:()=>q$});var z$=k(()=>{"use strict";zb();Sk();pv();pv();Ev();Ev();xp();gc();gc();});var Av=v(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});zp.cloneJson=void 0;function mie(e){return JSON.parse(JSON.stringify(e))}zp.cloneJson=mie});var nx=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.BUSINESS_RULE_NULL_GUID=qo.businessRuleRegistration=qo.BusinessRuleAdapter=void 0;var j$=ct(),bc=(z$(),zr(W$)),H$=jr(),K$=Q(),hie=Av(),hi=cn(),gie=dh(),yie=ct(),bie=sa(),vie=new Set(["ShowErrorMessage","Recommendation"]);function X$(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?X$(n):vie.has(String(n.type))):!1}function wie(e){return Z$((0,hie.cloneJson)(e))}function Z$(e){var t,r;let n=i=>(i??[]).map(o=>Cie(o)?Z$(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function Cie(e){return Object.prototype.hasOwnProperty.call(e,"type")?!1:Object.prototype.hasOwnProperty.call(e,"clauses")||Object.prototype.hasOwnProperty.call(e,"trueBranch")||Object.prototype.hasOwnProperty.call(e,"falseBranch")||Object.prototype.hasOwnProperty.call(e,"logic")}function Eie(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new K$.ValidationError("businessRule","(new)","/rootCondition",`rootCondition must be a condition object or null, got ${Array.isArray(e)?"array":typeof e}`);if(Object.prototype.hasOwnProperty.call(e,"type"))throw new K$.ValidationError("businessRule",(t=e.id)!==null&&t!==void 0?t:"(new)","/rootCondition","rootCondition looks like an ACTION (it carries 'type'), but it must be a condition. Wrap the action in a condition's trueBranch instead \u2014 a bare action would compile to an empty rule that saves successfully and does nothing.");return e}var Aie="00000000-0000-0000-0000-000000000000";qo.BUSINESS_RULE_NULL_GUID=Aie;var Sie=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Nie=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],_ie=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Tie=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Vn(e,t){return e===void 0?t:{...e,...t}}var ka=["kind","id","type","displayName","field","stepName","stepLabels"],J$=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Die={Recommendation:[...ka,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...ka,"lock"],ShowErrorMessage:[...ka,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...ka,...J$],SetDefaultValue:[...ka,...J$],SetBusinessRequired:[...ka,"required"],SetVisibility:[...ka,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function ex(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Sv(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",ex(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function tx(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Iie=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function Oie(e){return Vn(e.bag,{id:e.id,field:e.field,...Sv(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Pie(e){let t=tx(e,Iie);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function Y$(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function Q$(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Rie=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Lie=new Set,kie="INVALID_CLEAR_FOR_FIELD";function $ie(e){let t=n=>{var i;return(0,hi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,hi.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var jp=class{toArtifact(t){let r=this.residualBag(t,Nie),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Vn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,bc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return X$(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,bc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:bie.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,j$.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,bc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(wie(Eie(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,j$.newId)()),u}assignMissingIds(t){return(0,yie.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,hi.isJsonObject)(n)?(rx(n,"/rootCondition",r),r):(r.push((0,hi.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(a){return[(0,hi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:$ie(n.rootCondition),o;return r.length===0?o=Rie:r.some(a=>a.requiredLevel!==void 0)?o=Lie:o=new Set([kie]),(0,bc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,hi.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return tx(t,r)}buildWorkflowEntity(t,r){return(0,bc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,_ie),n={id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseToJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemToJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemToJson(i))};return r&&(n.bag=r),n}clauseToJson(t){let r=this.residualBag(t,Tie),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,Die[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Pie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...Y$(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...Y$(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return Q$(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Vn(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Vn(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",ex(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!Sie.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Fie(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Vn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Oie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Vn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Vn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Vn(t.bag,{...r,type:"SetFieldValue",...Sv(t)});case"SetDefaultValue":return Vn(t.bag,{...r,type:"SetDefaultValue",...Sv(t)});case"SetBusinessRequired":return Vn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Vn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return Q$(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};qo.BusinessRuleAdapter=jp;function rx(e,t,r){(0,hi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,hi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,hi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?rx(o,`${t}/${n}/${a}`,r):xie(o,`${t}/${n}/${a}`,r)})}function xie(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,hi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Fie(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Mie(){return{adapter:new jp,api:gie.businessRuleApi,publish:(e,t,r)=>(0,H$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,H$.boundEntityPublishScope)(t)}}qo.businessRuleRegistration=Mie});var Cx=v(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.appRegistration=Vo.AppAdapter=Vo.HEADER_NAV_BOOLEAN_RULE=void 0;var Zi=cn(),$t=wo(),wc=Eo(),Uie=jr(),px=Af(),Nv=tf(),_v=Co(),Bie=ct(),qie=oe(),mx=sa(),hx=Q(),gx=nf();Object.defineProperty(Vo,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return gx.HEADER_NAV_BOOLEAN_RULE}});var Yp="7.0.0.0",ix=`<SiteMap IntroducedVersion="${Yp}"></SiteMap>`,ox="/_imgs/imagestrips/transparent_spacer.gif",ax="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",yx=["Entity","Url","DefaultDashboard","Page","GenPageId"],vc="sitemapId",sx="sitemapName",Vie="sitemapNameUnique",lx="aiDescription",ux="[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",Gie=new RegExp(`^(?:\\{${ux}\\}|${ux})$`);function cx(e,t){if(!Gie.test(e.trim()))throw new hx.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function dx(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new hx.ValidationError("app",t,[bx(e)]);return e}function bx(e){return(0,Zi.issue)("/headerAndNavigationRefresh",gx.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function Wie(e){let t=n=>{let i=e[n];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},r=n=>{let i=t(n);if(i!==void 0)try{return(0,qie.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}function zie(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var Qp=class{constructor(t=mx.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Hp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,$t.emptyBag)()}}fromArtifact(t){(0,_v.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,$t.rebuildRaw)(i,(0,wc.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,_v.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,wc.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:ix,ix),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[vc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[sx,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Vie,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[lx,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,_v.installDomShim)();let w=(0,wc.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?C.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let O=(s=t.bag)!==null&&s!==void 0?s:(0,$t.emptyBag)();return{sitemapId:Dv(O,vc)||(t.sitemapId?cx(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Dv(O,sx)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Dv(O,lx))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Nv.HEADER_AND_NAVIGATION_REFRESH]:dx(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Nv.APP_SETTING_ON:Nv.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Bie.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:cx(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:dx(t.headerAndNavigationRefresh,(s=t.id)!==null&&s!==void 0?s:"(new)",!0),...typeof t.published=="boolean"?{published:t.published}:{},...t.components?{components:t.components}:{}}}assignMissingIds(t){let r=t;if(!r||typeof r!="object")return t;let n=r.siteMap;return n&&Array.isArray(n.areas)?n.areas.forEach(Ov):Array.isArray(r.areas)?r.areas.forEach(Ov):Array.isArray(r.groups)?Ov(r):Array.isArray(r.subAreas)?wx(r):"type"in r&&Xp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Zi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(bx(o)),i==null)return r;if(!(0,Zi.isJsonObject)(i))return r.push((0,Zi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Zi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Zi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Zi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Zi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=Wie(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,Zi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,px.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,zie(t))}applyServerIdentity(t,r){let n=r[vc];if(!n)return;t.bag||(t.bag=(0,$t.emptyBag)());let i=t.bag.a.find(o=>o[0]===vc);i?i[1]=n:t.bag.a.push([vc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Hp(t,null),i=jie(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Tv(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==ox&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,$t.emptyBag)(),l=Kp(a)?[["IntroducedVersion",Yp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,$t.mergeAttrs)(a.a,l),c:(0,$t.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Yp]),t.icon!==void 0?a.push(["Icon",t.icon]):Jp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Iv((0,$t.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,$t.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Yp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Iv((0,$t.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,$t.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),i=Kp(n),o=Kie(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>yx.includes(c));Yie(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):Jp(o,"Icon",ox)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",ax]):s.push("VectorIcon"):t.type==="GenPage"&&!Hie(o,"VectorIcon")&&a.push(["VectorIcon",ax]);let u=Iv((0,$t.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,$t.mergeAttrs)(o,a,s),c:u}}};Vo.AppAdapter=Qp;function Hp(e,t){let r=(0,wc.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,$t.rawFromNode)((0,wc.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function fx(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function Tv(e,t){var r;let n=fx(e,"Titles")[0];if(!n)return"";let o=fx(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function jie(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Kp(e){return e.a.length===0&&e.c.length===0}function Hie(e,t){return e.some(([r])=>r===t)}function Jp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Dv(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Kie(e,t){let r=Jie(t);return e.filter(([n])=>!yx.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function Jie(e){switch(e){case"Entity":return new Set(["Entity"]);case"URL":return new Set(["Url"]);case"DashBoard":return new Set(["DefaultDashboard","Url"]);case"CustomPage":return new Set(["Page"]);case"GenPage":return new Set(["GenPageId"]);default:return new Set}}function Yie(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(a=t.page)!==null&&a!==void 0?a:""]);break;case"GenPage":e.push(["GenPageId",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Iv(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=Qie(e[i],t,n),o}return r?[Xie(t,n),...e]:e}function Qie(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Zie(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,$t.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(vx(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Xie(e,t){return{n:"Titles",a:[],c:[vx(e,t)]}}function vx(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Zie(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function eoe(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Xp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${eoe(8)}`)}function Ov(e){var t;Xp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])wx(r)}function wx(e){var t;Xp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Xp(r,"subarea")}function toe(e=mx.DEFAULT_LCID){return{adapter:new Qp(e),api:px.appApi,languageSensitive:!0,publish:(t,r)=>(0,Uie.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Vo.appRegistration=toe});var Ex={};nn(Ex,{ActionType:()=>Rv,AppActionOrigin:()=>Bv,AppActionVisibilityType:()=>Uv,ButtonType:()=>kv,CannotUpdateAppActionColumns:()=>roe,Context:()=>xv,IconType:()=>Lv,Location:()=>$v,OnClickEventType:()=>Mv,Scope:()=>Fv,VisibilityType:()=>Pv});var Pv,Rv,Lv,kv,$v,xv,Fv,Mv,Uv,Bv,roe,Ax=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Pv||(Pv={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Rv||(Rv={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Lv||(Lv={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(kv||(kv={}));(function(e){e[e.Form=0]="Form",e[e.HomePageGrid=1]="HomePageGrid",e[e.SubGridStandard=2]="SubGridStandard",e[e.SubGridAssociated=3]="SubGridAssociated",e[e.QuickForm=4]="QuickForm",e[e.Global=5]="Global",e[e.Dashboard=6]="Dashboard"})($v||($v={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(xv||(xv={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Fv||(Fv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Mv||(Mv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Uv||(Uv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Bv||(Bv={}));roe=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Ox=v(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.assertOneWritePerRow=xt.commandApi=xt.COMMAND_DUPLICATE_ROW_CODE=xt.COMMAND_ROW_NOT_IN_BAR_CODE=xt.COMMAND_TABLE_MISMATCH_CODE=void 0;var qv=Tt(),Ur=fe(),eo=Q(),Br=oe();xt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";xt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";xt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var noe="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Vv(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Br.odataPathLiteral)(t)}')${(0,Br.odataQuery)([["$select","MetadataId"]])}`,i=(0,Ur.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Br.normalizeGuid)(o,"entityMetadataId"):""}function Gv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Br.odataLiteral)(e)}'`}function Cc(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function Sx(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function Nx(e,t,r){let n=await Vv(e,t);if(r){let i=(0,Br.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Cc(t))}return n}xt.commandApi={async get(e,t){let r=t,n=await Vv(e,r),i=Gv(r,n),o=`/appactions${(0,Br.odataQuery)([["$expand",noe],["$filter",i]])}`,a,s=await(0,qv.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Br.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Ur.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=Sx(n,r),o=await Nx(e,i,n.entityMetadataId);return _x(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=Sx(o,t),s=await Nx(e,a,o.entityMetadataId);return _x(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Vv(e,t),n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Ur.deleteRecord)(e,"appactions",o.appactionid)}};async function _x(e,t,r,n,i){let o=r.entityMetadataId?(0,Br.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await ooe(e,t,r,o,n,i),s={};try{await soe(e,a,o,s)}catch(l){throw(0,eo.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Wv(e){return e.replace(/[{}]/g,"").toLowerCase()}function Ix(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=Wv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new eo.SdkError(xt.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}xt.assertOneWritePerRow=Ix;var ioe={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Tx(e,t){let r=ioe[t].exec(e);return r?Wv(r[1]):void 0}async function ooe(e,t,r,n,i,o){var a,s;Ix(t,r);let l=loe(r.rows),u=new Set(l.map(f=>Wv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Tx(m,"entities")===n))throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Cc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Tx(p,"appactions");if(h===void 0||!u.has(h))throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+Cc(t))}if(i&&f.exists){let h=(0,Br.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Ur.isVersionToken)(g))throw Dx(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new eo.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,Br.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Ur.isVersionToken)(p))throw Dx(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await aoe(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Cc(t))}return c}function Dx(e,t,r,n){return new eo.SdkError(Ur.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Cc(e))}async function aoe(e,t,r){let n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Br.normalizeGuid)(a.appactionid,"appactionid"));return o}async function soe(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Ur.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Ur.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Ur.readEtag)(s)}else{let o=(0,Ur.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Ur.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Ur.readCreatedId)(l,"appactionid");u&&(n[(0,Br.normalizeGuid)(u,"appactionid")]=(0,Ur.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Ur.deleteRecord)(e,"appactions",i,o),delete n[i]}function loe(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var jx=v(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.commandRegistration=Cl.CommandAdapter=void 0;var mt=(Ax(),zr(Ex)),Px=jr(),St=cn(),kx=Ox(),$x=ct(),El=oe(),xx=Q(),Hv="$ClientSvg:",Kv=".svg",uoe=2,coe=1,doe=1,Fx="entityMetadataId",foe=new Set(["@odata.etag","IconWebResourceId","OnClickEventJavaScriptWebResourceId","VisibilityFormulaComponentLibraryId","OnClickEventFormulaComponentLibraryId","ContextEntity","_appmoduleid_value","_contextentity_value","_createdby_value","_createdonbehalfby_value","_iconwebresourceid_value","_modifiedby_value","_modifiedonbehalfby_value","_onclickeventformulacomponentlibraryid_value","_onclickeventjavascriptwebresourceid_value","_organizationid_value","_parentappactionid_value","_visibilityformulacomponentlibraryid_value","createdon","modifiedon","overriddencreatedon","overwritetime","componentstate","componentidunique","solutionid","ismanaged","iscustomizable","versionnumber","importsequencenumber","timezoneruleversionnumber","utcconversiontimezonecode","statecode","statuscode","scope"]),Zp=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new xx.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=yoe(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:moe(g,f,qx(h),c)});return{id:c,entityLogicalName:c,commandBars:goe(p),bag:{a:[[Fx,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),appActions:zv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?zv(r).map(l=>l.appactionid):[]),i=zv(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?Ooe(l.row):zx(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,kx.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,$x.assignMissingIds)(t)}normalize(t){let r=Coe(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,St.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,St.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>Gx(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,St.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,St.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,St.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;rm(l.bag)||((0,St.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),Mx((0,St.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Cl.CommandAdapter=Zp;function rm(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function Mx(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;rm(n.bag)||(0,St.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,St.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,St.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,St.isJsonObject)(n.action)?(0,St.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,St.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,St.childObjects)(n,"children",o,"control",r);s.length>0&&Mx(s,`${o}/children`,r)})}function Jv(e){return{a:Object.entries(e)}}function poe(e){return Object.fromEntries(e.a)}function Ec(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Yv(e){let t=Ec(e.bag,Fx);return typeof t=="string"?t:""}function moe(e,t,r,n){var i,o;let a=[],s=[];for(let l of tm(e))l.type===mt.ButtonType.Group?a.push({id:Bx(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:tm((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>em(u,t,r,n)),bag:Jv(l)}):s.push(em(l,t,r,n));return s.length>0&&a.unshift({id:Ioe(n,r),title:"",controls:s}),a}function Qv(e){let t=e.bag?Ec(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function em(e,t,r,n){var i,o,a,s,l;let u=Bx(e.name,n),c={id:u,type:boe(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Jv(e)},d=Ux(e);d&&(c.icon=d);let f=hoe(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of tm(m))if(g.type===mt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Jv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let S of tm((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=em(S,t,r,n);p.push(O),C.push(Qv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(em(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function Ux(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Hv)?e.fonticon.slice(Hv.length)+Kv:e.fonticon}function hoe(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Rx(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function tm(e){return[...e].sort((t,r)=>Rx(t)-Rx(r))}function goe(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function Bx(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let r=e.split("!");return r.length===2?r[1]:e}function yoe(e){switch(e){case mt.Location.Form:case mt.Location.QuickForm:return"MainTab";case mt.Location.HomePageGrid:case mt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function qx(e){switch(e){case"MainTab":return mt.Location.Form;case"HomeTab":return mt.Location.HomePageGrid;default:return mt.Location.SubGridStandard}}function boe(e){switch(e){case mt.ButtonType.Dropdown:return"FlyoutAnchor";case mt.ButtonType.Split:return"SplitButton";default:return"Button"}}function voe(e){switch(e){case"FlyoutAnchor":return mt.ButtonType.Dropdown;case"SplitButton":return mt.ButtonType.Split;default:return mt.ButtonType.Standard}}function woe(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function Vx(e,t){var r,n,i;return((n=(r=e.bag)===null||r===void 0?void 0:r.a.length)!==null&&n!==void 0?n:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function zv(e,t=new Set){var r,n,i,o;let a=[],s=Yv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=qx(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!Vx(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(woe(m)){let h=Aoe(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])Wx(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function Gx(e,t){if(!(0,St.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>Gx(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!rm(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,$x.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Coe(e){let t=new Set,r=(o,...a)=>{if((0,St.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),rm(o.bag)?Ec(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,St.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,St.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,St.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function Wx(e,t,r,n,i,o,a,s=new Set){var l;let u=Eoe(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!Vx(h,s)),f=(h,g,b)=>{Wx(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[Qv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let L=O.id||(S===0?jv(u.appactionid):Zv("flyout-group",`${u.appactionid}#${S}`)),I=Lx(L,t,u.appactionid,n,i,O.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let P of O.childIds){let x=h.get(P);!x||g.has(P)||(g.add(P),f(x,D,b),b+=1)}}let C=w??jv(u.appactionid);for(let S of c){let O=Qv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||jv(u.appactionid);o.push(Lx(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Eoe(e,t,r,n,i,o){let a=Xv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=Ux(s);return e.location!==void 0&&(s.location=e.location),s.type=voe(e.type),s.buttonlabeltext=e.label,Noe(s,e.icon,l),Toe(s,e.action),_oe(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function Aoe(e,t,r,n,i){let o=Xv(e,t,r,n,i);return o.row.type=mt.ButtonType.Group,o.row.grouptitle=e.title,o}function Lx(e,t,r,n,i,o){let a=Xv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command flyout group id")})`,s.type=mt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Xv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=poe(e.bag),a=!0;let u=Ec(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Ec(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new xx.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=Soe(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==mt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Soe(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:mt.Context.Entity,contextvalue:r.entityLogicalName,scope:mt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,El.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Noe(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,El.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Kv)?Hv+t.slice(0,t.length-Kv.length):t,e.IconWebResourceId=null}function _oe(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,El.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===coe&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===doe)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Toe(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=uoe,t.webResourceId){let r=(0,El.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function Doe(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function Zv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Doe(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function jv(e){return Zv("flyout-group",e)}function Ioe(e,t){return Zv("loose-group",`${e}|${t}`)}function zx(e){let t={...e};for(let r of foe)delete t[r];return t}function Ooe(e){let t=zx(e);for(let r of mt.CannotUpdateAppActionColumns)delete t[r];return t}function Poe(){return{adapter:new Zp,api:kx.commandApi,publish:(e,t,r)=>(0,Px.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Px.boundEntityPublishScope)(t)}}Cl.commandRegistration=Poe});var Kx=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.chartApi=void 0;var Roe=Tt(),qr=fe(),$a=oe(),Hx="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Loe="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";nm.chartApi={async get(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]);return{raw:(0,qr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]),i=(0,qr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,$a.odataQuery)([["$select",Loe],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,$a.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Roe.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,qr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,qr.ensureSuccess)(await e.post(o,(0,qr.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,qr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,qr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,$a.normalizeGuid)(t,"id"),a=(0,qr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,qr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,qr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,qr.readEtag)(l)}},delete(e,t){return(0,qr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var dF=v(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.chartRegistration=Sl.ChartAdapter=void 0;var ew=wo(),Jx=cn(),gi=Eo(),Yx=jr(),koe=Kx(),tw=Co(),$oe=ct(),xoe=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Foe=new Map(xoe.map(e=>[e.toLowerCase(),e]));function tF(e){var t;return e&&(t=Foe.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Moe(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Uoe(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${Al(h.series.attribute)}" aggregate="${Al(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${Al(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${Al(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${Al(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${Al(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var im=class{toArtifact(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,gi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,gi.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:om(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:iF(d),categories:oF(d),presentation:rF(f),dataBag:u?(0,gi.projectElementBag)(d):void 0,presentationBag:c?(0,gi.projectElementBag)(f):void 0,rowBag:Boe(t.charttype,t.type)}}fromArtifact(t){(0,tw.installDomShim)();let{datadescription:r,presentationdescription:n}=qoe(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:Qx(t.rowBag,"charttype"),type:Qx(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,$oe.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,Jx.childObjects)(n,"series","","series",r),(0,Jx.childObjects)(n,"categories","","category",r),r}};Sl.ChartAdapter=im;function Boe(e,t){let r=[];return e!==void 0&&r.push(["charttype",String(e)]),t!==void 0&&r.push(["type",String(t)]),r.length>0?{a:r,c:[]}:void 0}function Qx(e,t){if(!e)return;let r=e.a.find(([i])=>i===t);if(!r)return;let n=parseInt(r[1],10);return Number.isNaN(n)?void 0:n}function om(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return tF(t[r].getAttribute("ChartType"));return"Column"}function rF(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function am(e){return e.getElementsByTagName("fetch")[0]}function nF(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function iF(e){let t=am(e);if(!t)return[];let r=nF(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=tF(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function oF(e){var t;let r=am(e);if(!r)return[];let n=nF(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function qoe(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!Xx(e.dataBag)||!Xx(e.presentationBag)){let c=Uoe({...e,series:n,categories:i});return{datadescription:c,presentationdescription:aae(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=Zx(e.dataBag,"datadefinition",o),s=Zx(e.presentationBag,"Chart",o),l=e.chartType||om(s),u=iF(a);if(!rw(n,u)){let c=nw(a);Voe(o,a,n);let d=nw(a),f=d.length>0?d:n.map(()=>"");aF(o,s,f,c,l)}return rw(i,oF(a))||Goe(o,a,i),e.chartType&&e.chartType!==om(s)&&uF(s,e.chartType),e.presentation&&!rw(e.presentation,rF(s))&&cF(s,e.presentation),{datadescription:(0,gi.serializeNode)(a),presentationdescription:(0,gi.serializeNode)(s)}}function Xx(e){return!!e&&(e.c.length>0||e.a.length>0)}function aF(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function nw(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function Zx(e,t,r){let n={n:t,a:(0,ew.mergeAttrs)(e.a,[]),c:(0,ew.spliceChildren)(e.c,[])};return(0,ew.rebuildRaw)(n,(0,gi.domEngine)(r),null)}function Voe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Yoe(n),r,Xoe,{aliasPrefix:"aggregate_column",addRef:joe,removeRef:Joe})}function Goe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Qoe(n),r,Zoe,{aliasPrefix:"groupby_column",addRef:Hoe,removeRef:Koe})}function sF(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=eae(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),eF(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||zoe(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),eF(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),rae(m)}}function Woe(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function zoe(e,t){let r=Woe(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function lF(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function joe(e,t,r){let n=lF(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function Hoe(e,t,r){let n=lF(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function Koe(e,t){let r=e.getElementsByTagName("category");for(let n=0;n<r.length;n+=1)r[n].getAttribute("alias")===t&&r[n].removeAttribute("alias")}function Joe(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!iae(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function Yoe(e){let t=[],r=e.getElementsByTagName("attribute");for(let n=0;n<r.length;n+=1)r[n].getAttribute("aggregate")&&t.push(r[n]);return t}function Qoe(e){var t;let r=[],n=e.getElementsByTagName("attribute");for(let i=0;i<n.length;i+=1)((t=n[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&r.push(n[i]);return r}function Xoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Zoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function eae(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function eF(e,t,r,n){n?tae(e,t,n).appendChild(r):t.appendChild(r)}function tae(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function rae(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!nae(t))){let r=t.parentNode;r&&r.removeChild(t)}}function nae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1){let i=n.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function iae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function uF(e,t){let r=e.getElementsByTagName("Series"),n=!1;for(let i=0;i<r.length;i+=1)r[i].getAttribute("ChartType")&&(r[i].setAttribute("ChartType",t),n=!0);if(!n){for(let i=0;i<r.length;i+=1)if(!oae(r[i])){r[i].setAttribute("ChartType",t);return}}}function oae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName==="Series")return!0}return!1}function cF(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function aae(e,t){let r=(0,gi.parseXmlRoot)(Moe(),"<Chart/>"),n=e.chartType||om(r);uF(r,n),e.presentation&&cF(r,e.presentation);let i=nw((0,gi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&aF(r.ownerDocument,r,i,i.slice(0,1),n),(0,gi.serializeNode)(r)}function rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Al(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function sae(){return{adapter:new im,api:koe.chartApi,publish:(e,t,r)=>(0,Yx.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Yx.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Sl.chartRegistration=sae});var hF=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.dashboardApi=xa.dashboardEntity=void 0;var lae=Tt(),Go=fe(),Nl=oe(),uae=Jg(),fF=vu();function pF(e){return e&&e.toLowerCase()!=="none"?e:void 0}xa.dashboardEntity=pF;var mF="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",cae={select:mF,required:["name","type","objecttypecode","istabletenabled"]},dae="formid,name,type,objecttypecode",fae=0,pae=10;xa.dashboardApi={async get(e,t){let r=(0,Nl.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Nl.odataQuery)([["$select",mF]]),i=(0,Go.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,fF.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Go.readEtag)(i)}},async list(e,t){let r=[`(type eq ${fae} or type eq ${pae})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Nl.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Nl.odataQuery)([["$select",dae],["$filter",r.join(" and ")]])}`;return(await(0,lae.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=pF(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Go.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Go.ensureSuccess)(await e.post(o,(0,Go.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Go.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Go.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,uae.patchSystemForm)(e,(0,Nl.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,cae)},readContentThenToken(e,t){return xa.dashboardApi.get(e,t)},async delete(e,t){let r=(0,Nl.normalizeGuid)(t,"id");return await(0,fF.assertSystemFormKind)(e,r,"dashboard"),(0,Go.deleteRecord)(e,"systemforms",r)}}});var DF=v(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.dashboardRegistration=yi.TILE_CLASS_ID=yi.DashboardAdapter=void 0;var Sc=wo(),En=Eo(),iw=jr(),Ac=cn(),CF=hF(),ow=Co(),Fa=ct(),EF=oe(),AF=sa(),mae=yb(),gF="0",aw="10",hae=new Map([["{E7A81278-8635-4D9E-8D4D-59480B391C5B}","chart"],["{FD2A7985-3187-444E-908D-6624B21F69C0}","iframe"],["{9FDF5F91-88B1-47F4-AD53-C11EFC01A01D}","webresource"],["{EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8}","stream"],["{06375649-C143-495E-A496-C962E5B4488E}","timeline"],["{8C54228C-1B25-4909-A12A-F2B968BB0D62}","powerbi"],["{F9A8A302-114E-466A-B582-6771B2AE0D92}","assistant"]]),gae="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",lm=class{constructor(t=AF.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,ow.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,En.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:yae(t.type),entityLogicalName:(a=(0,CF.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:bae(l),components:yF(l,this.lcid),bag:(0,En.projectElementBag)(l)}}fromArtifact(t){var r;return(0,ow.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:bF(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,mae.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:bF(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,ow.installDomShim)();let c=(0,En.parseXmlRoot)(Pae(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Fa.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:yF(c,this.lcid),bag:(0,En.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let r=t;(typeof r.id!="string"||r.id.length===0)&&(r.id=(0,Fa.newId)())}return t}validate(t){let r=[],n=(0,Ac.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,Ac.isJsonObject)(u)&&r.push((0,Ac.issue)(`${s}/${l}`,`component-${l}-must-be-object`,`a component ${l} must be a JSON object when present, got ${u===null?"null":typeof u}`))}if((0,Ac.isJsonObject)(o.position)){let l=Nc(o.position);i.has(l)?r.push((0,Ac.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};yi.DashboardAdapter=lm;function yae(e){return String(e??"")===aw?"Interactive":"Standard"}function bae(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function se(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function yF(e,t){let r=[];return se(e,"tabs").flatMap(i=>se(i,"tab")).forEach((i,o)=>{se(i,"columns").flatMap(s=>se(s,"column")).forEach((s,l)=>{se(s,"sections").flatMap(c=>se(c,"section")).forEach((c,d)=>{vae(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function vae(e,t,r,n){se(e,"rows").flatMap(o=>se(o,"row")).forEach((o,a)=>{se(o,"cell").forEach((s,l)=>{let u=wae(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function wae(e,t,r){var n,i;let o=_F((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=se(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=Aae(a),u=Sae(s,l,a),c=Cae(a);return{id:a.getAttribute("id")||o,type:u,name:NF(e,r),classId:s,position:t,colspan:um(e,"colspan",1),rowspan:um(e,"rowspan",1),parameters:l,bag:(0,En.projectElementBag)(e),...c?{icProperties:c}:{}}}function SF(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName.toLowerCase()==="icproperties")return n}}function Cae(e){let t=SF(e);return t?(0,En.serializeNode)(t):void 0}function Eae(e,t,r){let n=SF(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,Sc.rebuildRaw)((0,Sc.rawFromNode)((0,En.nodeLikeFromDom)(i)),(0,En.domEngine)(e),null);n&&(0,En.serializeNode)(n)===(0,En.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function NF(e,t){var r,n;let i=se(e,"labels")[0];if(!i)return"";let o=se(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function Aae(e){var t;let r={},n=se(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function Sae(e,t,r){var n;let i=hae.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===gae?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function um(e,t,r){var n;let i=parseInt((n=e.getAttribute(t))!==null&&n!==void 0?n:"",10);return Number.isNaN(i)?r:i}function _F(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function Nae(e,t){let r={n:"form",a:(0,Sc.mergeAttrs)(e.bag.a,[]),c:(0,Sc.spliceChildren)(e.bag.c,[])};return(0,Sc.rebuildRaw)(r,(0,En.domEngine)(t),null)}function bF(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Nae(e,r);return Dae(r,n,e.components,t),_ae(r,n,e.components,t),(0,En.serializeNode)(n)}function _ae(e,t,r,n){let i=TF(t);for(let o of r)i.has(Nc(o.position))||Tae(e,t,o,n)}function Tae(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Rae(t,e,l);for(let x of se(u,"row"))se(x,"cell").some(K=>se(K,"control").length>0)||u.removeChild(x);let c=r.classId||yi.TILE_CLASS_ID[r.type]||yi.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&vF(r.bag,"id")?String(vF(r.bag,"id")):sm((0,Fa.newId)()),m=r.id?sm(r.id):sm((0,Fa.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=se(u,"row"),w=b[b.length-1],C=w?se(w,"cell").reduce((x,K)=>x+um(K,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let O=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),O.appendChild(L),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",sm(c));let D=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(P)){let K=(0,EF.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function vF(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Dae(e,t,r,n){var i;let o=TF(t),a=new Set(r.map(s=>Nc(s.position)));for(let s of r){let l=o.get(Nc(s.position));if(!l)continue;let u=se(l,"control")[0];u&&(Iae(e,l,s.name,n),Oae(e,u,s.parameters),wF(l,"colspan",s.colspan),wF(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Eae(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function TF(e){let t=new Map;return se(e,"tabs").flatMap(n=>se(n,"tab")).forEach((n,i)=>{se(n,"columns").flatMap(a=>se(a,"column")).forEach((a,s)=>{se(a,"sections").flatMap(u=>se(u,"section")).forEach((u,c)=>{se(u,"rows").flatMap(f=>se(f,"row")).forEach((f,m)=>{se(f,"cell").forEach((p,h)=>{var g;_F((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||se(p,"control")[0]&&t.set(Nc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function Nc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Iae(e,t,r,n){if(r===NF(t,n))return;let i=se(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=se(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function Oae(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=se(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,EF.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function wF(e,t,r){um(e,t,1)!==r&&e.setAttribute(t,String(r))}function Pae(e=2){let t=`{${(0,Fa.newId)()}}`,r=`{${(0,Fa.newId)()}}`,n=`{${(0,Fa.newId)()}}`,i=Math.max(1,Math.floor(e));return`<form><tabs><tab id="${t}" name="General" showlabel="true" expanded="true" verticallayout="true"><columns><column width="100%"><sections><section id="${r}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${n}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}yi.TILE_CLASS_ID={chart:"E7A81278-8635-4D9E-8D4D-59480B391C5B",list:"E7A81278-8635-4D9E-8D4D-59480B391C5B",iframe:"FD2A7985-3187-444E-908D-6624B21F69C0",webresource:"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"};function sm(e){return`{${e.replace(/[{}]/g,"")}}`}function Rae(e,t,r){var n;let i=se(e,"tabs").flatMap(u=>se(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=se(i,"columns").flatMap(u=>se(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=se(o,"sections").flatMap(u=>se(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=se(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Lae(e=AF.DEFAULT_LCID){return{adapter:new lm(e),api:CF.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,iw.publishBoundEntity)(t,n):(0,iw.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,iw.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}yi.dashboardRegistration=Lae});var lw=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.readEveryInOrder=Vr.readInOrder=Vr.plainRead=Vr.resolveReadConcurrency=Vr.MAX_READ_CONCURRENCY=void 0;var IF=Q();Vr.MAX_READ_CONCURRENCY=8;function kae(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Vr.MAX_READ_CONCURRENCY)throw new IF.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Vr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Vr.resolveReadConcurrency=kae;var $ae=e=>({ok:!0,value:e}),sw=e=>({ok:!1,error:e});function xae(e){let t=(async()=>e())().then($ae,sw);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Vr.plainRead=xae;async function OF(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new IF.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(sw);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:sw(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function Fae(e,t,r,n){return OF(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Vr.readInOrder=Fae;function Mae(e,t,r,n){return OF(e,t,r,n,"continue")}Vr.readEveryInOrder=Mae});var HF=v(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});dm.genPageApi=void 0;var cm=Tt(),VF=Es(),Ve=fe(),be=oe(),Gn=pa(),Qe=Q(),GF=ct(),PF=lw();function Uae(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var bi="uxagentprojects",Ua="uxagentprojectfiles",Dc="agentconversationmessages",Ic="uxagentprojectid",jt="uxagentprojectfileid",Ba="agentconversationmessageid",_c=`${Ic},name`,Bae=`${jt},filename,filetype`,WF=2e8,zF=200000001,qa={"MSCRM.IncludeUnpublished":"true"},uw={};function Ma(e,t){return{"MSCRM.VersioningChangeset":e,...qa,...t}}async function fw(e,t,r,n){var i;let o=`/${t}(${r})`+(0,be.odataQuery)([["$select",n]]),a=(0,Ve.ensureSuccess)(await e.get(o,{headers:{...qa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Ve.readEtag)(a)}}async function Oc(e,t,r=qa){let n=`/${Ua}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ve.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Uae(o);if(a)return{status:"available",data:(0,Gn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,Gn.utf8ToBase64)(o)};throw new Qe.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function jF(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function qae(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let a=`/${Ua}(${t})/filecontent`,s=(0,Gn.base64ToBytes)(n);(0,be.assertNoControlChars)(r,"generative-page file name"),(0,Ve.ensureSuccess)(await e.patchRaw(a,s,{headers:Ma(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":jF(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function Tc(e,t,r=qa){let n=`/${Ua}`+(0,be.odataQuery)([["$select",Bae],["$filter",`_${Ic}_value eq ${t}`]]);return(await(0,cm.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function cw(e,t){let r=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,cm.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...qa}})}async function RF(e,t){var r,n,i;let{row:o,etag:a}=await fw(e,bi,t,_c),s=new Map;for(let{row:l,etag:u}of await Tc(e,t))s.set((0,be.normalizeGuid)(String((r=l[jt])!==null&&r!==void 0?r:""),jt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function LF(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,be.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Qe.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Qe.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function pw(e){let t=(0,Gn.base64ToUtf8)(e);return(0,Gn.utf8ToBase64)(t)===(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(e))?t:void 0}function Vae(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Ba]:(0,be.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${bi}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?WF:zF}}async function Gae(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,be.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ba} eq ${f}`).join(" or ")]]),u=await(0,cm.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...qa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ba])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,be.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?WF:zF)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Qe.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function dw(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${bi}`,body:(0,Ve.withClientMintedId)({name:t.name},Ic,e),headers:Ma(n)};case"createRow":return{method:"POST",path:`/${Ua}`,body:(0,Ve.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${Ic}@odata.bind`]:`/${bi}(${e})`},jt,(0,be.normalizeGuid)(t.file.id,"file id")),headers:Ma(n)};case"renameRow":return{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ma(n,{"If-Match":"*"})};case"content":{let i=pw(t.data);if(i===void 0)throw new Qe.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,be.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ma(n,{"x-ms-file-name":jF(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Ua}(${t.fileId})`,headers:Ma(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${bi}(${e})`,body:{name:t.name},headers:Ma(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${Dc}`,body:Vae(e,t.turn,r,n)};default:{let i=t;throw new Qe.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function kF(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||pw(r.data)!==void 0)}async function $F(e,t,r,n,i){await(0,VF.postChangeSet)(e,r.map(o=>dw(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function xF(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await qae(e,(0,be.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=dw(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Ve.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>dw(t,l,n,i));if(e.supportsAtomicBatch)await(0,VF.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Ve.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function FF(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await RF(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,be.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,S]of c){let O=u.rows.get(C);O&&(O.filename!==S.name||O.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${O.filename}' (type ${O.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await Oc(e,(0,be.normalizeGuid)(C.file.id,"file id")),O=(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,Gn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,Gn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,be.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await Oc(e,C)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await RF(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(C=>{var S,O;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((O=m.rows.get(C))===null||O===void 0?void 0:O.etag)}),g=p.length!==i.size||p.some(C=>!i.has(C)),b={},w=[];for(let[C,S]of m.rows){let O=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;b[C]=O,O!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):Wae({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function MF(e,t,r,n=e.readConcurrency){var i;let o=(0,be.normalizeGuid)(t,"id"),{row:a,etag:s}=await fw(e,bi,o,_c),l=await Tc(e,o),u={},c=[];if(n>1)await(0,PF.readInOrder)(l,n,({row:f})=>{var m;let p=(0,be.normalizeGuid)(String((m=f[jt])!==null&&m!==void 0?m:""),jt);return(0,PF.plainRead)(async()=>({fileId:p,content:await Oc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,be.normalizeGuid)(String((i=f[jt])!==null&&i!==void 0?i:""),jt);u[p]=m;let h=await Oc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await cw(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}dm.genPageApi={get(e,t,r){return MF(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return MF(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,be.normalizeGuid)(t,"id"),o=`/${bi}(${i})`+(0,be.odataQuery)([["$select",_c]]),a=await e.get(o);if(a.status===404)return null;(0,Ve.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await Tc(e,i,uw);for(let{row:g,etag:b}of c){let w=(0,be.normalizeGuid)(String((n=g[jt])!==null&&n!==void 0?n:""),jt);l[w]=b,u.push({...g,content:await Oc(e,w,uw)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[jt])}@${String(w)}`).sort().join("|"),f=()=>new Qe.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Ve.ensureSuccess)(m,e.apiUrl(o));let p=await Tc(e,i,uw);if([(0,Ve.readEtag)(a),(0,Ve.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Qe.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Ve.readEtag)(m)!==(0,Ve.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Ve.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${bi}`+(0,be.odataQuery)([["$select",_c]]);return(await(0,cm.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...qa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[Ic])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,be.normalizeGuid)(r,"id"):(0,GF.newId)(),a=LF(o,i,void 0);qF(e,a),BF(e,o,i);let s=UF(),l=[],u=!0;kF(e,a)?await $F(e,o,a,i,s):{warnings:l,turnRecorded:u}=await xF(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,be.normalizeGuid)(f.id,"file id"))),d=await FF(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,be.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Qe.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await Gae(e,l,s);BF(e,l,u);let c=await Tc(e,l),{row:d,etag:f}=await fw(e,bi,l,_c);if(n&&f&&n!==f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,P;return[(0,be.normalizeGuid)(String((D=I[jt])!==null&&D!==void 0?D:""),jt),{filename:String((P=I.filename)!==null&&P!==void 0?P:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,be.normalizeGuid)(I.id,"file id")));if(!i)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}));for(let[I,D]of Object.entries(i)){let P=I.toLowerCase();if(!p.has(P))continue;let x=b.get(P);if(!D||!x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${D?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(D!==x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let w=LF(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(qF(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}))};let C=UF(),S=[],O=!0;kF(e,w)?await $F(e,l,w,u,C):{warnings:S,turnRecorded:O}=await xF(e,l,w,u,C);let L=await FF(e,l,w,u,h,b,S);return O?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,be.normalizeGuid)(t,"id"),i=await cw(e,n);await(0,Ve.deleteRecord)(e,bi,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ba])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await cw(e,n)){let u=String((r=l[Ba])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Ve.deleteRecord)(e,Dc,l)}catch(u){u instanceof Qe.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Qe.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${Dc} rows regarding '${n}'.`)}};function UF(){return`uxagentproject_${(0,GF.newId)()}`}function Wae(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function BF(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function qF(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>pw(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var cM=v(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.genPageRegistration=Tl.GenPageAdapter=void 0;var zae=HF(),jae=jr(),Ie=cn(),gm=ct(),ym=pa(),Hae=oe(),Va=Q(),iM=v0(),mw=Oh(),Wo=2e8,oM=200000001,ro={source:{name:"src/pages/page.tsx",fileType:Wo},output:{name:"src/pages/page.compiled",fileType:oM},config:{name:"config.json",fileType:Wo},prompt:{name:"firstPrompt.json",fileType:Wo}},aM=Object.keys(ro),Kae=["dataSources","model","connectorBindings","actionBindings"],Jae=["userMessage","agentMessage"],KF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Yae={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},Qae="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function sM(e,t,r){let n=(0,Hae.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function fm(e,t){return sM(e,Yae[t],"id")}function Xae(e,t){let r=sM(e,Qae,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function JF(e){return typeof e=="string"&&e.trim()!==""?e:(0,gm.newId)()}function to(e){return(0,Ie.isJsonObject)(e)?e:{}}function _l(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function pm(e){return JSON.parse(JSON.stringify(e))}function Zae(e){let t=to(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function Rc(e){if(!e||e.status!=="available")return;let t=(0,ym.base64ToUtf8)(e.data);return(0,ym.utf8ToBase64)(t)===e.data?t:void 0}function lM(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&_l((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,iM.isLoadableGenPageOutput)(r)}function ese(e,t){var r;try{return lM(e,t,Rc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function mm(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function YF(e,t){if(t===Wo&&e.includes("page.tsx"))return"source";if(t===oM&&e.includes(".compiled"))return"output";if(t===Wo&&e===ro.config.name)return"config";if(t===Wo&&e===ro.prompt.name)return"prompt"}function QF(e){let t=e.toLowerCase();return aM.some(r=>ro[r].name.toLowerCase()===t)}function hw(e){return Object.fromEntries(e)}function uM(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),hw(i)}function XF(e){var t,r,n;return uM({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Kae,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function ZF(e){var t,r;return uM({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Jae,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function eM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=hw(n)),!0}function tM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=hw(n)),!0}function Lc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var tse=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function rM(e){return Lc(e)?[]:tse.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function nM(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function hm(e){return{status:"available",data:(0,ym.utf8ToBase64)(e)}}function Pc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var bm=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=to(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=to(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:Wo),content:Zae(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=to(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((w=C.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=YF(g.name,g.fileType);b?((s.has(b)||g.name!==ro[b].name)&&(u=!1),s.set(b,g)):(QF(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(Pc(n,i));let c=Pc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=Rc(f.content);if(g===void 0)return a(Pc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=mm(Rc(p.content));if(!g||!eM(c,d,g))return a(Pc(n,i))}let h=s.get("prompt");if(h){let g=mm(Rc(h.content));if(!g||!tM(c,d,g))return a(Pc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!_l((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=rM(t);if(b.length>0)throw new Va.ValidationError("genPage",t.id,b);let w=[],C=r===void 0,S=C&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(Lc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Ge=>{var Ut;return(Ut=I[Ge])!==null&&Ut!==void 0?Ut:fm(S.id,Ge)},P=(Ge,Ut,de)=>{w.push({id:D(Ge),name:ro[Ge].name,fileType:ro[Ge].fileType,content:Ut,unchanged:de})};if(S.source!==void 0){P("source",hm(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Ge=Rc((l=S.bag)===null||l===void 0?void 0:l.output);lM(S,r,Ge)?P("output",{status:"retain"},!0):P("output",hm(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Va.ValidationError("genPage",S.id,[nM()]);if(I.output!==void 0){if(!C&&!_l((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Va.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);P("output",{status:"retain"},!0)}}let x=XF(S),K=!C&&r!==void 0&&_l(XF(r),x);(C||I.config!==void 0||!K)&&P("config",hm(JSON.stringify(x)),K&&I.config!==void 0);let Le=ZF(S),lr=!C&&r!==void 0&&_l(ZF(r),Le);(I.prompt!==void 0||Object.keys(Le).length>0&&!lr)&&P("prompt",hm(JSON.stringify(Le)),lr&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(P=>P.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&_l(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Xae(I,P)}:{};O.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&O.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...O.length>0?{messages:O,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:pm(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!Lc(t)&&!t.newTurn)return t;let u=pm(t);if(delete u.newTurn,!Lc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=aM.find(p=>ro[p].name===d.name&&ro[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,ym.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,eM(u,c,(s=mm(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,tM(u,c,(l=mm(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&KF.test(r.id)?t:{...t,newTurn:{...r,id:(0,gm.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Va.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,mw.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,mw.buildGenPageLegacyEnums)(a):void 0,d=(0,iM.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Va.ValidationError("genPage",t.id,d.diagnostics.map(rse));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=ese(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=JF(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:JF(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Wo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=pm(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=pm(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:fm(i,"source"),output:fm(i,"output"),config:fm(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,gm.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,gm.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&to(to(n.bag).rows).source!==void 0&&r.push(nM()),r.push(...rM(t)),n.newTurn!==void 0){let s=to(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!KF.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!mw.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=Lc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=to(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(QF(f)||YF(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=to(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Tl.GenPageAdapter=bm;function rse(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function nse(){return{adapter:new bm,api:zae.genPageApi,publish:(e,t)=>(0,jae.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Tl.genPageRegistration=nse});var fM=v(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});wm.reconcileBpfSecurityRoles=void 0;var dM=Tt(),yw=Q(),vm=fe(),kc=oe(),ise="Global",gw={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function ose(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,dM.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(gw).forEach(u=>{let c=a.find(d=>d.PrivilegeType===gw[u]);if(c){let d=(0,kc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function ase(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,dM.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,kc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function sse(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:ise,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function lse(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function use(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await ose(e,t.toLowerCase());for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new yw.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=gw[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await ase(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await sse(e,l,f);for(let p of m)await lse(e,l,p)}}wm.reconcileBpfSecurityRoles=use});var NM=v(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.bpfApi=void 0;var vr=lo(),pM=Es(),cse=Tt(),Xe=Q(),ht=fe(),An=oe(),dse=fM(),fse=lh(),$c=ch(),pse={"Content-Type":"application/json",Accept:"application/json"},vw={...pse,Prefer:"return=representation"},mse=`category eq ${vr.WorkflowCategory.BusinessProcessFlow} and type eq ${vr.WorkflowTypeCode.Definition} and businessprocesstype eq ${vr.BusinessProcessType.BusinessFlow}`,hse="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",gse="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",yse=["xaml","name","description","processorder"];async function bw(e,t){var r;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let n=String((r=t.record.uniquename)!==null&&r!==void 0?r:"");n!==""&&await(0,dse.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Cw(e,t,r){let n={statecode:vr.StateCode.Activated,statuscode:vr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await SM(e,i,n,r,null);try{return(0,ht.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?EM(s):s}}var CM=new WeakSet;function EM(e){return typeof e=="object"&&e!==null&&CM.add(e),e}function AM(e){return typeof e=="object"&&e!==null&&CM.has(e)}function mM(e){return e instanceof Xe.ConnectionError&&(e.statusCode===0||ht.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function SM(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ht.resendWhile)(ht.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...vw};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ht.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?EM(s):s}}async function hM(e,t,r){return(0,ht.readEtag)(await Cw(e,t,r))}function gM(e,t){return new Xe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Cm(e))}async function xc(e,t){var r;let n=`/workflows(${t})${(0,An.odataQuery)([["$select","statecode"]])}`,i=(0,ht.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Xe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function ww(e,t,r,n,i=null){if((n??await xc(e,t))!==vr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:vr.StateCode.Draft,statuscode:vr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await SM(e,a,o,r,i))}catch(c){return await yM(e,t,c,AM(c))}if(ht.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await yM(e,t,new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ht.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ht.readEtag)(u)}}async function yM(e,t,r,n){let i;try{i=await xc(e,t)}catch{i=void 0}if(i===vr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===vr.StateCode.Activated)throw r;let o=new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===vr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Xe.attachCause)(o,r),o}async function bse(e,t){let r=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,r,null),"restored"}catch{return Ew(e,r)}}async function vse(e,t,r){let n=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,n,r),"restored"}catch(i){return i instanceof Xe.SdkError&&i.code===ht.VERSION_CONFLICT_CODE?"changed":Ew(e,n)}}async function Ew(e,t){try{let r=await xc(e,t);return r===vr.StateCode.Activated?"restored":r===vr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function bM(e,t,r,n){return r?{outcome:await vse(e,t,r),attempted:!0}:n?{outcome:await Ew(e,(0,An.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await bse(e,t),attempted:!0}}function wse(e,t){let r=new Xe.SdkError($c.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,$c.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function vM(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Xe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Xe.attachCause)(s,n),s}async function Cse(e,t){try{return await xc(e,t),"survived"}catch(r){return r instanceof Xe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Ese(e,t,r){if(r)try{let{deactivated:n,etag:i}=await ww(e,t,r),o=n?i:r;if(o)return await(0,$c.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Cse(e,t)}function Cm(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function wM(e,t){return new Xe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Cm(e)}`)}function Ase(e,t){let r=new Xe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Sse(e,t){let r=new Xe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Nse(e,t){let r=new Xe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Aw(e){let t={};for(let r of yse)e[r]!==void 0&&(t[r]=e[r]);return t}var _se=["name,processorder","description,name,processorder"];function Tse(e){let{xaml:t,...r}=Aw(e);return typeof t=="string"&&_se.includes(Object.keys(r).sort().join(","))}async function Dse(e,t,r,n){let{xaml:i,...o}=Aw(r),[,a]=await(0,pM.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,An.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ht.readEtag)((0,pM.partResponse)(a))}Em.bpfApi={async get(e,t){let n=`/workflows(${(0,An.normalizeGuid)(t,"id")})${(0,An.odataQuery)([["$select",gse]])}`,i=(0,ht.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ht.readEtag)(i)}},async list(e,t){let r=[mse];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,An.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,An.odataQuery)([["$select",hse],["$filter",r.join(" and ")]])}`;return(await(0,cse.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,An.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ht.ensureSuccess)(await e.post(i,r.record,{headers:vw}),e.apiUrl(i)),a=(0,ht.readEtag)(o);if(!a)throw wM(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await hM(e,n,a)),await bw(e,r)}catch(l){let u=await Ese(e,n,s);throw u==="survived"?Ase(n,l):u==="unknown"?Sse(n,l):l instanceof Xe.SdkError&&l.code===ht.VERSION_CONFLICT_CODE?Nse(n,l):l}if(!s)throw wM(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,An.normalizeGuid)(t,"id"),a=(0,ht.requireEtag)(n,"bpf",o),s=await xc(e,o);if(s===vr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Tse(i.record)){let m=await Dse(e,o,i.record,a);return await bw(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await ww(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw gM(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ht.ensureSuccess)(await e.patch(p,Aw(i.record),{headers:{...vw,"If-Match":m}}),e.apiUrl(p))}catch(b){throw mM(b)&&(d=null),b}let g=(0,ht.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw gM(o,"definition write");try{g=await hM(e,o,g)}catch(b){throw mM(b)&&(d=null),b}f=!0}return await bw(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await bM(e,o,d,AM(m));if(p!=="restored")throw vM(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,An.normalizeGuid)(t,"id"),n=await(0,fse.assertWorkflowKind)(e,r,vr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await ww(e,r,null,void 0,n);try{await(0,$c.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,$c.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await bM(e,r,o,!1);if(s==="changed")throw wse(r,a);if(s!=="restored")throw vM(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var lU=v(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});Il.bpfRegistration=Il.BpfAdapter=void 0;var Am=lo(),Ise=NM(),Sw=wo(),Ga=Eo(),MM=Co(),tn=cn(),Gr=ct(),Wn=Q(),Ose=100,Nw='<?xml version="1.0" encoding="utf-16"?>',_M=1033,UM="mxswa:Workflow",Pse="mxswa:ActivityReference.Properties",Rse="mcwo:StepLabel",Lse="mcwb:Control",TM="mcwb:Control.ControlDisplayName",BM="mcwb:Control.DataFieldName",qM="DataFieldName",DM="ControlDisplayName",VM="Literal",Nm="x:Null",IM="x:String",_w="x:Key",Tw="DisplayName",Tm="Activities",kse="StepLabels",GM="StageId",WM="StageCategory",zM="NextStageId",jM="ProcessStepId",Sm="IsProcessRequired",HM="EntityComposite",KM="StageComposite",JM="StepComposite";function Fc(e){return(0,tn.isJsonObject)(e)?e:{}}function wi(e){if(!e)return[];let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];i.nodeType===1&&t.push(i)}return t}function Wa(e,t){var r;return(r=wi(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Ei(e){return Wa(e,Pse)}function wr(e,t){var r;return(r=wi(e).find(n=>n.getAttribute(_w)===t))!==null&&r!==void 0?r:null}function Dl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function YM(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Mc(e){var t;let r=(t=e.getAttribute(Tw))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function QM(e,t){var r;let n=(r=e.getAttribute(Tw))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Tw,i>=0?n.slice(0,i+2)+t:t)}function XM(e,t){let r=wr(e,kse),n=Wa(r,Rse);n&&n.setAttribute("Description",t)}function $se(e){let t=wr(e,WM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:Number(r)}function xse(e){let t=wr(e,zM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:r}function ZM(e){let t=eU(e);if(!t)return;let r=rU(t,qM,BM);return r===""?void 0:r}function Dw(e,t){let r=wi(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of wi(n))r.push(i)}return null}function eU(e){let t=wr(Ei(e),Tm);return t?Dw(t,Lse):null}function tU(e,t){let r=e.attributes;for(let n=0;n<r.length;n+=1)if(r[n].name===t)return!0;return!1}function rU(e,t,r){var n;return tU(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":qse(e,r)}function OM(e,t,r,n){if(tU(e,t)){e.setAttribute(t,n);return}if(Wa(e,r)){Fse(e,r,n);return}throw new Wn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Fse(e,t,r){let n=Wa(e,t),i=n?Dw(n,VM):null;if(!i)throw new Wn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function nU(e){return Mc(e)}function Dm(e){let t=Wa(e,UM),r=[];for(let n of wi(t).filter(i=>Dl(i,HM))){let i=wr(Ei(n),Tm);for(let o of wi(i).filter(a=>Dl(a,KM)))r.push({el:o,entity:nU(n)})}return r}function Iw(e){let t=wr(Ei(e),Tm);return wi(t).filter(r=>Dl(r,JM))}function Mse(e){let t=Ei(e),r=Ci(wr(t,Sm)).trim().toLowerCase(),n=ZM(e),i={id:Ci(wr(t,jM)),name:Mc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Use(e,t){let r=Ei(e),n=$se(r),i=xse(r),o={id:Ci(wr(r,GM)),name:Mc(e),entityLogicalName:t,steps:Iw(e).map(Mse)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Bse(e){return Dm(e).map(({el:t,entity:r})=>Use(t,r))}function vi(e){return new Wn.NotImplementedError("bpf-structural-authoring",`${e} is not supported yet (this phase authors identity, stage/step names, step required, step field binding, stage categories, and adding/removing/reordering stages & steps on a single-table process; branching, actions, security-role wiring and multi-table processes land in later phases). The rest of the process round-trips losslessly.`)}function qse(e,t){var r;let n=Wa(e,t),i=n?Dw(n,VM):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Ow(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Ow(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function iU(e){return wr(Ei(e),Tm)}function Vse(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Gr.newId)(),{body:a}=Im(Pw(i,(0,Gr.newId)(),t.id,o));return Ow(e,Dm((0,Ga.parseXmlRoot)(a,"<Activity/>"))[0].el)}function Gse(e,t){let{body:r}=Im(Pw("account",(0,Gr.newId)(),(0,Gr.newId)(),t.id));return Ow(e,Iw(Dm((0,Ga.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function oU(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function aU(e,t,r,n){let i=wr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw vi(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Nm&&Ci(i).trim()!==""){let s=t.createElement(Nm);s.setAttribute(_w,r),o.replaceChild(s,i)}return}if(i.tagName===IM){Ci(i).trim()!==n&&YM(i,t,n);return}let a=t.createElement(IM);a.setAttribute(_w,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function Wse(e,t,r){aU(e,t,WM,r===void 0?void 0:String(r))}function zse(e,t,r){aU(e,t,zM,r)}function sU(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(r(e[n])!==t[n])return!1;return!0}function PM(e){return Ci(wr(Ei(e),GM))}function RM(e){return Ci(wr(Ei(e),jM))}function LM(e,t,r){var n,i,o,a;let s=Ei(e);r.name!==Mc(e)&&(QM(e,r.name),XM(s,r.name));let l=Ci(wr(s,Sm)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=wr(s,Sm);if(!u)throw vi(`setting '${Sm}' on a step whose xaml does not expose that slot`);YM(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=ZM(e))!==null&&o!==void 0?o:"")){let u=eU(e);if(!u)throw new Wn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";OM(u,qM,BM,c),c!==""&&rU(u,DM,TM)===""&&OM(u,DM,TM,c)}}function kM(e,t,r,n){var i;let o=Ei(e);if(!o)throw new Wn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Mc(e)&&(QM(e,r.name),XM(o,r.name)),Wse(o,t,r.category),zse(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw vi("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw vi("stage actions or conditional branching");let a=iU(e);if(!a)throw new Wn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Wn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Iw(e);if(sU(l,s.map(d=>d.id),RM)){l.forEach((d,f)=>LM(d,t,s[f]));return}let u=new Map(l.map(d=>[RM(d),d]));if(wi(a).some(d=>!Dl(d,JM)))throw vi("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:Gse(t,d)});oU(a,c),c.forEach((d,f)=>LM(d,t,s[f]))}function jse(e,t,r){let n=Wa(e,UM);if(!n)throw new Wn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw vi("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Wn.InvalidArgumentError("a BPF must have at least one stage");let i=Dm(e),o=i.map(f=>f.el);if(sU(o,r.stages.map(f=>f.id),PM)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw vi(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);kM(f,t,h,h.nextStageId)});return}let a=wi(n).filter(f=>Dl(f,HM));if(a.length!==1)throw vi("adding, removing or reordering stages on a multi-table process");let s=a[0],l=nU(s),u=iU(s);if(!u)throw new Wn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(wi(u).some(f=>!Dl(f,KM)))throw vi("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw vi(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[PM(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Vse(t,f,l)});oU(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;kM(f,t,r.stages[m],p)})}function Im(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function Hse(e){var t,r,n,i,o,a;(0,MM.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,Sw.mergeAttrs)(s.a,[]),c:(0,Sw.spliceChildren)(s.c,[])};return{root:(0,Sw.rebuildRaw)(m,(0,Ga.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Nw,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Pw(e.entityLogicalName,(0,Gr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Gr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Gr.newId)()),{body:d}=Im(c);return{root:(0,Ga.parseXmlRoot)(d,"<Activity/>"),prolog:Nw,eol:"lf"}}function Kse(e){let{root:t,prolog:r,eol:n}=Hse(e);jse(t,t.ownerDocument,e);let i=(0,Ga.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function Jse(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var _m=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,MM.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=Im(o),u=(0,Ga.parseXmlRoot)(l,"<Activity/>");a.stages=Bse(u),a.bag={xaml:(0,Ga.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:t.name,uniquename:Jse(t),primaryentity:t.entityLogicalName,xaml:Kse(t),category:Am.WorkflowCategory.BusinessProcessFlow,type:Am.WorkflowTypeCode.Definition,businessprocesstype:Am.BusinessProcessType.BusinessFlow,scope:Am.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Ose};t.description!==void 0&&(n.description=t.description);let i={record:n,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new Wn.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let o=t.stages&&t.stages.length>0?t.stages.map(xM):[xM({id:(0,Gr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Fc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Gr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,tn.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof n}`)),r;let i=Array.isArray(n)?n:[];i.length>30&&r.push((0,tn.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Fc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,tn.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,tn.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,tn.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,tn.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Fc(h).id=="string"?h.id.trim():"";w===""?r.push((0,tn.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,tn.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!$M(i,d.branch.nextStageId)&&r.push((0,tn.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!$M(i,d.nextStageId)&&r.push((0,tn.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,tn.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=Yse(i);return s>=0&&r.push((0,tn.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Il.BpfAdapter=_m;function Yse(e){let t=new Map(e.map(r=>[Fc(r).id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function $M(e,t){return e.some(r=>Fc(r).id===t)}function xM(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(FM):[FM({id:(0,Gr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(r=e.entityLogicalName)!==null&&r!==void 0?r:"",steps:n};return e.category!==void 0&&(i.category=e.category),e.nextStageId!==void 0&&(i.nextStageId=e.nextStageId),e.relationshipName!==void 0&&(i.relationshipName=e.relationshipName),e.actions!==void 0&&(i.actions=e.actions),e.branch!==void 0&&(i.branch=e.branch),i}function FM(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(r.fieldName=e.fieldName),e.required!==void 0&&(r.required=e.required),r}function Pw(e,t,r,n){return`${Nw}<Activity x:Class="XrmWorkflow00000000000000000000000000000000" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mcwb="clr-namespace:Microsoft.Crm.Workflow.BusinessProcessFlowActivities;assembly=Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mcwo="clr-namespace:Microsoft.Crm.Workflow.ObjectModel;assembly=Microsoft.Crm, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxs="clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxswa="clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:srs="clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:this="clr-namespace:" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><x:Members><x:Property Name="InputEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /><x:Property Name="CreatedEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /></x:Members><this:XrmWorkflow00000000000000000000000000000000.InputEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.InputEntities><this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings><mxswa:Workflow><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.EntityComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="EntityStep1: ${e}"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StageComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StageStep2: New Stage"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StepComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StepStep3: New Step"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><Sequence DisplayName="ControlStep4"><mcwb:Control ControlId="${t}" IsSystemControl="False" IsUnbound="False" SystemStepType="0"><mcwb:Control.ClassId><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ClassId><mcwb:Control.ControlDisplayName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ControlDisplayName><mcwb:Control.DataFieldName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.DataFieldName><mcwb:Control.Parameters><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.Parameters></mcwb:Control></Sequence></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Step" LabelId="${n}" LanguageCode="${_M}" /></sco:Collection><x:String x:Key="ProcessStepId">${n}</x:String><x:Boolean x:Key="IsProcessRequired">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Stage" LabelId="${r}" LanguageCode="${_M}" /></sco:Collection><x:String x:Key="StageId">${r}</x:String><x:Null x:Key="StageCategory" /><x:Null x:Key="NextStageId" /></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><x:Null x:Key="RelationshipName" /><x:Null x:Key="AttributeName" /><x:Boolean x:Key="IsClosedLoop">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></mxswa:Workflow></Activity>`}function Qse(){return{adapter:new _m,api:Ise.bpfApi,languageSensitive:!0}}Il.bpfRegistration=Qse});var uU=v(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});Om.buildRegistrations=void 0;var Xse=tk(),Zse=Ck(),ele=nx(),tle=Cx(),rle=jx(),nle=dF(),ile=DF(),ole=cM(),ale=lU();function sle(e){let t=new Map;return t.set("form",(0,Xse.formRegistration)(e)),t.set("view",(0,Zse.viewRegistration)()),t.set("businessRule",(0,ele.businessRuleRegistration)()),t.set("app",(0,tle.appRegistration)(e)),t.set("command",(0,rle.commandRegistration)()),t.set("chart",(0,nle.chartRegistration)()),t.set("dashboard",(0,ile.dashboardRegistration)(e)),t.set("genPage",(0,ole.genPageRegistration)()),t.set("bpf",(0,ale.bpfRegistration)()),t}Om.buildRegistrations=sle});var AU=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var za=Tt(),Sn=fe(),He=oe(),cU=ct(),Ze=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var gU={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},lle=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>gU[e]===t).map(([e])=>e)),ule={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Rw(e){return ule[e]}var Pm=1e6;function cle(e,t){let r=Rw(t),n=()=>{throw new Ze.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Pm} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Pm?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Pm).length||Number(s)>Pm?n():s}}return n()}function dle(e,t){let r=Rw(t);return r?e===r.enabled:e!=="0"}async function fle(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function ple(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var dU=new WeakMap;async function mle(e,t){var r,n;let i=dU.get(e);if(i||(i=new Map,dU.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,He.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function hle(e,t,r){var n,i;let o=await mle(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,He.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ze.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var gle=4,yle=500,fU=20,pU=3e4;function ble(e){if(e===void 0)return gle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${fU}; got ${e}.`);return Math.min(fU,Math.max(1,Math.floor(e)))}function vle(e){if(e===void 0)return yle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${pU}; got ${e}.`);return Math.min(pU,Math.max(0,Math.floor(e)))}async function wle(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await hle(e,m,n),f===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(m){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await Rm(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function yU(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Rw(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Rm(e,t,r={}){var n;let i=[`SettingName='${(0,He.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,He.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=Rm;async function bU(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Sn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=bU;async function Cle(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Rm(e,i,t);r[n]={enabled:yU(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Cle;async function Ele(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ze.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=ble(n.verifyAttempts),a=vle(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=gU[p];g&&s.push({feature:p,setting:g,requestedValue:cle(h,p)})}let l=[],u=n.appModuleId?(0,He.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await ple(e,t);if(p&&(0,He.normalizeGuid)(p,"appModuleId")!==u)throw new Ze.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await fle(e,t)),c),f=new Map,m=async p=>{if(lle.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Rm(e,h);f.set(h,{enabled:yU(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await bU(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await wle(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let C=dle(g,p)?await m(p):void 0;C&&!C.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${C.setting}' reads '${C.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=Ele;var vU="GptPowerPrompt",Ale='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function wU(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=wU;async function Sle(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,He.odataPathLiteral)(t)}')${(0,He.odataQuery)([["$select","MetadataId"]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,za.describeMalformedValue)(o)}`);return o}async function CU(e){var t,r;let n=`/msdyn_aitemplates${(0,He.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${vU}'`],["$top",1]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(t=i.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(o))throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(o)}`);return((r=o[0])!==null&&r!==void 0?r:{}).msdyn_aitemplateid}function EU(e){return`${e} row summary`}async function Nle(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,He.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,Sn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await CU(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===EU(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function _le(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=s[0];if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Sle(e,t.entityLogicalName),c=await CU(e);if(c===void 0)throw new Ze.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${vU}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,cU.newId)(),f=(0,cU.newId)(),m=JSON.stringify(wU(t)),p={ModelId:d,RunConfigurationId:f,ModelName:EU(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:Ale,RunConfiguration:""};(0,Sn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,Sn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,Sn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=_le;async function Tle(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,Sn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);let s=a[0];if(!s)return;let l=(0,He.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,He.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Nle(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await mU(e,f,`${f}${(0,He.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${hU(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await mU(e,p,`${p}${(0,He.odataQuery)([["$select","msdyn_aimodelid"]])}`,Ile);if(h.kind==="failed")throw(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${hU(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}}Te.removeRowSummary=Tle;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Dle="0x8004f01f";function Ile(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Dle}function Ole(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function mU(e,t,r,n=()=>!1){let i;try{let o=await(0,Sn.resendWhile)(Ole,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,Sn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function hU(e){return e instanceof Error?e.message:String(e)}});var _U=v(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.findArtifact=Ol.resolveArtifact=void 0;var Ht=oe(),no=Zd(),Ple=Af(),Rle=Tt(),Lle=fe(),SU=Q();async function NU(e,t,r){let n="/uxagentprojects"+(0,Ht.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Ht.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Rle.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function kle(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Ple.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Ht.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Lle.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Ht.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,no.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Ht.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Ht.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,no.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Ht.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Ht.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,no.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Ht.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,no.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Ht.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return NU(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}Ol.resolveArtifact=kle;async function $le(e,t,r){var n,i,o,a,s,l;let u=(0,Ht.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Ht.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await NU(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new SU.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=xle(t,u,c,r),f=t!=="app",m=await(0,no.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new SU.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}Ol.findArtifact=$le;function xle(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,Ht.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var DU=v(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});km.seedRecordGraph=void 0;var TU=Zd(),Fle=$d(),Lm=oe(),Mle=Q();async function Ule(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Fle.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let P=D.parentEntity.toLowerCase(),x=(s=d(P))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Mle.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,Lm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Le=(0,Lm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Le})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Lm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Lm.odataLiteral)(x)}'`).join(" or "),P=await(0,TU.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let P=D.toLowerCase(),x=C.get(P);if(x!==void 0)return x;let K=w.push(L)-1;return C.set(P,K),K}return w.push(L)-1}),O=w.length?await(0,TU.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}km.seedRecordGraph=Ule});var MU=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.getEntityPrivileges=or.addEntityPrivilegesToRole=or.deleteSecurityRole=or.createPersonaRole=or.createSecurityRole=or.SDK_ROLE_MARKER=void 0;var zn=fe(),Ft=oe(),rn=Q(),$m={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},kw={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},IU={user:1,businessUnit:2,parentChild:3,organization:4},Lw={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};or.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Ble(e){return Object.prototype.hasOwnProperty.call($m,e)?$m[e]:void 0}function qle(e){return Object.prototype.hasOwnProperty.call(kw,e)}var OU=new WeakMap,PU=new WeakMap;async function kU(e,t){var r,n;(0,Ft.assertODataName)(t,"entity logical name");let i=OU.get(e);i||(i=new Map,OU.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Ft.odataPathLiteral)(t)}')${(0,Ft.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,zn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new rn.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Vle(e){var t,r,n;let i=PU.get(e);if(i)return i;let o=`/businessunits${(0,Ft.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new rn.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Ft.normalizeGuid)(l,"businessUnitId");return PU.set(e,u),u}async function $U(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new rn.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!qle(o))throw new rn.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await kU(e,i.entity);for(let s of i.access){let l=Ble(s);if(!l)throw new rn.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new rn.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Lw[o];if(u[c]===!1)throw new rn.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Ft.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new rn.InvalidArgumentError(`Entities '${p}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}f.scope=IU[o]>IU[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function Gle(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:kw[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,zn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function RU(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Ft.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,zn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function Wle(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Ft.normalizeGuid)(l,"teamId");if(!await RU(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Ft.normalizeGuid)(l,"userId");if(!await RU(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function LU(e,t,r){var n,i;let o=`/roles${(0,Ft.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Ft.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===or.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new rn.InvalidArgumentError(`A role named '${t}' already exists in this business unit and was not created by the SDK; refusing to modify or assign it. Choose a different persona/role name.`);if(l.length>1)throw new rn.InvalidArgumentError(`Multiple (${l.length}) SDK-owned roles named '${t}' exist in this business unit; refusing to reuse one arbitrarily. Remove the duplicate role(s) and retry.`);let c=l[0].roleid;return c?(0,Ft.normalizeGuid)(c,"roleId"):void 0}function zle(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Ft.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Ft.normalizeGuid)(n,"userId"))}}function xU(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function FU(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Ft.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Vle(e),a=await $U(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=zle(t.assignTo),l=await LU(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:or.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,zn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Ft.normalizeGuid)((0,zn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await LU(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await Gle(e,l,a,u);let c=await Wle(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:xU(a),assignedTeams:c.teams,assignedUsers:c.users}}or.createSecurityRole=FU;async function jle(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return FU(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}or.createPersonaRole=jle;async function Hle(e,t){let n=`/roles(${(0,Ft.normalizeGuid)(t,"roleId")})`;(0,zn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}or.deleteSecurityRole=Hle;async function Kle(e,t,r){let n=(0,Ft.normalizeGuid)(t,"roleId");if(r.length===0)throw new rn.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await $U(e,r),o={Privileges:i.map(s=>({Depth:kw[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,zn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),xU(i)}or.addEntityPrivilegesToRole=Kle;var Jle=new Map(Object.keys($m).map(e=>[$m[e],e]));async function Yle(e,t){return(await kU(e,t)).map(n=>{let i=Object.keys(Lw).filter(a=>n[Lw[a]]!==!1),o=Jle.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}or.getEntityPrivileges=Yle});var tB=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.createMakerSdk=Er.MakerSdk=Er.PUSH_NOT_ATTEMPTED_CODE=Er.ALREADY_EXISTS_CODE=void 0;var UU=dh(),BU=jr(),Z=Q(),Nn=Xa(),Qle=CE(),QU=DE(),Pl=kE(),Xle=ph(),Zle=tA(),Rl=iA(),eue=bA(),tue=SA(),rue=tS(),qU=QS(),Mt=$d(),$w=e0(),VU=l_(),xm=vu(),io=Zd(),Fm=g_(),Ll=tf(),nue=nf(),ar=Jd(),iue=aT(),oue=v0(),aue=T0(),GU=w0(),sue=uU(),Mm=ct(),lue=sa(),Ai=Av(),_n=bh(),xw=lw(),uue=3e5,Cr=fe(),ja=oe(),kl=AU(),WU=_U(),cue=DU(),due=Ub(),Uc=MU(),XU=Symbol("cds-maker-sdk.committedWrite");function fue(e){return typeof e=="object"&&e!==null&&(e[XU]=!0),e}function pue(e){return typeof e=="object"&&e!==null&&e[XU]===!0}var mue={fileConcurrency:1},Fw="SOLUTION_COMPONENT_UNCLASSIFIED",hue=2,gue=4,yue="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function zU(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:yue}:{}}}function jU(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:zo(t)}}function HU(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,Cr.nowIso)(),isDirty:!1}}var bue=new Set(["entity","appmodule","dashboard","uxagentproject"]);function vue(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,ja.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function wue(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new QU.WorkspaceManager(Eue,e.instanceUrl,(0,Xle.assertStorageContract)(t))}Er.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Cue="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";Er.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Eue="<injected workspaceStorage>",Um=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,xw.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:lue.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:uue,this.compiler={load:(0,oue.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=wue(t),this.versions=new Pl.VersionManager(this.workspace),this.dataverse=new Zle.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new rue.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,sue.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,_n.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,Cr.nowIso)()},b)}return(0,Ai.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,Ai.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,ar.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(zU(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(HU(a,o,s))}catch(a){i.push(jU(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,Cr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,xw.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(zU(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(HU(a.type,o,s))}catch(a){n.push(jU(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,mue);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,xw.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,Rl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,eue.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,Rl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,tue.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,Rl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Mt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Mt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,$w.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,$w.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Mt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Mt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Mt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Mt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Mt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Mt.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large})),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,ja.xmlText)(t)}</entity></entities></importexportxml>`;(0,Cr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Mt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Mt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Mt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Mt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Mt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Uc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Uc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Uc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Uc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Uc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,io.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,io.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,io.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,io.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,io.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,io.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,io.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,cue.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,WU.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,WU.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,aue.deleteAppCascade)(this.dataverse,t,r),i=(0,ja.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,io.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,io.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Fm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Fm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Fm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Fm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Ll.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Ll.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:nue.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Ll.setAppSetting)(this.dataverse,t,Ll.HEADER_AND_NAVIGATION_REFRESH,r?Ll.APP_SETTING_ON:Ll.APP_SETTING_OFF)}getSolution(t){return(0,ar.getSolution)(this.dataverse,t)}createPublisher(t){return(0,ar.createPublisher)(this.dataverse,t)}createSolution(t){return(0,ar.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,ar.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,ar.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,ar.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,ar.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,ar.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,ar.getDeploymentSettingsTemplate)(this.dataverse,t)}registerPcfControl(t,r){let n=()=>(0,iue.registerPcfControl)(this.dataverse,t,r);return r?.publishAll===!0?this.schemaWrite(void 0,n):n()}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,ar.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,QU.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,_n.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=Nn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,Qle.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=Nn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=oo(s)&&oo(i)?{...s,...i}:i;return Nn.JsonPointer.set(a,n,(0,Ai.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=Nn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!oo(l)||!oo(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,Ai.cloneJson)(i[f]),p=(0,Mm.isValueMapKey)(f)||(0,Mm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>oo(h)?this.assignMissingIds(t,h):h):oo(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))Nn.JsonPointer.set(s,Nn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Mm.pointerTouchesValueMap)(n)?(0,Ai.cloneJson)(i):this.assignMissingIds(t,(0,Ai.cloneJson)(i)),c=_ue(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=Nn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=Nn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");Nn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),YU(c);let f=Nn.JsonPointer.resolve(l,JU(n));return Array.isArray(f)&&f!==c&&YU(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(Nn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return Nn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,JU(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,kl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,kl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,kl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,kl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,kl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,kl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,due.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,BU.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&pue(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,Ai.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=vue(a),f;if(d)try{await(0,BU.publishXml)(this.dataverse,d)}catch(p){f=zo(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!bue.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,_n.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:zo(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,Cr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!Sue(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,_n.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,Cr.isVersionToken)(o)||!ZU(a,t.heldSiblings)||!eB(a)||!(o!==t.heldEtag||!(0,_n.deepEqual)(a??void 0,t.heldSiblings))||!(0,_n.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,Cr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${zo(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,_n.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,_n.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,Cr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i,o,a,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,ja.normalizeGuid)(r,"id")})${(0,ja.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},f=n;if(!f)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let m=[];return((o=f.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&m.push("name"),((s=f.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&m.push("description"),m.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${m.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:zo(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,_n.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,_n.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:zo(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,Rl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let P=await this.createWithMintedId(m,d,f,g,p);if("adopted"in P)return await this.persistAdoption(d,f,p,P.adopted);w=P.written}b=!0;let C=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,O=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,C,O.artifact,h&&C===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,_n.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,C,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,C,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(O.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},C===f?h:void 0),{type:d,id:C,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var P;let x=(P=m.publishScope)===null||P===void 0?void 0:P.call(m,C,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let C=(0,Z.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},O={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(O).length>0?{siblingEtags:O}:{}},h)}if(w instanceof Z.SdkError&&w.code===Er.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===Cr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,GU.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?fue(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==Pl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${Pl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,$w.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,VU.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n,u)+(this.createRecovery==="adoptExact"?` ${KU(Cue)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==Cr.VERSION_CONFLICT_CODE||(0,GU.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,VU.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,`${Mw(r,n)} ${KU(l.refused)}`)}throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,_n.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=Rl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(P=>P.entityLogicalName===L).map(P=>P.fieldName);try{let P=await(0,Rl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,P,x;return(P=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,C=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),O=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:Nue(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...C!==void 0?{baseLanguageCode:C}:{},...O?{pcf:O}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,qU.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,qU.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(Er.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Mm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case ar.SolutionComponentType.SavedQuery:return"view";case ar.SolutionComponentType.SavedQueryVisualization:return"chart";case ar.SolutionComponentType.AppModule:return"app";case ar.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case ar.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,xm.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(Fw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,xm.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,ja.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,ja.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,Cr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,xm.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(Fw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===hue)return"businessRule";if(a===gue){let s=(0,xm.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(Fw,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Er.MakerSdk=Um;function Aue(e){return new Um(e)}Er.createMakerSdk=Aue;function zo(e){return e instanceof Error?e:new Error(String(e))}function ZU(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function eB(e){return Object.values(e??{}).every(Cr.isVersionToken)}function Sue(e,t){return ZU(e,t)&&eB(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function KU(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Mw(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function Nue(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JU(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function YU(e){e.length===0||!e.every(t=>oo(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function _ue(e,t){if(t===void 0||t==="end")return e.length;if(t==="start")return 0;if("index"in t)return Math.max(0,Math.min(t.index,e.length));if("before"in t){let n=e.findIndex(i=>oo(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>oo(n)&&n.id===t.after);return r<0?e.length:r+1}});var rB=v(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.ARTIFACT_TYPES=void 0;Bm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var iB=v(nB=>{"use strict";Object.defineProperty(nB,"__esModule",{value:!0})});var aB=v(oB=>{"use strict";Object.defineProperty(oB,"__esModule",{value:!0})});var lB=v(sB=>{"use strict";Object.defineProperty(sB,"__esModule",{value:!0})});var cB=v(uB=>{"use strict";Object.defineProperty(uB,"__esModule",{value:!0})});var fB=v(dB=>{"use strict";Object.defineProperty(dB,"__esModule",{value:!0})});var mB=v(pB=>{"use strict";Object.defineProperty(pB,"__esModule",{value:!0})});var gB=v(hB=>{"use strict";Object.defineProperty(hB,"__esModule",{value:!0})});var bB=v(yB=>{"use strict";Object.defineProperty(yB,"__esModule",{value:!0})});var wB=v(vB=>{"use strict";Object.defineProperty(vB,"__esModule",{value:!0})});var EB=v(CB=>{"use strict";Object.defineProperty(CB,"__esModule",{value:!0})});var SB=v(AB=>{"use strict";Object.defineProperty(AB,"__esModule",{value:!0})});var _B=v(NB=>{"use strict";Object.defineProperty(NB,"__esModule",{value:!0})});var DB=v(TB=>{"use strict";Object.defineProperty(TB,"__esModule",{value:!0})});var OB=v(IB=>{"use strict";Object.defineProperty(IB,"__esModule",{value:!0})});var RB=v(PB=>{"use strict";Object.defineProperty(PB,"__esModule",{value:!0})});var kB=v(LB=>{"use strict";Object.defineProperty(LB,"__esModule",{value:!0})});var xB=v($B=>{"use strict";Object.defineProperty($B,"__esModule",{value:!0})});var MB=v(FB=>{"use strict";Object.defineProperty(FB,"__esModule",{value:!0})});var BB=v(UB=>{"use strict";Object.defineProperty(UB,"__esModule",{value:!0})});var VB=v(qB=>{"use strict";Object.defineProperty(qB,"__esModule",{value:!0})});var WB=v(GB=>{"use strict";Object.defineProperty(GB,"__esModule",{value:!0})});var jB=v(zB=>{"use strict";Object.defineProperty(zB,"__esModule",{value:!0})});var KB=v(ce=>{"use strict";var Tue=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ue=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Tue(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Due=tB();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Due.createMakerSdk}});Ue(rB(),ce);Ue(iB(),ce);Ue(aB(),ce);Ue(lB(),ce);Ue(cB(),ce);Ue(fB(),ce);Ue(mB(),ce);Ue(gB(),ce);Ue(bB(),ce);Ue(wB(),ce);Ue(EB(),ce);Ue(SB(),ce);Ue(_B(),ce);Ue(DB(),ce);Ue(OB(),ce);Ue(nf(),ce);Ue(RB(),ce);Ue(kB(),ce);Ue(xB(),ce);Ue(MB(),ce);Ue(BB(),ce);Ue(VB(),ce);Ue(WB(),ce);Ue(jB(),ce);Ue(Q(),ce);var HB=Wl();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return HB.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return HB.projectConnectorOperationSchema}})});var Bw=v(Si=>{"use strict";var Iue=Si&&Si.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Oue=Si&&Si.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),QB=Si&&Si.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Iue(t,e,r);return Oue(t,e),t};Object.defineProperty(Si,"__esModule",{value:!0});Si.NodeFileSystemStorage=void 0;var Nt=QB(require("fs")),sr=QB(require("path")),JB=Q(),YB=mh();async function XB(e){let t;try{t=await Nt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Nt.promises.unlink(e)}catch{await Nt.promises.rmdir(e)}return}if(!t.isDirectory()){await Nt.promises.unlink(e);return}for(let r of await Nt.promises.readdir(e))await XB(sr.join(e,r));await Nt.promises.rmdir(e)}var Uw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(sr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Nt.existsSync(r);){n.unshift(sr.basename(r));let i=sr.dirname(r);if(i===r)return sr.resolve(t);r=i}return sr.resolve(Nt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=sr.resolve(this.root),i=sr.resolve(t);if(i!==n&&!i.startsWith(n+sr.sep))throw new JB.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):sr.resolve(this.realPathThroughNearestAncestor(sr.dirname(i)),sr.basename(i));if(a!==o&&!a.startsWith(o+sr.sep))throw new JB.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Nt.existsSync(r))return null;try{return await(0,YB.retryTransientIoAsync)(()=>Nt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=sr.dirname(n);await Nt.promises.mkdir(i,{recursive:!0});let o=sr.join(i,`.${sr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Nt.promises.writeFile(o,r,"utf8"),await(0,YB.retryTransientIoAsync)(()=>Nt.promises.rename(o,n))}catch(a){try{Nt.existsSync(o)&&await Nt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Nt.existsSync(r)&&await Nt.promises.unlink(r)}async deleteByPrefix(t){await XB(this.pathFor(t,!1))}async ensureContainer(t){await Nt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Nt.existsSync(this.pathFor(t))}};Si.NodeFileSystemStorage=Uw});var ZB=v(Wr=>{"use strict";var Pue=Wr&&Wr.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Rue=Wr&&Wr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Lue=Wr&&Wr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Pue(t,e,r);return Rue(t,e),t};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.loadNodeTypeScript=Wr.createNodeWorkspaceStorage=Wr.NodeFileSystemStorage=void 0;var kue=Bw(),$ue=Bw();Object.defineProperty(Wr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return $ue.NodeFileSystemStorage}});function xue(e){return new kue.NodeFileSystemStorage(e)}Wr.createNodeWorkspaceStorage=xue;async function Fue(){return await Promise.resolve().then(()=>Lue(require("typescript")))}Wr.loadNodeTypeScript=Fue});var ao={};module.exports=zr(ao);so(ao,Ce(KB()),module.exports);so(ao,Ce(ZB()),module.exports);+`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,he.resendWhile)(m=>uW(m,s),()=>e.postBatch(o,r),he.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=a_(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,e_.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new Se.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function $d(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,he.readEtag)(r)}catch{return null}}async function JN(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,he.ensureSuccess)(n,e.apiUrl(r)),(0,he.readEtag)(n)}function YN(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Ig(e,t,r,n){if(!n)return null;let i=await $d(e,t);if(!i)return null;try{let o=await e.get(Fd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=nu(o);return!a||!Md(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function l_(e){return e>=400&&e<500&&e!==408&&e!==429}function QN(e,t,r){if(!e)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function u_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:QN(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await cW(e,n,i);return}if(!e.supportsAtomicBatch)throw new Se.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await lW(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:QN(r.sitemapEtag,t,"sitemap")}])}async function cW(e,t,r){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function XN(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,V8.collectGenPageIds)(t))]}catch(i){throw new Se.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Oi(i)}).`)}if(r.length===0)return;let n=await(0,G8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Se.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function dW(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 fW(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 ZN(e,t,r){var n;let i=(0,Ne.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await JN(e,i):null,s=Rg(Pg,i),l=(0,he.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=nu(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new Se.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await t_(e,u.uniquename),d=c?(0,Ne.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await $d(e,d));let p=Fd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,he.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=nu(h),b=w=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Md(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await $d(e,d))}o||(a=await JN(e,i));let m=a??H8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ne.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Qn.appApi={get(e,t){return ZN(e,t,"tokens-first")},readContentThenToken(e,t){return ZN(e,t,"content-first")},async list(e,t){let r=Rg(Pg);return(await(0,ms.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new Se.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 XN(e,n.sitemapxml);let i=await jN(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await J8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new Se.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||K8(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,he.ensureSuccess)(await(0,he.resendDeadlockVictim)(()=>e.post(c,(0,he.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,he.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ne.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Og.newId)(),w=!1,E=YN(n);try{let P="/sitemaps",L=(0,he.echoWrite)("sitemapid"),I=await e.post(`${P}${L.query}`,{sitemapid:b,sitemapnameunique:l,...E},L.options);w=l_(I.status);let D=(0,he.ensureSuccess)(I,e.apiUrl(P));p=(0,he.readEtag)(D),m=p??await Ig(e,b,E,l);let O=await WN(e,n,i);h.push(...O.warnings);let x=O.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await HN(e,f,x);let K=kd(e,f);await KN(e,f,O.tables,K),i&&await tW(e,f,i,K);let Re=await Y8(e,f);Re&&h.push(Re),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,W8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,BN.publishAppModule)(e,f),g={kind:"submitted"})}catch(P){let L=await nW(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,z8.failedAfterPrimaryWrite)(iW(P,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let P=await e.get(`/appmodules(${f})?$select=appmoduleid`);P.status>=200&&P.status<300&&(S=(0,he.readEtag)(P))}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,Ne.normalizeGuid)(t,"id");if(await XN(e,u.sitemapxml),!u.sitemapId)throw new Se.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,Ne.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,he.isVersionToken)(n))throw new Se.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 jN(e,u,c),m=await WN(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let ge=Rg(Pg,c),je=await e.get(ge);if(je.status>=200&&je.status<300){let de=nu(je);if(typeof de=="object"&&de!==null&&!Array.isArray(de)){g=de;let He=g.uniquename;b=typeof He=="string"&&He?He:void 0}}}catch{}let w=fW(u,g),E=h;if(Object.keys(w).length>0){if(!(0,he.isVersionToken)(h))throw new Se.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 ge=(0,he.echoWrite)("appmoduleid",{"If-Match":h}),je=await e.patch(`${p}${ge.query}`,w,ge.options);if(dW(je))throw new Se.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,he.ensureSuccess)(je,e.apiUrl(p)),E=(0,he.readEtag)(je)}let S=YN(u),P=b||u.appModuleUniqueName||void 0,L=(0,he.echoWrite)("sitemapid",{"If-Match":n}),I=`/sitemaps(${d})`,D;try{D=(0,he.ensureSuccess)(await e.patch(`${I}${L.query}`,{...S},L.options),e.apiUrl(I))}catch(ge){throw(0,Se.withPartialTokens)(ge,{siblingEtags:{[c]:E}})}let O=[...m.warnings],x=kd(e,c);try{await HN(e,c,m.components),await KN(e,c,m.tables,x)}catch(ge){O.push(`App '${c}': one or more components were not pinned (${ge.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&O.push(...await rW(e,c,f,x));let K={kind:"notRequested"},Re=E,qt=(s=(0,he.readEtag)(D))!==null&&s!==void 0?s:await Ig(e,d,S,P);if(u.published===!0){try{await(0,BN.publishAppModule)(e,c),K={kind:"submitted"}}catch(ge){K={kind:"failed",error:ge},O.push(`App '${c}': saved, but publishing failed (${ge.message}). The app remains unpublished; re-push to retry.`)}if(K.kind==="submitted"){Re=null;try{let ge=await e.get(`/appmodules(${c})?$select=appmoduleid`);ge.status>=200&&ge.status<300&&(Re=(0,he.readEtag)(ge)),qt=(l=await Ig(e,d,S,P))!==null&&l!==void 0?l:qt}catch{}}}return{id:c,etag:qt,siblingEtags:{[c]:Re},publish:K,...O.length>0?{warnings:O}:{}}},async delete(e,t){let r=(0,Ne.normalizeGuid)(t,"id");await u_(e,r,await o_(e,r))}}});var $g=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.deleteAppCascade=hs.collectGenPageIds=void 0;var pW=Ud(),mW=Q(),xg=se(),hW=es();function c_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new hW.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 mW.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,xg.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}hs.collectGenPageIds=c_;async function gW(e,t,r){let n=(0,xg.normalizeGuid)(t,"appModuleId");(0,xg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,pW.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...c_(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}hs.deleteAppCascade=gW});var d_={};Hr(d_,{Guid:()=>U});var U,pt=k(()=>{"use strict";U=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var q,Yt=k(()=>{"use strict";ot();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 f_={};Hr(f_,{ScriptUtilities:()=>R});var R,ot=k(()=>{"use strict";pt();Yt();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 Bd,qd,ea,Vd,Fg,Gd,Mg=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Bd||(Bd={}));qd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ea=class extends qd{key;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Vd=class extends qd{property;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Fg=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()})}},Gd=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 Fg(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 p_={};Hr(p_,{ChartGridMode:()=>an,ColumnLayoutWidths:()=>CW,ComponentCategory:()=>zd,ComponentType:()=>Ug,ControlLayoutTypes:()=>jg,DisplayConditionsInfo:()=>vW,ElementNames:()=>C,ElementProperties:()=>y,ElementType:()=>qg,EntityAttributeProperty:()=>Vg,EventType:()=>iu,FormActivationState:()=>zg,FormCanvasServiceScope:()=>LW,FormDesignerSideBarTab:()=>Bg,FormPresentation:()=>Gg,FormState:()=>Wd,FormType:()=>mt,HeaderDensityType:()=>mo,LookUpTable:()=>Xn,MORE_TAB_PREFIX:()=>AW,NavBarChildElementType:()=>Wg,PREVIEW_ID_HEADER_FLYOUT:()=>TW,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>IW,PREVIEW_ID_NAVIGATION_AREA:()=>NW,PREVIEW_ID_QUICKCREATE_ROOT:()=>PW,PREVIEW_ID_TAB:()=>OW,PREVIEW_ID_TAB_LIST:()=>DW,PREVIEW_ID_TAB_PANEL:()=>_W,PropertyModelKeys:()=>Jg,PropertyModelSectionKeys:()=>EW,RELATED_TAB_ID:()=>Yg,RELATED_TAB_PREFIX:()=>SW,SectionDefaultProperties:()=>wW,SectionLayoutTypes:()=>ze,TabContentType:()=>Hg,TabDefaultProperties:()=>ho,TabLayoutTypes:()=>We,TelemetryPropertyNames:()=>RW,UnboundControlPropertyKeys:()=>Kg,compositeAddressFields:()=>bW,compositeFieldNames:()=>Gr,compositeFields:()=>yW});var mt,Ug,Bg,C,y,qg,Gr,yW,bW,Vg,Xn,Wd,mo,Gg,vW,Wg,zg,We,wW,ho,ze,jg,Hg,CW,Kg,Jg,EW,iu,an,Yg,AW,SW,NW,_W,TW,DW,IW,OW,PW,RW,zd,LW,le=k(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(mt||(mt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Ug||(Ug={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Bg||(Bg={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(C||(C={}));y={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})(qg||(qg={}));Gr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},yW=[Gr.fullname,Gr.yomifullname,Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto],bW=[Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Vg||(Vg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Xn||(Xn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Wd||(Wd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(mo||(mo={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Gg||(Gg={}));vW={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Wg||(Wg={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(zg||(zg={}));(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"})(We||(We={}));wW={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},ho={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"})(ze||(ze={}));(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"})(jg||(jg={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Hg||(Hg={}));CW={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"})(Kg||(Kg={}));(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"})(Jg||(Jg={}));EW={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})(iu||(iu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(an||(an={}));Yg="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",AW="more_tab_",SW="related_tab_",NW="preview_id_navigation_area",_W="tab-section",TW="headerFieldsFlyout",DW="tablist",IW="header_overflowButton",OW="tab",PW="quickCreateRoot",RW={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"})(zd||(zd={}));LW="CellCanvasServiceScope"});var m_={};Hr(m_,{Attribute:()=>jd,FormElementNode:()=>re});var jd,re,Dt=k(()=>{"use strict";ot();Yt();Mg();le();pt();jd=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(C.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new jd(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 ea(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 ea(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 ea(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 Vd(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 ea(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 C.formCell:let t=this.getAncestor(C.formSection);return t||(t=this.getAncestor(C.formHeader),t)||(t=this.getAncestor(C.formFooter),t)?t:null;case C.formSection:return this.getAncestor(C.formTab);case C.formTab:return this.getAncestor(C.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(C.form);return t?t.changeTracker():null}}});var h_={};Hr(h_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Hd,getControlDisplayNames:()=>kW});function kW(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,Hd,ta=k(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(N||(N={}));Hd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ra=v((Dle,y_)=>{var ou=new Proxy(function(){return ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ou},apply:function(){return ou},construct:function(){return{}}}),g_=function(){return ou};Object.setPrototypeOf(g_,ou);y_.exports=g_});var sr,Pi,b_,v_,gs=k(()=>{"use strict";sr="cds-designer-models",Pi="FormCustomControl",b_="FormCell",v_="Form"});var na,Qg=k(()=>{"use strict";Bl();le();na=class e{static lockedFieldCount=new nr;static dependencyFieldCount=new nr;static getNecessaryLookUpTable(t){switch(t){case Xn.DependencyFieldTable:return e.dependencyFieldCount;case Xn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Xn.DependencyFieldTable:e.dependencyFieldCount=new nr;case Xn.LockedFieldTable:e.lockedFieldCount=new nr}}}});var Kd,w_=k(()=>{"use strict";pt();ot();le();Dt();Kd=class extends re{constructor(t){super(C.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(C.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 Ri(){return Zn||(Zn=window._makerConfig,Zn&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Zn={...Zn,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Zn?.region==="prod"&&(Zn={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/"}}},...Zn}),Zn||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Zn,Jd=k(()=>{"use strict";});function C_(e,t,r){if(!e)return Yd.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Yd.add("")),!1;if(e){if(e=e.toLowerCase(),Yd.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}}),Yd.add(e),!1}return!0}function $W(e){return C_(e,Xg,"Location dictionary")?Xg[e.toLowerCase()]:"us"}function xW(){let e=Ri().location.toLowerCase();return C_(e,Xg,"Current location dictionary")?e:"us"}var Yd,Xg,qle,E_=k(()=>{"use strict";Jd();Yd=new Set,Xg={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"};qle=$W(xW())});var Y,Gle,A_=k(()=>{"use strict";Y={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},Gle={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var S_=k(()=>{"use strict";Jd();});var au=k(()=>{"use strict";Jd();E_();A_();S_();});function su(e,t){return N_?N_.isOverridden(e,t):{overridden:!1}}var N_,lu=k(()=>{"use strict";});var Zg=k(()=>{"use strict";au();lu();});function FW(e,t){let{region:r}=Ri();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=su(e.packageName,t);if(s.overridden)return typeof s.value=="string"?MW(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 MW(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function UW(e){let t=e.packageName;if(Qd.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=>t0(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=>!Zd(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function uu(e){UW(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:FW(e,r)}}),Qd.set(e.packageName,e),Object.defineProperties({},t)}function e0(e,t){return Qd.has(e)?!!Qd.get(e).settings[t]:!1}var Qd,Xd=k(()=>{"use strict";au();lu();r0();cu();Qd=new Map});function __(e,t){let{region:r}=Ri();return()=>{let n=su(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function BW(e){let t=e.packageName;if(ef.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=>e0(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=>!Zd(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function n0(e){BW(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:__(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:__(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},ef.set(e.packageName,e),Object.defineProperties(r,t)}function t0(e,t){return ef.has(e)?!!ef.get(e).features[t]:!1}var ef,r0=k(()=>{"use strict";au();cu();lu();Xd();ef=new Map});var D_=v((mue,T_)=>{"use strict";T_.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 P_=v(i0=>{"use strict";var qW=Object.prototype.hasOwnProperty,VW;function I_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function O_(e){try{return encodeURIComponent(e)}catch{return null}}function GW(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=I_(n[1]),o=I_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function WW(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(qW.call(e,i)){if(n=e[i],!n&&(n===null||n===VW||isNaN(n))&&(n=""),i=O_(i),n=O_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}i0.stringify=WW;i0.parse=GW});var s0=v((gue,F_)=>{"use strict";var L_=D_(),tf=P_(),k_=/[\n\r\t]/g,zW=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,jW=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,HW=/^[a-zA-Z]:/,KW=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function a0(e){return(e||"").toString().replace(KW,"")}var o0=[["#","hash"],["?","query"],function(t,r){return ei(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]],R_={hash:1,query:1};function $_(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 ti(unescape(e.pathname),{});else if(i==="string"){n=new ti(e,{});for(o in R_)delete n[o]}else if(i==="object"){for(o in e)o in R_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=zW.test(e.href))}return n}function ei(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function x_(e,t){e=a0(e),e=e.replace(k_,""),t=t||{};var r=jW.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)):ei(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ei(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ei(n),slashesCount:a,rest:s}}function JW(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 ti(e,t,r){if(e=a0(e),e=e.replace(k_,""),!(this instanceof ti))return new ti(e,t,r);var n,i,o,a,s,l,u=o0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=tf.parse),t=$_(t),i=x_(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||HW.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ei(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=JW(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ei(d.protocol)&&(d.pathname="/"+d.pathname),L_(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:"&&ei(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function YW(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||tf.parse)(t)),n[e]=t;break;case"port":n[e]=t,L_(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<o0.length;a++){var s=o0[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:"&&ei(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function QW(e){(!e||typeof e!="function")&&(e=tf.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||ei(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ei(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}ti.prototype={set:YW,toString:QW};ti.extractProtocol=x_;ti.location=$_;ti.trimLeft=a0;ti.qs=tf;F_.exports=ti});var XW,M_=k(()=>{"use strict";XW=Ee(s0());});function l0(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 rf=k(()=>{"use strict";});var u0,c0,d0=k(()=>{"use strict";rf();u0=class{features=new Map;register(t,r){let n=l0(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()}},c0=new u0});var f0=k(()=>{"use strict";});function Zd(e){return ZW.has(e)}var ZW,cu=k(()=>{"use strict";Zg();r0();Xd();lu();Zg();M_();d0();rf();f0();ZW=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var e6,U_=k(()=>{"use strict";cu();e6=uu({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var G_,m0,ys,ia,p0,nf,bs,Li,Ue,B_,q_,V_,_n=k(()=>{"use strict";G_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},m0={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(ys||(ys={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(ia||(ia={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(p0||(p0={}));nf=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})(bs||(bs={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:ia.Left,labelPosition:bs.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(B_||(B_={}));(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"})(V_||(V_={}))});var h0,W_=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(h0||(h0={}))});var H_,t6,z_,dce,fce,du,j_,pce,mce,K_=k(()=>{"use strict";H_=Ee(ra());ot();gs();U_();rs();_n();zo();le();t6=Ee(Yi());W_();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(z_||(z_={}));dce={Read:no.Read,Edit:no.Edit,Both:no.Both,Container:no.Container},fce={input:Wo.Input,bound:Wo.Bound,output:Wo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(du||(du={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(j_||(j_={}));pce=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]),mce={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 Tn,of,J_=k(()=>{"use strict";Tn=Ee(ra());pt();ot();Yt();gs();zo();K_();rs();le();Dt();_n();of=class extends re{constructor(t){super(C.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(jt.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===jt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===jt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(jt.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:Lh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===du.dataset?o.get(jt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===du.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Tn.trackInfoTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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===jt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===_i.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(Rh.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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Tn.trackWarningTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return od.includes(t)}isNumberTypeProperty(t,r){return ad.includes(r)||t.ofTypeGroup.some(n=>ad.includes(n))}isDataSet(t){return jt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,g0=k(()=>{"use strict";ee=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var Y_={};Hr(Y_,{CustomControlUniqueId:()=>oa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>at,mapFieldTypeToControl:()=>r6});function r6(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,oa,at,fu=k(()=>{"use strict";pt();Bl();ot();Yt();rs();ta();g0();_n();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"}};oa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},at=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new nr;static initializeFieldControls(){let t=new nr,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 E=e.getControlName($.Currency,W.None);t.add(E,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let P=e.getControlName($.MultipleLineofText,W.Text);t.add(P,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let O=e.getControlName($.TwoOptions,W.None);t.add(O,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 Re=e.getControlName($.TwoOptions,"Radio");t.add(Re,new U(G.RadioControl));let qt=e.getControlName($.TwoOptions,"CheckBox");t.add(qt,new U(G.CheckBoxControl));let ge=e.getControlName($.TwoOptions,"List");t.add(ge,new U(G.PicklistControl));let je=e.getControlName($.State,W.None);t.add(je,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let He=e.getControlName($.OwnerType,W.None);t.add(He,new U(G.LookupControl));let bn=e.getControlName($.PartyListType,W.None);t.add(bn,new U(G.PartyListControl));let CU=e.getControlName($.LookupType,W.Regarding);t.add(CU,new U(G.RegardingControl));let EU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(EU,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 nr;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(oa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new nr;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 ts;return t.add(ys.IFRAME,!0),t.add(ys.SPACER,!0),t.add(ys.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===oa.RelationshipAssistant||t.guidString===oa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===oa.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 af,Q_=k(()=>{"use strict";af=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 aa,vs,X_,Z_,go,eT,tT,y0=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(aa||(aa={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(vs||(vs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(X_||(X_={}));(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"})(Z_||(Z_={}));(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"})(go||(go={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(eT||(eT={}));(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"})(tT||(tT={}))});var ws,rT=k(()=>{"use strict";cu();ws=n0({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 nT(e){return{...e,extractConfig:t=>n6(t,Object.keys(e.fallback))}}function n6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var b0=k(()=>{"use strict";});var v0=v((qce,oT)=>{var pu=new Proxy(function(){return pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:pu},apply:function(){return pu},construct:function(){return{}}}),iT=function(){return pu};Object.setPrototypeOf(iT,pu);oT.exports=iT});var lT=v((Vce,sT)=>{var mu=new Proxy(function(){return mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:mu},apply:function(){return mu},construct:function(){return{}}}),aT=function(){return mu};Object.setPrototypeOf(aT,mu);sT.exports=aT});var w0=v((Gce,cT)=>{var hu=new Proxy(function(){return hu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:hu},apply:function(){return hu},construct:function(){return{}}}),uT=function(){return hu};Object.setPrototypeOf(uT,hu);cT.exports=uT});var fT=v((Wce,dT)=>{function i6(){this.__data__=[],this.size=0}dT.exports=i6});var Cs=v((zce,pT)=>{function o6(e,t){return e===t||e!==e&&t!==t}pT.exports=o6});var gu=v((jce,mT)=>{var a6=Cs();function s6(e,t){for(var r=e.length;r--;)if(a6(e[r][0],t))return r;return-1}mT.exports=s6});var gT=v((Hce,hT)=>{var l6=gu(),u6=Array.prototype,c6=u6.splice;function d6(e){var t=this.__data__,r=l6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():c6.call(t,r,1),--this.size,!0}hT.exports=d6});var bT=v((Kce,yT)=>{var f6=gu();function p6(e){var t=this.__data__,r=f6(t,e);return r<0?void 0:t[r][1]}yT.exports=p6});var wT=v((Jce,vT)=>{var m6=gu();function h6(e){return m6(this.__data__,e)>-1}vT.exports=h6});var ET=v((Yce,CT)=>{var g6=gu();function y6(e,t){var r=this.__data__,n=g6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}CT.exports=y6});var yu=v((Qce,AT)=>{var b6=fT(),v6=gT(),w6=bT(),C6=wT(),E6=ET();function Es(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Es.prototype.clear=b6;Es.prototype.delete=v6;Es.prototype.get=w6;Es.prototype.has=C6;Es.prototype.set=E6;AT.exports=Es});var NT=v((Xce,ST)=>{var A6=yu();function S6(){this.__data__=new A6,this.size=0}ST.exports=S6});var TT=v((Zce,_T)=>{function N6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}_T.exports=N6});var IT=v((ede,DT)=>{function _6(e){return this.__data__.get(e)}DT.exports=_6});var PT=v((tde,OT)=>{function T6(e){return this.__data__.has(e)}OT.exports=T6});var C0=v((rde,RT)=>{var D6=typeof global=="object"&&global&&global.Object===Object&&global;RT.exports=D6});var Dn=v((nde,LT)=>{var I6=C0(),O6=typeof self=="object"&&self&&self.Object===Object&&self,P6=I6||O6||Function("return this")();LT.exports=P6});var bu=v((ide,kT)=>{var R6=Dn(),L6=R6.Symbol;kT.exports=L6});var MT=v((ode,FT)=>{var $T=bu(),xT=Object.prototype,k6=xT.hasOwnProperty,$6=xT.toString,vu=$T?$T.toStringTag:void 0;function x6(e){var t=k6.call(e,vu),r=e[vu];try{e[vu]=void 0;var n=!0}catch{}var i=$6.call(e);return n&&(t?e[vu]=r:delete e[vu]),i}FT.exports=x6});var BT=v((ade,UT)=>{var F6=Object.prototype,M6=F6.toString;function U6(e){return M6.call(e)}UT.exports=U6});var sa=v((sde,GT)=>{var qT=bu(),B6=MT(),q6=BT(),V6="[object Null]",G6="[object Undefined]",VT=qT?qT.toStringTag:void 0;function W6(e){return e==null?e===void 0?G6:V6:VT&&VT in Object(e)?B6(e):q6(e)}GT.exports=W6});var ki=v((lde,WT)=>{function z6(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}WT.exports=z6});var sf=v((ude,zT)=>{var j6=sa(),H6=ki(),K6="[object AsyncFunction]",J6="[object Function]",Y6="[object GeneratorFunction]",Q6="[object Proxy]";function X6(e){if(!H6(e))return!1;var t=j6(e);return t==J6||t==Y6||t==K6||t==Q6}zT.exports=X6});var HT=v((cde,jT)=>{var Z6=Dn(),ez=Z6["__core-js_shared__"];jT.exports=ez});var YT=v((dde,JT)=>{var E0=HT(),KT=(function(){var e=/[^.]+$/.exec(E0&&E0.keys&&E0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function tz(e){return!!KT&&KT in e}JT.exports=tz});var A0=v((fde,QT)=>{var rz=Function.prototype,nz=rz.toString;function iz(e){if(e!=null){try{return nz.call(e)}catch{}try{return e+""}catch{}}return""}QT.exports=iz});var ZT=v((pde,XT)=>{var oz=sf(),az=YT(),sz=ki(),lz=A0(),uz=/[\\^$.*+?()[\]{}|]/g,cz=/^\[object .+?Constructor\]$/,dz=Function.prototype,fz=Object.prototype,pz=dz.toString,mz=fz.hasOwnProperty,hz=RegExp("^"+pz.call(mz).replace(uz,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gz(e){if(!sz(e)||az(e))return!1;var t=oz(e)?hz:cz;return t.test(lz(e))}XT.exports=gz});var tD=v((mde,eD)=>{function yz(e,t){return e?.[t]}eD.exports=yz});var yo=v((hde,rD)=>{var bz=ZT(),vz=tD();function wz(e,t){var r=vz(e,t);return bz(r)?r:void 0}rD.exports=wz});var lf=v((gde,nD)=>{var Cz=yo(),Ez=Dn(),Az=Cz(Ez,"Map");nD.exports=Az});var wu=v((yde,iD)=>{var Sz=yo(),Nz=Sz(Object,"create");iD.exports=Nz});var sD=v((bde,aD)=>{var oD=wu();function _z(){this.__data__=oD?oD(null):{},this.size=0}aD.exports=_z});var uD=v((vde,lD)=>{function Tz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}lD.exports=Tz});var dD=v((wde,cD)=>{var Dz=wu(),Iz="__lodash_hash_undefined__",Oz=Object.prototype,Pz=Oz.hasOwnProperty;function Rz(e){var t=this.__data__;if(Dz){var r=t[e];return r===Iz?void 0:r}return Pz.call(t,e)?t[e]:void 0}cD.exports=Rz});var pD=v((Cde,fD)=>{var Lz=wu(),kz=Object.prototype,$z=kz.hasOwnProperty;function xz(e){var t=this.__data__;return Lz?t[e]!==void 0:$z.call(t,e)}fD.exports=xz});var hD=v((Ede,mD)=>{var Fz=wu(),Mz="__lodash_hash_undefined__";function Uz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Fz&&t===void 0?Mz:t,this}mD.exports=Uz});var yD=v((Ade,gD)=>{var Bz=sD(),qz=uD(),Vz=dD(),Gz=pD(),Wz=hD();function As(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}As.prototype.clear=Bz;As.prototype.delete=qz;As.prototype.get=Vz;As.prototype.has=Gz;As.prototype.set=Wz;gD.exports=As});var wD=v((Sde,vD)=>{var bD=yD(),zz=yu(),jz=lf();function Hz(){this.size=0,this.__data__={hash:new bD,map:new(jz||zz),string:new bD}}vD.exports=Hz});var ED=v((Nde,CD)=>{function Kz(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}CD.exports=Kz});var Cu=v((_de,AD)=>{var Jz=ED();function Yz(e,t){var r=e.__data__;return Jz(t)?r[typeof t=="string"?"string":"hash"]:r.map}AD.exports=Yz});var ND=v((Tde,SD)=>{var Qz=Cu();function Xz(e){var t=Qz(this,e).delete(e);return this.size-=t?1:0,t}SD.exports=Xz});var TD=v((Dde,_D)=>{var Zz=Cu();function ej(e){return Zz(this,e).get(e)}_D.exports=ej});var ID=v((Ide,DD)=>{var tj=Cu();function rj(e){return tj(this,e).has(e)}DD.exports=rj});var PD=v((Ode,OD)=>{var nj=Cu();function ij(e,t){var r=nj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}OD.exports=ij});var uf=v((Pde,RD)=>{var oj=wD(),aj=ND(),sj=TD(),lj=ID(),uj=PD();function Ss(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Ss.prototype.clear=oj;Ss.prototype.delete=aj;Ss.prototype.get=sj;Ss.prototype.has=lj;Ss.prototype.set=uj;RD.exports=Ss});var kD=v((Rde,LD)=>{var cj=yu(),dj=lf(),fj=uf(),pj=200;function mj(e,t){var r=this.__data__;if(r instanceof cj){var n=r.__data__;if(!dj||n.length<pj-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new fj(n)}return r.set(e,t),this.size=r.size,this}LD.exports=mj});var S0=v((Lde,$D)=>{var hj=yu(),gj=NT(),yj=TT(),bj=IT(),vj=PT(),wj=kD();function Ns(e){var t=this.__data__=new hj(e);this.size=t.size}Ns.prototype.clear=gj;Ns.prototype.delete=yj;Ns.prototype.get=bj;Ns.prototype.has=vj;Ns.prototype.set=wj;$D.exports=Ns});var FD=v((kde,xD)=>{var Cj="__lodash_hash_undefined__";function Ej(e){return this.__data__.set(e,Cj),this}xD.exports=Ej});var UD=v(($de,MD)=>{function Aj(e){return this.__data__.has(e)}MD.exports=Aj});var qD=v((xde,BD)=>{var Sj=uf(),Nj=FD(),_j=UD();function cf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Sj;++t<r;)this.add(e[t])}cf.prototype.add=cf.prototype.push=Nj;cf.prototype.has=_j;BD.exports=cf});var GD=v((Fde,VD)=>{function Tj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}VD.exports=Tj});var zD=v((Mde,WD)=>{function Dj(e,t){return e.has(t)}WD.exports=Dj});var N0=v((Ude,jD)=>{var Ij=qD(),Oj=GD(),Pj=zD(),Rj=1,Lj=2;function kj(e,t,r,n,i,o){var a=r&Rj,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&Lj?new Ij: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(!Oj(t,function(b,w){if(!Pj(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}jD.exports=kj});var _0=v((Bde,HD)=>{var $j=Dn(),xj=$j.Uint8Array;HD.exports=xj});var JD=v((qde,KD)=>{function Fj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}KD.exports=Fj});var QD=v((Vde,YD)=>{function Mj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}YD.exports=Mj});var rI=v((Gde,tI)=>{var XD=bu(),ZD=_0(),Uj=Cs(),Bj=N0(),qj=JD(),Vj=QD(),Gj=1,Wj=2,zj="[object Boolean]",jj="[object Date]",Hj="[object Error]",Kj="[object Map]",Jj="[object Number]",Yj="[object RegExp]",Qj="[object Set]",Xj="[object String]",Zj="[object Symbol]",e7="[object ArrayBuffer]",t7="[object DataView]",eI=XD?XD.prototype:void 0,T0=eI?eI.valueOf:void 0;function r7(e,t,r,n,i,o,a){switch(r){case t7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case e7:return!(e.byteLength!=t.byteLength||!o(new ZD(e),new ZD(t)));case zj:case jj:case Jj:return Uj(+e,+t);case Hj:return e.name==t.name&&e.message==t.message;case Yj:case Xj:return e==t+"";case Kj:var s=qj;case Qj:var l=n&Gj;if(s||(s=Vj),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=Wj,a.set(e,t);var c=Bj(s(e),s(t),n,i,o,a);return a.delete(e),c;case Zj:if(T0)return T0.call(e)==T0.call(t)}return!1}tI.exports=r7});var iI=v((Wde,nI)=>{function n7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}nI.exports=n7});var bo=v((zde,oI)=>{var i7=Array.isArray;oI.exports=i7});var sI=v((jde,aI)=>{var o7=iI(),a7=bo();function s7(e,t,r){var n=t(e);return a7(e)?n:o7(n,r(e))}aI.exports=s7});var uI=v((Hde,lI)=>{function l7(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}lI.exports=l7});var dI=v((Kde,cI)=>{function u7(){return[]}cI.exports=u7});var mI=v((Jde,pI)=>{var c7=uI(),d7=dI(),f7=Object.prototype,p7=f7.propertyIsEnumerable,fI=Object.getOwnPropertySymbols,m7=fI?function(e){return e==null?[]:(e=Object(e),c7(fI(e),function(t){return p7.call(e,t)}))}:d7;pI.exports=m7});var gI=v((Yde,hI)=>{function h7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}hI.exports=h7});var vo=v((Qde,yI)=>{function g7(e){return e!=null&&typeof e=="object"}yI.exports=g7});var vI=v((Xde,bI)=>{var y7=sa(),b7=vo(),v7="[object Arguments]";function w7(e){return b7(e)&&y7(e)==v7}bI.exports=w7});var D0=v((Zde,EI)=>{var wI=vI(),C7=vo(),CI=Object.prototype,E7=CI.hasOwnProperty,A7=CI.propertyIsEnumerable,S7=wI((function(){return arguments})())?wI:function(e){return C7(e)&&E7.call(e,"callee")&&!A7.call(e,"callee")};EI.exports=S7});var SI=v((efe,AI)=>{function N7(){return!1}AI.exports=N7});var df=v((Eu,_s)=>{var _7=Dn(),T7=SI(),TI=typeof Eu=="object"&&Eu&&!Eu.nodeType&&Eu,NI=TI&&typeof _s=="object"&&_s&&!_s.nodeType&&_s,D7=NI&&NI.exports===TI,_I=D7?_7.Buffer:void 0,I7=_I?_I.isBuffer:void 0,O7=I7||T7;_s.exports=O7});var ff=v((tfe,DI)=>{var P7=9007199254740991,R7=/^(?:0|[1-9]\d*)$/;function L7(e,t){var r=typeof e;return t=t??P7,!!t&&(r=="number"||r!="symbol"&&R7.test(e))&&e>-1&&e%1==0&&e<t}DI.exports=L7});var I0=v((rfe,II)=>{var k7=9007199254740991;function $7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=k7}II.exports=$7});var PI=v((nfe,OI)=>{var x7=sa(),F7=I0(),M7=vo(),U7="[object Arguments]",B7="[object Array]",q7="[object Boolean]",V7="[object Date]",G7="[object Error]",W7="[object Function]",z7="[object Map]",j7="[object Number]",H7="[object Object]",K7="[object RegExp]",J7="[object Set]",Y7="[object String]",Q7="[object WeakMap]",X7="[object ArrayBuffer]",Z7="[object DataView]",eH="[object Float32Array]",tH="[object Float64Array]",rH="[object Int8Array]",nH="[object Int16Array]",iH="[object Int32Array]",oH="[object Uint8Array]",aH="[object Uint8ClampedArray]",sH="[object Uint16Array]",lH="[object Uint32Array]",$e={};$e[eH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=!0;$e[U7]=$e[B7]=$e[X7]=$e[q7]=$e[Z7]=$e[V7]=$e[G7]=$e[W7]=$e[z7]=$e[j7]=$e[H7]=$e[K7]=$e[J7]=$e[Y7]=$e[Q7]=!1;function uH(e){return M7(e)&&F7(e.length)&&!!$e[x7(e)]}OI.exports=uH});var LI=v((ife,RI)=>{function cH(e){return function(t){return e(t)}}RI.exports=cH});var $I=v((Au,Ts)=>{var dH=C0(),kI=typeof Au=="object"&&Au&&!Au.nodeType&&Au,Su=kI&&typeof Ts=="object"&&Ts&&!Ts.nodeType&&Ts,fH=Su&&Su.exports===kI,O0=fH&&dH.process,pH=(function(){try{var e=Su&&Su.require&&Su.require("util").types;return e||O0&&O0.binding&&O0.binding("util")}catch{}})();Ts.exports=pH});var pf=v((ofe,MI)=>{var mH=PI(),hH=LI(),xI=$I(),FI=xI&&xI.isTypedArray,gH=FI?hH(FI):mH;MI.exports=gH});var P0=v((afe,UI)=>{var yH=gI(),bH=D0(),vH=bo(),wH=df(),CH=ff(),EH=pf(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e,t){var r=vH(e),n=!r&&bH(e),i=!r&&!n&&wH(e),o=!r&&!n&&!i&&EH(e),a=r||n||i||o,s=a?yH(e.length,String):[],l=s.length;for(var u in e)(t||SH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||CH(u,l)))&&s.push(u);return s}UI.exports=NH});var mf=v((sfe,BI)=>{var _H=Object.prototype;function TH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||_H;return e===r}BI.exports=TH});var R0=v((lfe,qI)=>{function DH(e,t){return function(r){return e(t(r))}}qI.exports=DH});var GI=v((ufe,VI)=>{var IH=R0(),OH=IH(Object.keys,Object);VI.exports=OH});var zI=v((cfe,WI)=>{var PH=mf(),RH=GI(),LH=Object.prototype,kH=LH.hasOwnProperty;function $H(e){if(!PH(e))return RH(e);var t=[];for(var r in Object(e))kH.call(e,r)&&r!="constructor"&&t.push(r);return t}WI.exports=$H});var Nu=v((dfe,jI)=>{var xH=sf(),FH=I0();function MH(e){return e!=null&&FH(e.length)&&!xH(e)}jI.exports=MH});var KI=v((ffe,HI)=>{var UH=P0(),BH=zI(),qH=Nu();function VH(e){return qH(e)?UH(e):BH(e)}HI.exports=VH});var YI=v((pfe,JI)=>{var GH=sI(),WH=mI(),zH=KI();function jH(e){return GH(e,zH,WH)}JI.exports=jH});var ZI=v((mfe,XI)=>{var QI=YI(),HH=1,KH=Object.prototype,JH=KH.hasOwnProperty;function YH(e,t,r,n,i,o){var a=r&HH,s=QI(e),l=s.length,u=QI(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:JH.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 E=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(E===void 0?b===w||i(b,w,r,n,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,P=t.constructor;S!=P&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof P=="function"&&P instanceof P)&&(h=!1)}return o.delete(e),o.delete(t),h}XI.exports=YH});var tO=v((hfe,eO)=>{var QH=yo(),XH=Dn(),ZH=QH(XH,"DataView");eO.exports=ZH});var nO=v((gfe,rO)=>{var eK=yo(),tK=Dn(),rK=eK(tK,"Promise");rO.exports=rK});var oO=v((yfe,iO)=>{var nK=yo(),iK=Dn(),oK=nK(iK,"Set");iO.exports=oK});var sO=v((bfe,aO)=>{var aK=yo(),sK=Dn(),lK=aK(sK,"WeakMap");aO.exports=lK});var hO=v((vfe,mO)=>{var L0=tO(),k0=lf(),$0=nO(),x0=oO(),F0=sO(),pO=sa(),Ds=A0(),lO="[object Map]",uK="[object Object]",uO="[object Promise]",cO="[object Set]",dO="[object WeakMap]",fO="[object DataView]",cK=Ds(L0),dK=Ds(k0),fK=Ds($0),pK=Ds(x0),mK=Ds(F0),la=pO;(L0&&la(new L0(new ArrayBuffer(1)))!=fO||k0&&la(new k0)!=lO||$0&&la($0.resolve())!=uO||x0&&la(new x0)!=cO||F0&&la(new F0)!=dO)&&(la=function(e){var t=pO(e),r=t==uK?e.constructor:void 0,n=r?Ds(r):"";if(n)switch(n){case cK:return fO;case dK:return lO;case fK:return uO;case pK:return cO;case mK:return dO}return t});mO.exports=la});var AO=v((wfe,EO)=>{var M0=S0(),hK=N0(),gK=rI(),yK=ZI(),gO=hO(),yO=bo(),bO=df(),bK=pf(),vK=1,vO="[object Arguments]",wO="[object Array]",hf="[object Object]",wK=Object.prototype,CO=wK.hasOwnProperty;function CK(e,t,r,n,i,o){var a=yO(e),s=yO(t),l=a?wO:gO(e),u=s?wO:gO(t);l=l==vO?hf:l,u=u==vO?hf:u;var c=l==hf,d=u==hf,f=l==u;if(f&&bO(e)){if(!bO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new M0),a||bK(e)?hK(e,t,r,n,i,o):gK(e,t,l,r,n,i,o);if(!(r&vK)){var m=c&&CO.call(e,"__wrapped__"),p=d&&CO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new M0),i(h,g,r,n,o)}}return f?(o||(o=new M0),yK(e,t,r,n,i,o)):!1}EO.exports=CK});var TO=v((Cfe,_O)=>{var EK=AO(),SO=vo();function NO(e,t,r,n,i){return e===t?!0:e==null||t==null||!SO(e)&&!SO(t)?e!==e&&t!==t:EK(e,t,r,n,NO,i)}_O.exports=NO});var IO=v((Efe,DO)=>{var AK=TO();function SK(e,t){return AK(e,t)}DO.exports=SK});var U0=v((Afe,OO)=>{var NK=yo(),_K=(function(){try{var e=NK(Object,"defineProperty");return e({},"",{}),e}catch{}})();OO.exports=_K});var gf=v((Sfe,RO)=>{var PO=U0();function TK(e,t,r){t=="__proto__"&&PO?PO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}RO.exports=TK});var B0=v((Nfe,LO)=>{var DK=gf(),IK=Cs();function OK(e,t,r){(r!==void 0&&!IK(e[t],r)||r===void 0&&!(t in e))&&DK(e,t,r)}LO.exports=OK});var $O=v((_fe,kO)=>{function PK(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}}kO.exports=PK});var FO=v((Tfe,xO)=>{var RK=$O(),LK=RK();xO.exports=LK});var VO=v((_u,Is)=>{var kK=Dn(),qO=typeof _u=="object"&&_u&&!_u.nodeType&&_u,MO=qO&&typeof Is=="object"&&Is&&!Is.nodeType&&Is,$K=MO&&MO.exports===qO,UO=$K?kK.Buffer:void 0,BO=UO?UO.allocUnsafe:void 0;function xK(e,t){if(t)return e.slice();var r=e.length,n=BO?BO(r):new e.constructor(r);return e.copy(n),n}Is.exports=xK});var zO=v((Dfe,WO)=>{var GO=_0();function FK(e){var t=new e.constructor(e.byteLength);return new GO(t).set(new GO(e)),t}WO.exports=FK});var HO=v((Ife,jO)=>{var MK=zO();function UK(e,t){var r=t?MK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}jO.exports=UK});var JO=v((Ofe,KO)=>{function BK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}KO.exports=BK});var XO=v((Pfe,QO)=>{var qK=ki(),YO=Object.create,VK=(function(){function e(){}return function(t){if(!qK(t))return{};if(YO)return YO(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();QO.exports=VK});var q0=v((Rfe,ZO)=>{var GK=R0(),WK=GK(Object.getPrototypeOf,Object);ZO.exports=WK});var tP=v((Lfe,eP)=>{var zK=XO(),jK=q0(),HK=mf();function KK(e){return typeof e.constructor=="function"&&!HK(e)?zK(jK(e)):{}}eP.exports=KK});var nP=v((kfe,rP)=>{var JK=Nu(),YK=vo();function QK(e){return YK(e)&&JK(e)}rP.exports=QK});var aP=v(($fe,oP)=>{var XK=sa(),ZK=q0(),eJ=vo(),tJ="[object Object]",rJ=Function.prototype,nJ=Object.prototype,iP=rJ.toString,iJ=nJ.hasOwnProperty,oJ=iP.call(Object);function aJ(e){if(!eJ(e)||XK(e)!=tJ)return!1;var t=ZK(e);if(t===null)return!0;var r=iJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&iP.call(r)==oJ}oP.exports=aJ});var V0=v((xfe,sP)=>{function sJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}sP.exports=sJ});var G0=v((Ffe,lP)=>{var lJ=gf(),uJ=Cs(),cJ=Object.prototype,dJ=cJ.hasOwnProperty;function fJ(e,t,r){var n=e[t];(!(dJ.call(e,t)&&uJ(n,r))||r===void 0&&!(t in e))&&lJ(e,t,r)}lP.exports=fJ});var cP=v((Mfe,uP)=>{var pJ=G0(),mJ=gf();function hJ(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?mJ(r,s,l):pJ(r,s,l)}return r}uP.exports=hJ});var fP=v((Ufe,dP)=>{function gJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}dP.exports=gJ});var mP=v((Bfe,pP)=>{var yJ=ki(),bJ=mf(),vJ=fP(),wJ=Object.prototype,CJ=wJ.hasOwnProperty;function EJ(e){if(!yJ(e))return vJ(e);var t=bJ(e),r=[];for(var n in e)n=="constructor"&&(t||!CJ.call(e,n))||r.push(n);return r}pP.exports=EJ});var W0=v((qfe,hP)=>{var AJ=P0(),SJ=mP(),NJ=Nu();function _J(e){return NJ(e)?AJ(e,!0):SJ(e)}hP.exports=_J});var yP=v((Vfe,gP)=>{var TJ=cP(),DJ=W0();function IJ(e){return TJ(e,DJ(e))}gP.exports=IJ});var AP=v((Gfe,EP)=>{var bP=B0(),OJ=VO(),PJ=HO(),RJ=JO(),LJ=tP(),vP=D0(),wP=bo(),kJ=nP(),$J=df(),xJ=sf(),FJ=ki(),MJ=aP(),UJ=pf(),CP=V0(),BJ=yP();function qJ(e,t,r,n,i,o,a){var s=CP(e,r),l=CP(t,r),u=a.get(l);if(u){bP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=wP(l),m=!f&&$J(l),p=!f&&!m&&UJ(l);c=l,f||m||p?wP(s)?c=s:kJ(s)?c=RJ(s):m?(d=!1,c=OJ(l,!0)):p?(d=!1,c=PJ(l,!0)):c=[]:MJ(l)||vP(l)?(c=s,vP(s)?c=BJ(s):(!FJ(s)||xJ(s))&&(c=LJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),bP(e,r,c)}EP.exports=qJ});var z0=v((Wfe,NP)=>{var VJ=S0(),GJ=B0(),WJ=FO(),zJ=AP(),jJ=ki(),HJ=W0(),KJ=V0();function SP(e,t,r,n,i){e!==t&&WJ(t,function(o,a){if(i||(i=new VJ),jJ(o))zJ(e,t,a,r,SP,n,i);else{var s=n?n(KJ(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),GJ(e,a,s)}},HJ)}NP.exports=SP});var j0=v((zfe,_P)=>{function JJ(e){return e}_P.exports=JJ});var DP=v((jfe,TP)=>{function YJ(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)}TP.exports=YJ});var PP=v((Hfe,OP)=>{var QJ=DP(),IP=Math.max;function XJ(e,t,r){return t=IP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=IP(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),QJ(e,this,s)}}OP.exports=XJ});var LP=v((Kfe,RP)=>{function ZJ(e){return function(){return e}}RP.exports=ZJ});var xP=v((Jfe,$P)=>{var eY=LP(),kP=U0(),tY=j0(),rY=kP?function(e,t){return kP(e,"toString",{configurable:!0,enumerable:!1,value:eY(t),writable:!0})}:tY;$P.exports=rY});var MP=v((Yfe,FP)=>{var nY=800,iY=16,oY=Date.now;function aY(e){var t=0,r=0;return function(){var n=oY(),i=iY-(n-r);if(r=n,i>0){if(++t>=nY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}FP.exports=aY});var BP=v((Qfe,UP)=>{var sY=xP(),lY=MP(),uY=lY(sY);UP.exports=uY});var VP=v((Xfe,qP)=>{var cY=j0(),dY=PP(),fY=BP();function pY(e,t){return fY(dY(e,t,cY),e+"")}qP.exports=pY});var WP=v((Zfe,GP)=>{var mY=Cs(),hY=Nu(),gY=ff(),yY=ki();function bY(e,t,r){if(!yY(r))return!1;var n=typeof t;return(n=="number"?hY(r)&&gY(t,r.length):n=="string"&&t in r)?mY(r[t],e):!1}GP.exports=bY});var H0=v((epe,zP)=>{var vY=VP(),wY=WP();function CY(e){return vY(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&&wY(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})}zP.exports=CY});var HP=v((tpe,jP)=>{var EY=z0(),AY=H0(),SY=AY(function(e,t,r,n){EY(e,t,r,n)});jP.exports=SY});var sn,Tu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(sn||(sn={}))});function JP(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${KP.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 KP,NY,YP=k(()=>{"use strict";KP=Ee(w0()),NY=Ee(v0());});var K0,QP=k(()=>{"use strict";Xd();K0=uu({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var ZP,eR,tR,rR,J0,_Y,yf,XP,Y0=k(()=>{"use strict";ZP=Ee(v0()),eR=Ee(lT()),tR=Ee(w0()),rR=Ee(IO()),J0=Ee(HP());Tu();YP();QP();_Y=60*1e3,yf=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=sn.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"?K0.prodEcsEndpoint:K0.integrationEcsEndpoint}client=new eR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=ZP.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:[tR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:JP(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===sn.NotLoaded&&(this._status=sn.Initialized)}catch(s){this._status=sn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*_Y)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,J0.default)({},t.fallback,n,t.override,XP)};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,rR.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,J0.default)({},this.client.getConfig()?.config,this.clientConfigOverride,XP);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=sn.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})}},XP=(e,t)=>{if(Array.isArray(t))return t}});var iR=v((cpe,nR)=>{"use strict";var TY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};nR.exports=TY});var Q0=v((dpe,aR)=>{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{}}}),oR=function(){return Du};Object.setPrototypeOf(oR,Du);aR.exports=oR});var uR=v((fpe,lR)=>{var Iu=new Proxy(function(){return Iu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Iu},apply:function(){return Iu},construct:function(){return{}}}),sR=function(){return Iu};Object.setPrototypeOf(sR,Iu);lR.exports=sR});var gR=v((ppe,hR)=>{"use strict";var X0=uR(),DY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},IY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},OY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},pR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Z0={};Z0[X0.ForwardRef]=OY;Z0[X0.Memo]=pR;function cR(e){return X0.isMemo(e)?pR:Z0[e.$$typeof]||DY}var PY=Object.defineProperty,RY=Object.getOwnPropertyNames,dR=Object.getOwnPropertySymbols,LY=Object.getOwnPropertyDescriptor,kY=Object.getPrototypeOf,fR=Object.prototype;function mR(e,t,r){if(typeof t!="string"){if(fR){var n=kY(t);n&&n!==fR&&mR(e,n,r)}var i=RY(t);dR&&(i=i.concat(dR(t)));for(var o=cR(e),a=cR(t),s=0;s<i.length;++s){var l=i[s];if(!IY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=LY(t,l);try{PY(e,l,u)}catch{}}}}return e}hR.exports=mR});function bR(e,t,r){let[n,i]=(0,Os.useState)(e.getConfig(t));return(0,Os.useEffect)(()=>{if(!r?.subscribe&&e.status===sn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function vR(e){return function(t,r){return bR(e,t,r)}}function wR(e,t,r,n){let i=o=>{let a=bR(e,t,n),s={...o,...a};return Os.default.createElement(r,{...s})};return(0,yR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function CR(e,t,r,n){return t.reduce((i,o)=>wR(e,o,i,n),r)}function ER(e){return function(t,r,n){return wR(e,t,r,n)}}var yR,Os,ey=k(()=>{"use strict";yR=Ee(gR()),Os=Ee(Q0());Tu();});var SR=v((gpe,AR)=>{var $Y=z0(),xY=H0(),FY=xY(function(e,t,r){$Y(e,t,r)});AR.exports=FY});var bf=v((ype,NR)=>{var MY=sa(),UY=vo(),BY="[object Symbol]";function qY(e){return typeof e=="symbol"||UY(e)&&MY(e)==BY}NR.exports=qY});var TR=v((bpe,_R)=>{var VY=bo(),GY=bf(),WY=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zY=/^\w*$/;function jY(e,t){if(VY(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||GY(e)?!0:zY.test(e)||!WY.test(e)||t!=null&&e in Object(t)}_R.exports=jY});var OR=v((vpe,IR)=>{var DR=uf(),HY="Expected a function";function ty(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(HY);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(ty.Cache||DR),r}ty.Cache=DR;IR.exports=ty});var RR=v((wpe,PR)=>{var KY=OR(),JY=500;function YY(e){var t=KY(e,function(n){return r.size===JY&&r.clear(),n}),r=t.cache;return t}PR.exports=YY});var kR=v((Cpe,LR)=>{var QY=RR(),XY=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ZY=/\\(\\)?/g,eQ=QY(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(XY,function(r,n,i,o){t.push(i?o.replace(ZY,"$1"):n||r)}),t});LR.exports=eQ});var xR=v((Epe,$R)=>{function tQ(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}$R.exports=tQ});var VR=v((Ape,qR)=>{var FR=bu(),rQ=xR(),nQ=bo(),iQ=bf(),oQ=1/0,MR=FR?FR.prototype:void 0,UR=MR?MR.toString:void 0;function BR(e){if(typeof e=="string")return e;if(nQ(e))return rQ(e,BR)+"";if(iQ(e))return UR?UR.call(e):"";var t=e+"";return t=="0"&&1/e==-oQ?"-0":t}qR.exports=BR});var WR=v((Spe,GR)=>{var aQ=VR();function sQ(e){return e==null?"":aQ(e)}GR.exports=sQ});var jR=v((Npe,zR)=>{var lQ=bo(),uQ=TR(),cQ=kR(),dQ=WR();function fQ(e,t){return lQ(e)?e:uQ(e,t)?[e]:cQ(dQ(e))}zR.exports=fQ});var KR=v((_pe,HR)=>{var pQ=bf(),mQ=1/0;function hQ(e){if(typeof e=="string"||pQ(e))return e;var t=e+"";return t=="0"&&1/e==-mQ?"-0":t}HR.exports=hQ});var QR=v((Tpe,YR)=>{var gQ=G0(),yQ=jR(),bQ=ff(),JR=ki(),vQ=KR();function wQ(e,t,r,n){if(!JR(e))return e;t=yQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=vQ(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=JR(c)?c:bQ(t[i+1])?[]:{})}gQ(s,l,u),s=s[l]}return e}YR.exports=wQ});var ZR=v((Dpe,XR)=>{var CQ=QR();function EQ(e,t,r){return e==null?e:CQ(e,t,r)}XR.exports=EQ});function n2(e){let{query:t}=(0,r2.default)(window.location.href,!0);return SQ(e,t),e}function SQ(e,t){let r=AQ+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+i2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,t2.default)(u,c,s)}(0,e2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var e2,t2,r2,i2,AQ,o2=k(()=>{"use strict";e2=Ee(SR()),t2=Ee(ZR()),r2=Ee(s0());i2=".",AQ="ecs"+i2});function wf(e,t,r){let n=n2(new yf(e,t,r));function i(o){(0,vf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:_Q(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>CR(n,o,a,s)}}function _Q(e){let t=vR(e),r=ER(e);return function(i){let o=nT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===sn.ConfigsLoaded,c0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var NQ,vf,ry=k(()=>{"use strict";NQ=Ee(iR()),vf=Ee(Q0());b0();Y0();Tu();ey();o2();d0();});var a2=k(()=>{"use strict";b0();Y0();ry();Tu();ey();rf();f0();});function Cf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Ps.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Ps.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Ps.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Ps,ny=k(()=>{"use strict";Ps=Ee(ra());});var Kpe,Jpe,Ype,s2=k(()=>{"use strict";a2();ny();({featuresClient:Kpe,createFeature:Jpe,useFeaturesClientInitParams:Ype}=wf("PowerApps-Shell-Test",Cf("shell-features")))});var c2=v((Xpe,u2)=>{var Ou=new Proxy(function(){return Ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ou},apply:function(){return Ou},construct:function(){return{}}}),l2=function(){return Ou};Object.setPrototypeOf(l2,Ou);u2.exports=l2});var TQ,DQ,d2=k(()=>{"use strict";au();TQ=Ee(c2()),DQ=Ee(ra());});var f2=k(()=>{"use strict";s2();ny();d2();});var sme,Rs,lme,p2=k(()=>{"use strict";f2();ry();({featuresClient:sme,createFeature:Rs,useFeaturesClientInitParams:lme}=wf("PowerApps-MakerPortal",Cf("powerapps-features")))});var m2,h2,fme,pme,mme,hme,iy=k(()=>{"use strict";rT();p2();({feature:m2}=Rs({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:ws.enableAutoInsertionOfCellInRow}})),{feature:h2}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:ws.enableOneGridEvents}}),{feature:fme}=Rs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:ws.disablePBIComponents}}),{feature:pme}=Rs({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:ws.enableAgentResponse}}),{feature:mme,useFeature:hme}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:ws.enableDelayedLocalizationForCustomControls}})});var b2=v((yme,y2)=>{var Pu=new Proxy(function(){return Pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Pu},apply:function(){return Pu},construct:function(){return{}}}),g2=function(){return Pu};Object.setPrototypeOf(g2,Pu);y2.exports=g2});var Qt,wo=k(()=>{"use strict";pt();ot();Yt();fu();le();Dt();Qt=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(C.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){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(C.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(C.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(C.formControl);if(t&&t.ClassId){let r=at.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&at.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===C.formSection||this.NodeName===C.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(C.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(C.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Ls,oy=k(()=>{"use strict";Yt();le();Dt();Ls=class extends re{constructor(t,r){super(C.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var v2,ks,ay=k(()=>{"use strict";ot();oy();le();Dt();wo();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(v2||(v2={}));ks=class extends Qt{constructor(t,r){super(C.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(C.EventHandlers);return t&&t.length?t[0].getChildren(C.handler):[]}getAllDependencies(){let t=this.getChildren(C.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(C.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(C.formDependencies,this)),r=this.getFirstChild(C.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Ls(r,n.toString()))}}}});var In,Ru=k(()=>{"use strict";pt();Bl();ot();ta();le();Dt();_n();In=class extends re{previewVersion;constructor(t){super(C.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return 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 nr,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(C.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 nr;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()===mt.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 $s,sy=k(()=>{"use strict";Yt();zo();Ru();le();Dt();$s=class extends In{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 an.Chart:return an.Chart;case an.Grid:return an.Grid;default:return an.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=an.Chart:this.chartGridMode=this.enableChartPicker?an.All:an.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(jt.dataset)?n[i].getParameters().get(jt.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 xs,ly=k(()=>{"use strict";Yt();zo();Ru();le();xs=class extends In{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(jt.value)?n[i].getParameters().get(jt.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 w2,uy,_r,Lu=k(()=>{"use strict";w2=Ee(b2());wo();le();ot();pt();ay();Ru();fu();g0();Qg();_n();ta();gs();sy();ly();cy();rs();uy="_",_r=class e extends Qt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(C.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof In?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:!na.dependencyFieldCount.containsKey(this.control.id):!na.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ks(this,iu.onLoad))}get dependencies(){let t=this.getChildren(C.formEvents);for(let r of t){let n=r.getChildren(C.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Hd[i])o=Hd[i].replace(/ /g,uy)+uy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,w2.trackErrorTrace)(sr,{eventName:`${b_}/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===ln.Grid?(l=new $s(this),l.indicationOfSubgrid=!0):o===ln.Lookup?l=new xs(this):l=new In(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=at.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(at.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!at.isUnboundFormControlByIdentifier(d)?o!==ln.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=at.GetRowSpan(l),(at.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||at.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(at.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||at.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||at.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()===C.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(C.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return 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(m0.ONE_COLUMN),n=Number(m0.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(C.formRow)}getParentSection(){return this.getAncestor(C.formSection)}getParentTab(){return this.getAncestor(C.formTab)}getParentForm(){return this.getAncestor(C.form)}isInHeader(){let t=this.getAncestor(C.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(C.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(C.formHeader):this.isInFooter()?this.getAncestor(C.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(y.userspacer);return 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 ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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===io.ApplicationRequired||a===io.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?io.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??io.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===C.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===C.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===uy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Fs,dy=k(()=>{"use strict";Yt();le();Dt();Fs=class extends re{isInternal;constructor(t,r,n,i){super(C.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var ua,fy=k(()=>{"use strict";ot();Lu();le();Dt();ua=class extends re{isRowAddedOnDragOver;constructor(t){super(C.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return 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(C.formSection)}insertPaddingCellAtIndex(t){let r=new _r(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(C.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function IQ(e){switch(e){case ia.Left:return aa.Left;case ia.Right:return aa.Right;case ia.Center:return aa.Center;default:return aa.Left}}function OQ(e){switch(e){case bs.Left:return vs.Left;case bs.Top:return vs.Top;default:return vs.Left}}function C2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var PQ,ri,ku=k(()=>{"use strict";y0();pt();ot();Yt();iy();Lu();le();_n();wo();fy();PQ=115,ri=class e extends Qt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=ze.ONE_COLUMN;break;case 11:t=ze.TWO_COLUMN;break;case 111:t=ze.THREE_COLUMN;break;case 1111:t=ze.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===ze.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 ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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 ua(null);if(this.addGrandChild(C.formRows,r),m2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new _r(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===ze.REFERENCE_PANEL&&(n=ze.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(C.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(C.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(C.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(C.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(C.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(C.formRows);return t.length===0?[]:t[0].getChildren(C.formRow)}get columns(){let t=this.getProperty(y.columnName),r=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 C2(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(C.formColumn)}getParentTab(){return this.getAncestor(C.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){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?PQ: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:IQ(this.fieldLabelAlignment),Position:OQ(this.fieldLabelPosition)},Columns:C2(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===C.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===C.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===C.formFooter||this.NodeName===C.formHeader}}});var Co,Ef=k(()=>{"use strict";le();Dt();ku();Co=class e extends re{constructor(t){super(C.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ri(C.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}initialize(t,r,n,i=ze.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(C.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(C.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(C.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Af,E2=k(()=>{"use strict";pt();le();_n();ku();Af=class extends ri{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 Sf,A2=k(()=>{"use strict";Ef();le();E2();Sf=class extends Co{addAndIntializeNavBarSection(t,r,n,i){let o=new Af(C.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(C.formSections,o,n),o}}});var $i,Nf=k(()=>{"use strict";pt();ot();Yt();Ef();le();Dt();wo();$i=class extends Qt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(C.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(C.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=We.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=We.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=We.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=We.TWO_COLUMN_WIDER_RIGHT;break}t=We.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=We.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=We.THREE_COLUMN_WIDER_MID;break}t=We.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,ho.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,ho.IsUserDefined),this.addProperty(y.locklevel,ho.LockLevel),this.addProperty(y.showlabel,ho.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=ze.ONE_COLUMN,o=!0,a){let s=this.getChildren(C.formColumns)[0],l=[];switch(t){case We.ONE_COLUMN:l.push(100);break;case We.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case We.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case We.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case We.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case We.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Co(s);c.initialize(u,r,n,i),this.addGrandChild(C.formColumns,c)}}initialize(t,r,n,i,o,a=ze.ONE_COLUMN,s=!0,l){this.addChild(new re(C.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(C.formColumns);return t.length!==1?[]:t[0].getChildren(C.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){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(C.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(C.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(C.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===C.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ca,py=k(()=>{"use strict";pt();le();Dt();_n();A2();Nf();ca=class extends $i{constructor(t,r,n){super(t,We.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(C.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(C.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<nf.FIVE_COLUMN;t++){let r=new Sf(this.getChildren(C.formColumns)[0]);r.initializeDefaultProperties(G_.FiveEqColumn),this.addGrandChild(C.formColumns,r)}}}});function LQ(e){switch(e){case mt.Main:return go.Main;case mt.QuickCreate:return go.QuickCreate;case mt.QuickViewForm:return go.Quick;case mt.Dialog:return go.Dialog;default:return go.None}}function kQ(e,t){if(t===mt.Main){if(e)switch(e.toLowerCase()){case"low":return mo.Low;case"highreadonlyvalues":return mo.HighReadOnlyValues;default:return mo.HighWithControls}return mo.Low}}var Tf,RQ,_f,S2=k(()=>{"use strict";Q_();Tf=Ee(ra());y0();ot();Yt();gs();iy();le();zo();Mg();ta();Lu();le();wo();dy();py();Nf();RQ="1920";_f=class e extends Qt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(C.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Gd,this._metadataChangeEvent=new af}get FormLibraries(){let t=this.getFirstChild(C.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof _r).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 _r){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===C.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new Fs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,Tf.trackErrorTrace)(v_,{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))?RQ: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===mt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==mt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===mt.Main||this.formType===mt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(C.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(C.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(C.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(C.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new $i(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new $i(null,We.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(We.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(C.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===ho.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(C.formTabs);return t.length!==1?[]:t[0].getChildren(C.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ca)return t}return null}get NavigationNode(){let t=this.getChildren(C.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(C.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(C.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(C.formFooter).length>0}get displayCondition(){let t=this.getChildren(C.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(C.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(C.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(C.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(C.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof _r))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 _r&&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,_i.EditableGridControl)||h2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,_i.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,_i.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===C.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof ca)){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,Tf.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===mt.Main?{HeaderDensity:kQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:LQ(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 Df,my,N2=k(()=>{"use strict";pt();ot();le();Dt();wo();Df=class extends Qt{constructor(t){super(C.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(C.formEveryOne)&&this.getChildren(C.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new my(this))}},my=class extends re{constructor(t){super(C.formEveryOne,t)}}});var If,_2=k(()=>{"use strict";le();Dt();If=class extends re{constructor(t,r){super(C.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Ms,hy=k(()=>{"use strict";le();ku();Ms=class extends ri{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(C.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var $u,T2=k(()=>{"use strict";le();hy();$u=class extends Ms{_customFooter;constructor(t,r){super(C.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var xu,D2=k(()=>{"use strict";le();hy();xu=class extends Ms{_customHeader;constructor(t,r){super(C.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var Tr,da=k(()=>{"use strict";pt();Yt();le();wo();Tr=class e extends Qt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(C.Titles);return t.length===0?[]:t[0].getChildren(C.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(C.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(C.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Fu,I2=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Fu||(Fu={}))});var Of,O2=k(()=>{"use strict";ot();le();da();I2();Of=class extends Tr{constructor(t){super(C.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return R.IsNullOrUndefined(r)?Fu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Fu.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var xe,$Q,P2,a0e,Us,gy=k(()=>{"use strict";pt();le();da();(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={}));$Q=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),P2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),a0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Us=class extends Tr{constructor(t,r){super(C.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=$Q.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var Bs,yy=k(()=>{"use strict";le();da();Bs=class extends Tr{constructor(t,r){super(C.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(C.formNavBarArea)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Pf,R2=k(()=>{"use strict";ot();le();da();Pf=class extends Tr{RelationshipNameUCIRuntime;constructor(t){super(C.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return 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 Rf,L2=k(()=>{"use strict";le();da();Rf=class extends Tr{constructor(t){super(C.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Lf,k2=k(()=>{"use strict";pt();le();gy();yy();da();Lf=class extends Tr{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(C.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[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=>P2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Bs(C.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Us(C.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(C.formNavBar)}get id(){return new U(Yg,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(C.formNavBarAreas,r),this.addGrandChildAtIndex(C.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var $2={};Hr($2,{ControlType:()=>ln,DeserializationService:()=>wy,DeserializationServiceScope:()=>vy,DeserializedFormElementNode:()=>Dr});var by,Dr,vy,ln,wy,cy=k(()=>{"use strict";by=Ee(ra());pt();ot();Yt();gs();Qg();ta();w_();J_();fu();S2();Lu();Ef();Ru();oy();le();le();N2();Dt();_n();ay();_2();T2();sy();ly();D2();dy();fy();ku();Nf();O2();gy();yy();R2();L2();k2();Dr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},vy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(ln||(ln={}));wy=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,by.trackErrorTrace)(sr,{eventName:vy,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!==mt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=na.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 _f(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===mt.Main&&(this.insertHeaderFooterElementProperties(C.formHeader,d,d.header),this.insertHeaderFooterElementProperties(C.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===C.formHeader?new xu(r,!0):new $u(r,!0);Dr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Dr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Dr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Dr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Dr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new ua(o);for(let s=0;s<i.maxColumns;s++){let l=new _r(a);Dr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Dr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===C.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new Dr(`<${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,by.trackErrorTrace)(sr,{eventName:vy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Dr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===C.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Dr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case C.form:throw new Error("Form node shouldn't be created using this method");case C.formTab:return new $i(r);case C.formColumn:return new Co(r);case C.formHeader:return new xu(r,!1);case C.formFooter:return new $u(r,!1);case C.formSection:return new ri(C.formSection,r);case C.formRow:return new ua(r);case C.formCell:return new _r(r);case C.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=ln.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=ln.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=ln.Lookup)}return o===ln.Grid?new $s(r):o===ln.Lookup?new xs(r):new In(r);case C.formEvent:return new ks(r,q.EmptyString);case C.dependency:return this.populateDependencyTable(t),new Ls(r,q.EmptyString);case C.Handler:let a=[];return new If(a,r);case C.formNavigation:return new Lf(t.nodeName,r);case C.formNavBarArea:return new Us(t.nodeName,r);case C.formNavBarAreas:return new Bs(t.nodeName,r);case C.formNavBar:return new Of(r);case C.formNavBarByRelationshipItem:return new Pf(r);case C.formNavBarItem:return new Rf(r);case C.formDisplayConditions:return new Df(r);case C.library:return new Fs(r,q.EmptyString,q.EmptyString);case C.controlDescription:return new Kd(r);case C.customControl:return this.populateCustomControlConfigurationId(t),new of(r);default:return new Dr(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,Xn.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);at.CustomControlIdMap.upsert(l,o);break}}break}}}}});var x2={};Hr(x2,{SerializationService:()=>Cy,SerializationServiceScope:()=>xQ,SerializedFormElementNode:()=>qs});var xQ,qs,Cy,F2=k(()=>{"use strict";Yt();Dt();_n();py();xQ="SerializationService",qs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Cy=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=qs.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=qs.prototype.enumerateProperties.call(t),i=qs.prototype.enumerateChildren.call(t);if(!(t instanceof ca)){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 Ny=v(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.completeRecordAsStored=Vs.completeLabelsAsStored=void 0;var Ey=uo(),FQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",MQ=new Set(["tab","section","cell"]);function On(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Eo(e,t){return On(e).find(r=>r.tagName===t)}function U2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function Ay(e){let t=Eo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===FQ:!1}function Sy(e,t){var r,n;let i=((r=Eo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Eo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function UQ(e,t){if(Eo(e,"labels"))return;let r=On(e),n=On(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!U2(r,n.slice(1)))return;let o=On(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&Ay(e)&&Sy(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function BQ(e,t){let r=qQ(e.ownerDocument,t),n=On(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function qQ(e,t){let r=e.createElement("labels");for(let n of On(t))r.appendChild(B2(e,n));return r}function B2(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 M2(e,t){let r=Eo(e,"labels");return r?On(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function VQ(e,t,r){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return!1;let n=M2(e,r),i=M2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function GQ(e,t){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return;let r=Eo(e,"labels"),n=Eo(t,"labels");if(!r||!n)return;let i=On(r),o=On(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(MQ.has(e.tagName)){let a=UQ(e,t);a&&(BQ(e,a),n.changed=!0),VQ(e,t,r)&&(n.changed=!0);let s=GQ(e,t),l=Eo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=B2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=On(e),o=On(t);U2(i,o)&&i.forEach((a,s)=>q2(a,o[s],r,n))}function V2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ey.parseXmlRoot)(e,""),i=(0,Ey.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return q2(n,i,r,o),o.changed?(0,Ey.serializeNode)(n):e}Vs.completeLabelsAsStored=V2;function WQ(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=V2(n,i,r);return o===n?e:{...e,formxml:o}}Vs.completeRecordAsStored=WQ});var lL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var zQ=(fu(),Fr(Y_)),jQ=Q(),G2=dt(),V=wd(),HQ=Uh(),Ce=en(),Mi=["web","phone","tablet"],Mu={web:"2",phone:"0",tablet:"1"},K2=new Map([["2","web"],["0","phone"],["1","tablet"]]),KQ=["phone","web","tablet"];function $f(e){let t=new Set(e),r=KQ.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Mi.filter(n=>t.has(n))}}ue.pcfEntryLayout=$f;function lr(e){return Array.isArray(e)?e:[]}function st(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Uu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ty(e){return{n:`<${e}`,a:[],c:[]}}function J2(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function W2(e){let t=lr(e.c);return t.length===1&&J2(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function cn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Y2(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function Dy(e){try{let t=(0,zQ.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?Y2(String(t)):void 0}catch{return}}ue.nativeClassFor=Dy;var Iy=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}]]),Q2=new Set(["TwoOptions","Boolean"]),X2=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),JQ=new Map([...[...X2].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),YQ=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Z2(e){return YQ.test(e)&&e!=="__proto__"}function Oy(e){return e!==void 0&&(e==="Enum"||Iy.has(e)||Q2.has(e)||X2.has(e))}function eL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function Bu(e,t){let r=e!==void 0?Iy.get(e):void 0;if(r&&typeof t!="boolean"){let n=eL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=Bu;function QQ(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&Uu(r,a)?s=Bu(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Ty(s)]})}return i}function tL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Mi.filter(d=>Py(i).has(d)),l=$f(s),u=QQ(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Ty(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=tL;function Py(e){return new Set(Mi.filter(t=>e.availableOn[t]))}function kf(e){var t;let r=lr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||lr(r[0].a).length>0)return;let n=lr(r[0].c);return n.every(i=>st(i)&&!J2(i))?n:void 0}function fa(e){let t=lr(e?.c);if(t.length===0||!t.every(p=>st(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=lr(p.a),g=h.length===2?K2.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=$f(o);if(!cn(a.named,o)||i==="")return;let s=kf(n[0]);if(!s||!n.every(p=>cn(kf(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",Mu[h]]],b=kf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&lr(b[0].a).length===0?W2(b[0]):void 0;if(!u||!cn(lr(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=lr(p.a),g=W2(p),b=h.map(w=>w[0]);if(g===void 0||!Z2(p.n)||Uu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||cn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(cn(b,["static"])||cn(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===Mi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=fa;function rL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===Bu(r,e))}function nL(e){let t=e.formFactors;return t===void 0?[...Mi]:Array.isArray(t)?Mi.filter(r=>t.includes(r)):[]}function _y(e,t){var r,n,i;if(e.name!==t.binding.name||!cn(nL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Mi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>Uu(a,l)&&rL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=_y;function ht(e){return st(e)&&e.customControl!==void 0}ue.hasCustomControl=ht;function Fi(e,t){var r;return t?lr((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 Ry(e,t){let r=Fi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?fa(r[0]):void 0}ue.storedBindingOf=Ry;function Ly(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Ly;function XQ(e){if(!Ly(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!st(n)||!n.fieldName||!xi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Ry(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=XQ;function xi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var un=(e,t)=>({kind:"refused",rule:e,message:t});function ZQ(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!xi(e)}function z2(e,t,r){var n,i;let o=fa(r);if(!o)return un("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 un("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 un("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=st(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!cn(l,Object.keys(s).sort()))return un("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=>!rL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>Bu(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return un("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=nL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Mi],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=>!Oy(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return un("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)&&!ZQ(o.nativeClass)?un("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 eX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>ht(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Fi(e.bag,t)}:void 0}function iL(e,t){let r=new Map,n=tX(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:iX(u),uid:(0,V.controlUniqueId)(c),bound:ht(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;st(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(!st(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 O=m.findIndex(D);return O<0?void 0:m.splice(O,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(O=>O.bound&&O.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let O=D.cell?l(c,D.cell):void 0;return!O||!l(d,D.cell)||!m.includes(O)?!0:(m.splice(m.indexOf(O),1),f.includes(O)&&D.uid!==O.uid&&j2(D.control)&&r.set(D.control,H2(O.uid)),!1)}),b=[],w=(D,O)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!O||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)&&j2(D.control)),P=f.filter(D=>m.includes(D));if(S.length===0||P.length===0&&b.length===0)continue;let L=[...P,...b],I=P.length===1&&S.length===1&&m.length===1?H2(P[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function tX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=st(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||ht(a)||o>1)&&n.add(i)}return n}function j2(e){return ht(e)||e.genPage===void 0&&xi((0,V.effectiveClassId)(e))}function rX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!st(l)||ht(l)||l.genPage!==void 0||!xi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Fi(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 nX="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 H2(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 iX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function qu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Fi(e.bag,o),s=r?iL(e,r).get(t):void 0;if(s!==void 0)return un("pcf-binding-unique-id",s);let l=r?eX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?fa(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return un("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&&cn(c[0],a[0]))return z2(t,i,a[0]);let f=a.length===1?fa(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&_y(i,d)&&_y(i,f)?{kind:"unchanged"}:un("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 un("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=z2(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:un("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=qu;function oL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function oX(e){let t=n=>ht(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,G2.newId)()),n.id||(n.id=(0,G2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=oX;function aX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!ht(o)||!st(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=qu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):oL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=aX;function sX(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(!ht(p)||!st(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Fi(u,h).length>0&&c.set(p,{plan:qu(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=st(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(!ht(g))continue;let b=(0,V.controlUniqueId)(g),w=Fi(t.bag,b),E=Fi(u,b);if(w.length!==1||E.length!==1||!cn(w[0],E[0])||!fa(E[0]))continue;let S=p.get(b);if(S&&!ht(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let P=(o=(i=fa(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=P.replace(/^\{|\}$/g,"").toUpperCase(),lX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=lr(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(!ht(m)||!st(m.customControl))continue;xi(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 jQ.ValidationError("form",e.id,[(0,Ce.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&uX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?Dy(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let E=((l=(s=lr((a=m.bag)===null||a===void 0?void 0:a.a).find(P=>P[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=E.startsWith("{")?E:`{${p}}`;d.node.c.push(tL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=sX;function lX(e,t){st(e.bag)&&(e.bag.a=lr(e.bag.a).filter(r=>r[0]!==t))}function uX(e,t){var r,n;let i=lr(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=kf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Ty(Bu(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=K2.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=$f(e.factors),p=m.defaults.map(g=>{let b=a.find(E=>c(E)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Mu[g]]],w}),h=m.named.map(g=>{let b=s.find(E=>c(E)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Mu[g]]],w});e.description.c=[...p,...h]}function cX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>ht(t.control))}ue.mayCommitPcfState=cX;function dX(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(!ht(a))continue;let s=Ry(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=lr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!xi(a.classId)||a.type!==l||u!==void 0&&!xi(u[1])||!cn(a.customControl,s.binding))&&(xi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!xi(u[1])&&(u[1]=Y2(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=dX;var fX=new Set(["name","parameters","formFactors"]);function pX(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;ht(s)&&hX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&gX(e,t,n),n}ue.pcfBindingIssues=pX;function mX(e,t,r){let n=r.length;if(!st(e))return r.push((0,Ce.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))fX.has(i)||r.push((0,Ce.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ce.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!st(e.parameters))r.push((0,Ce.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,Ce.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"&&Mi.includes(a))&&new Set(i).size===i.length||r.push((0,Ce.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function hX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=mX(t.customControl,l,i);t.fieldName||i.push((0,Ce.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ce.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Ly(e)||i.push((0,Ce.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,Ce.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,Ce.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,Ce.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=qu(e,t,o,a);f.kind==="refused"&&i.push((0,Ce.issue)(l,f.rule,f.message))}function gX(e,t,r){var n;let i=new Map,o=iL(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=st(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),st(l.control)&&!ht(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ce.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!ht(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||ht(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ce.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):cn(Fi(t.bag,u),Fi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ce.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ce.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 rX(e,t))s.has(l)||r.push((0,Ce.issue)(l,"pcf-binding-unique-id",nX))}var yX=new Set(["Form.Card"]),bX="MscrmControls.ModelForm.ModelFormControl";function aL(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=>!Z2(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===bX||n.some(s=>s.defaultType!==void 0&&yX.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"&&!Oy(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 vX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function sL(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?Iy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:eL(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&&Q2.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?JQ.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 wX(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(!ht(d)||!d.fieldName)continue;let f=d.customControl;if(!st(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=qu(e,d,r,!0);if(p.kind==="edit"){oL(p)&&AX(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,Ce.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=aL(h.value,f.name);if(b){l.push((0,Ce.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),E=g.kind==="found"?g.value:void 0,S=E?(a=(0,HQ.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&Dy(E)!==void 0&&vX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&l.push((0,Ce.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,Ce.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=st(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Re=L.get(x);if(!Re){l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let qt=sL(Re,K);qt&&l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${qt}`))}for(let x of L.values())x.required&&!Uu(I,x.name)&&!x.defaultValue&&l.push((0,Ce.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Py(h.value),O=Array.isArray(f.formFactors)?f.formFactors:void 0;(O?O.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ce.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=wX;function CX(e,t){return t===void 0||!Oy(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function EX(e,t,r){var n,i;let o=aL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!Uu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function AX(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,Ce.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=EX(u.value,t.name,e.stored);if(c){l.push((0,Ce.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];CX(d.get(h),g)||l.push((0,Ce.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=sL(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ce.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Py(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ce.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var SL=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.classIdForAttributeType=Or.QUICK_VIEW_CLASS_ID=Or.NOTES_CLASS_ID=Or.SUBGRID_CLASS_ID=Or.formRegistration=Or.FormAdapter=void 0;var Ui=(pt(),Fr(d_)),uL=(ot(),Fr(f_)),SX=(Dt(),Fr(m_)),gt=(le(),Fr(p_)),tt=(ta(),Fr(h_)),NX=(cy(),Fr($2)),_X=(F2(),Fr(x2)),yt=so(),cL=Jr(),Ir=en(),TX=vg(),Ws=dt(),DX=Ny(),Xt=wd(),ni=lL(),Gs=Q(),Uy=se(),ky=lo(),gL=Ho(),IX={[gt.FormType.Main]:"Main",[gt.FormType.QuickCreate]:"QuickCreate",[gt.FormType.QuickViewForm]:"QuickView",[gt.FormType.Card]:"Card"},xf={Main:gt.FormType.Main,QuickCreate:gt.FormType.QuickCreate,QuickView:gt.FormType.QuickViewForm,Card:gt.FormType.Card},OX=new Map(Object.entries(tt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function By(e){var t;return e&&(t=OX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Vu(e){return e.getAllProperties().map(t=>[t.key,t.value])}function pa(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function yL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function qy(e,t){var r,n;let i=yL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>pa(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=pa(a).get("description"))!==null&&n!==void 0?n:""}function PX(e){let t=yL(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 bL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function $y(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Gu(e){return String(e??"").replace(/[{}]/g,"")}function xy(e){return`{${Gu(e)}}`}function Fy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Mf(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,yt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Vu(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,yt.rawFromNode)(u)})}),{modeled:s,bag:{a:Vu(e),c:o,w:{n:a.getNodeName(),a:Vu(a),c:l}}}}function vL(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,yt.rawFromNode)(o)})}),{modeled:n,bag:{a:Vu(e),c:i}}}function dL(e,t){let{modeled:r,bag:n}=Mf(e,"tabs","tab");return{tabs:r.map(i=>RX(i,t)),bag:n}}function RX(e,t){var r,n;let i=pa(e),{modeled:o,bag:a}=Mf(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=>LX(s,t)),bag:a}}function LX(e,t){let r=pa(e),{modeled:n,bag:i}=Mf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>kX(o,t)),bag:i}}function kX(e,t){var r,n,i;let o=pa(e),{modeled:a,bag:s}=Mf(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:bL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>$X(l,t)),bag:s}}function $X(e,t){let{modeled:r,bag:n}=vL(e,"cell",!1);return{cells:r.map(i=>xX(i,t)),bag:n}}function xX(e,t){var r;let n=pa(e),{modeled:i,bag:o}=vL(e,"control",!0),a=qy(e,t),s=n.get("showlabel")==="true",l=i[0]?FX(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:Fy(n.get("colspan"),1),rowspan:Fy(n.get("rowspan"),1),control:l,bag:o}}function FX(e,t,r){var n,i;let o=pa(e),a=Gu((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:By(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:PX(e),bag:{a:Vu(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,yt.rawFromNode)(l)}))}}}function No(e){return e.a.length===0&&e.c.length===0&&!e.w}function wL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ma(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=No(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=wL(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,yt.mergeAttrs)(e.a,o)}var Ao=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),So=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),fL=(e,t,r=1)=>({key:e,matches:n=>Fy(n,r)===t,render:()=>String(t),absentDefault:String(r)});function Vy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function My(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Uy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function MX(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 UX(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 Gy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||No(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:Vy(t,r)},...a]}}if(MX(e.c[n].node,r)===t)return e;let i=UX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function BX(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 qX(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function VX(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function GX(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||No(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:My(t)}]}}if(qX(BX(e.c[r].node),t))return e;let n=My(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Uf(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,yt.spliceChildren)(e.w.c,r)};return(0,yt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,yt.spliceChildren)(e.c,[...i,o])}function WX(e,t){let r=e.tabs.map(n=>zX(n,t));return{n:"form",a:ma(e.bag,[]),c:e.tabs.length===0&&No(e.bag)?[]:Uf(e.bag,"tabs",r,()=>[])}}function CL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Vy(t,r)]:[]}function zX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("expanded",e.expanded),So("visible",e.visible,!0)],n=e.columns.map(o=>jX(o,t)),i=Gy(e.bag,e.label,t);return{n:"tab",a:ma(i,r),c:Uf(i,"columns",n,()=>CL(i,e.label,t))}}function jX(e,t){let r=e.width!==void 0?[Ao("width",e.width)]:[],n=e.sections.map(i=>HX(i,t));return{n:"column",a:ma(e.bag,r),c:Uf(e.bag,"sections",n,()=>[])}}function HX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("showlabel",e.showLabel),So("visible",e.visible,!0),{key:"columns",matches:o=>bL(o)===e.columns,render:()=>$y(e.columns),absentDefault:$y(1)}],n=e.rows.map(o=>KX(o,t)),i=Gy(e.bag,e.label,t);return{n:"section",a:ma(i,r),c:Uf(i,"rows",n,()=>CL(i,e.label,t))}}function KX(e,t){let r=e.cells.map(n=>JX(n,t));return{n:"row",a:ma(e.bag,[]),c:No(e.bag)?r:(0,yt.assembleChildren)(e.bag,r)}}function JX(e,t){let r=e.control?e.control.showLabel:wL(e.bag,"showlabel")==="true",n=[Ao("id",e.id),So("showlabel",r),So("visible",e.visible,!0),fL("colspan",e.colspan),fL("rowspan",e.rowspan)],i=e.control?[YX(e.control)]:[],o;if(No(e.bag))o=[...e.control&&e.control.label?[Vy(e.control.label,t)]:[],...i];else{let a=e.control?Gy(e.bag,e.control.label,t):e.bag;o=(0,yt.assembleChildren)(a,i)}return{n:"cell",a:ma(e.bag,n),c:o}}function YX(e){let t=[Ao("id",e.id),{key:"classid",matches:i=>Gu(i)===e.classId,render:()=>xy(e.classId||String(tt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Ao("datafieldname",e.fieldName)),t.push(So("disabled",e.isReadOnly)),t.push(So("isrequired",e.isRequired));let r=e.fieldName===null?VX(e.bag,"datafieldname"):e.bag,n;return No(r)?n=Object.keys(e.parameters).length>0?[My(e.parameters)]:[]:n=(0,yt.assembleChildren)(GX(r,e.parameters),[]),{n:"control",a:ma(r,t),c:n}}var QX={make:(e,t)=>new SX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function pL(e,t,r,n){(0,ky.installDomShim)();let i=ZX(e,r);(0,Xt.reconcileEmbedDescriptions)(i,n),(0,ni.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,yt.rebuildRaw)(WX(i,t),QX,null);return new _X.SerializationService(t).serializeFormXmlNode(o)}function XX(e){return JSON.parse(JSON.stringify(e))}function ZX(e,t){let r=XX(e);r.bag||(r.bag=(0,yt.emptyBag)()),r.tabs||(r.tabs=[]),sZ(r.bag),t&&eZ(r,t);for(let n of r.tabs)tZ(n);return r}function eZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Wy(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=AL(s.attributeType)))})}function mL(e){let t=[];return Wy(e,r=>t.push(r)),t}function Wy(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 tZ(e){e.id||(e.id=Ui.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)rZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function rZ(e){e.sections||(e.sections=[]);for(let t of e.sections)nZ(t);e.bag||(e.bag=(0,yt.emptyBag)()),e.width===void 0&&No(e.bag)&&(e.width="100%")}function nZ(e){e.id||(e.id=Ui.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)iZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function iZ(e){e.cells||(e.cells=[]);for(let t of e.cells)oZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function oZ(e){(0,Xt.hasGenPage)(e.control)&&(0,Xt.applyEmbedCellDefaults)(e),e.id||(e.id=Ui.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&&aZ(e.control),e.bag||(e.bag=(0,yt.emptyBag)())}function aZ(e){var t;(0,Xt.hasGenPage)(e)&&(0,Xt.applyEmbedControlDefaults)(e),e.id||(e.id=Ui.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(tt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":By(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,Uy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,yt.emptyBag)())}function sZ(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"&&!hL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",xy(Ui.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!hL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",xy(Ui.Guid.NewGuid())])}}var Ff=class{constructor(t=gL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=dL(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=IX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,Xt.projectGenPageEmbeds)(l),(0,ni.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:pL(t,this.lcid),formid:t.id||(0,Ws.newId)(),objecttypecode:t.entityLogicalName,type:xf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ws.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,ky.installDomShim)();let f=uL.ScriptUtilities.ParseXml(c),m=lZ(f),p=this.deserializeDocument(d,f);return uZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,Xt.genPageEmbedIssues)(t);if(i.length>0)throw new Gs.ValidationError("form",t.id,i);let o=(0,ni.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Gs.ValidationError("form",t.id,o);let a=(0,ni.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Gs.attachCause)(new Gs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Gs.ValidationError("form",t.id,a.issues);return{formxml:pL(t,this.lcid,n,r),name:t.name,type:xf[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 Wy(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,ni.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,Xt.genPageEmbedIssues)(t),...(0,ni.pcfBindingIssues)(t)];if(p.length>0)throw new Gs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:vZ(this.lcid),g=h!==void 0?h:t.tabs.map(E=>cZ(E,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ws.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:xf[(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:gt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(gt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let E=mL(t);mL(w).forEach((S,P)=>{E[P]&&E[P].label===void 0&&delete S.label,E[P]&&E[P].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(E[P].genPage))),E[P]&&E[P].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(E[P].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,Ws.assignMissingIds)(t)}completeAsStored(t,r){return(0,DX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ni.mintPcfIdentity)((0,Xt.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,Xt.mayCommitEmbedState)(t)||(0,ni.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ws.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:xf[(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:gt.FormPresentation.AirForm,formactivationstate:gt.FormActivationState.Active}),{bag:d}=dL(c,this.lcid),f=(0,ni.commitPcfState)((0,Xt.commitEmbedState)(t,(l=(0,Xt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),By);return{artifact:f,baseline:f}}validate(t){return DZ(t)}deserialize(t){return(0,ky.installDomShim)(),this.deserializeDocument(t,uL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new NX.DeserializationService(this.lcid).deSerializeFormXml(r,new Ui.Guid(t.formid),t.objecttypecode,gt.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===gt.FormActivationState.InActive?"Inactive":"Active"}};Or.FormAdapter=Ff;var EL=["header","footer","DisplayConditions"];function lZ(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&&EL.includes(i.nodeName)&&n.add(i.nodeName);return n}function uZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=EL.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 Pn(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function zy(e,t){return e?`<labels><label description="${Pn(e)}" languagecode="${t}" /></labels>`:""}function jy(e){return e&&e.length>0?Gu(e):(0,Ws.newId)()}function cZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[bZ()]).map(l=>dZ(l,t)).join("");return`<tab id="{${Pn(jy(e.id))}}" name="${Pn((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}">${zy(e.label,t)}<columns>${s}</columns></tab>`}function dZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>fZ(o,t)).join("");return`<column width="${Pn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function fZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>pZ(l,t)).join("");return`<section id="{${Pn(jy(e.id))}}" name="${Pn((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="${$y((a=e.columns)!==null&&a!==void 0?a:1)}">${zy(e.label,t)}<rows>${s}</rows></section>`}function pZ(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>mZ(n,t)).join("")}</row>`}function mZ(e,t){var r,n,i,o,a;let s=hZ(e),l=s.control,u=l?zy((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?gZ(l):"";return`<cell id="{${Pn(jy(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 hZ(e){if(!(0,Xt.hasGenPage)(e.control))return e;let t={...e.control};(0,Xt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,Xt.applyEmbedCellDefaults)(r),r}function gZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Pn(e.fieldName)}"`:"",o=yZ(e.parameters),a=e.classId?Gu(e.classId):String(tt.ControlClassId.TextboxControl);return`<control id="${Pn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Pn(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 yZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Uy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Pn(e[n])}</${n}>`).join("")}</parameters>`)}function bZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function vZ(e){return`<tab id="{${Ui.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Ui.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 wZ(e=gL.DEFAULT_LCID){return{adapter:new Ff(e),api:TX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,cL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,cL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Or.formRegistration=wZ;var CZ=new Set(["id","name","label","expanded","visible","columns","bag"]),EZ=new Set(["id","width","sections","bag"]),AZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),SZ=new Set(["id","cells","bag"]),NZ=new Set(["id","visible","colspan","rowspan","control","bag"]),_Z=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),TZ={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 DZ(e){let t=[];return(0,Ir.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Ir.rejectUnknownKeys)(n,CZ,o,"tab",t),(0,Ir.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Ir.rejectUnknownKeys)(s,EZ,u,"column",t),(0,Ir.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Ir.rejectUnknownKeys)(d,AZ,m,"section",t),(0,Ir.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Ir.rejectUnknownKeys)(h,SZ,b,"row",t),(0,Ir.childObjects)(h,"cells",b,"cell",t).forEach(({node:E,index:S})=>{let P=`${b}/cells/${S}`;(0,Ir.rejectUnknownKeys)(E,NZ,P,"cell",t,TZ);let L=E.control;L!=null&&!(0,Ir.isJsonObject)(L)?t.push((0,Ir.issue)(`${P}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Ir.isJsonObject)(L)&&(0,Ir.rejectUnknownKeys)(L,_Z,`${P}/control`,"control",t)})})})})}),t.push(...(0,Xt.genPageEmbedIssues)(e)),t.push(...(0,ni.pcfBindingIssues)(e)),t}Or.SUBGRID_CLASS_ID=tt.ControlClassId.SubgridControl;Or.NOTES_CLASS_ID=tt.ControlClassId.TimelineControl;Or.QUICK_VIEW_CLASS_ID=tt.ControlClassId.QuickViewControl;var IZ={Lookup:String(tt.ControlClassId.LookupControl),Customer:String(tt.ControlClassId.LookupControl),Owner:String(tt.ControlClassId.LookupControl),PartyList:String(tt.ControlClassId.PartyListControl),Boolean:String(tt.ControlClassId.BooleanControl),DateTime:String(tt.ControlClassId.DateTimeControl),Decimal:String(tt.ControlClassId.DecimalControl),Double:String(tt.ControlClassId.FloatingNumberControl),Money:String(tt.ControlClassId.CurrencyControl),Integer:String(tt.ControlClassId.IntegerControl),BigInt:String(tt.ControlClassId.IntegerControl),Memo:String(tt.ControlClassId.TextAreaControl),String:String(tt.ControlClassId.TextboxControl)},OZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function AL(e){return e==="Picklist"||e==="State"||e==="Status"?OZ:e&&IZ[e]||String(tt.ControlClassId.TextboxControl)}Or.classIdForAttributeType=AL;function hL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Hy=v(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.viewApi=zs.findDefaultViews=void 0;var DL=Lt(),ur=ye(),Rn=se(),PZ=es(),NL="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",RZ="savedqueryid,name,returnedtypecode,querytype,isdefault",LZ=60*1e3;function Bf(e){return(e.localName||e.nodeName).toLowerCase()}function Wu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function kZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new PZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Bf(n)==="fetch"?n:void 0}function $Z(e){for(let t=e.parentNode;t;t=t.parentNode)if(Bf(t)==="link-entity")return!0;return!1}function _L(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=kZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Bf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Bf(u)==="link-entity").every(u=>{var c;return((c=Wu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!$Z(l)&&Wu(l,"entityname")===void 0&&((n=Wu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Wu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Wu(l,"value")===String(t)}function xZ(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 FZ(e){var t,r;let n=e.filter(a=>_L(a,0)),i=e.filter(a=>_L(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:"")))<=LZ&&xZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function MZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Rn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Rn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,DL.collectPages)(e,a,`findDefaultViews('${t}')`),l=FZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}zs.findDefaultViews=MZ;async function UZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Rn.odataPathLiteral)(t)}')${(0,Rn.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 TL(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await UZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}zs.viewApi={async get(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]);return{raw:(0,ur.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]),i=(0,ur.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Rn.odataQuery)([["$select",RZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Rn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,DL.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,ur.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await TL(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,ur.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,ur.ensureSuccess)(await(0,ur.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,ur.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,ur.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Rn.normalizeGuid)(t,"id"),a=(0,ur.echoWrite)("savedqueryid",{"If-Match":(0,ur.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await TL(e,i.layoutxml,i.returnedtypecode),u=(0,ur.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,ur.readEtag)(u)}},delete(e,t){return(0,ur.deleteRecord)(e,"savedqueries",t)}}});var WL=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.viewRegistration=js.ViewAdapter=void 0;var $L=Q(),Wr=en(),Ky=so(),ha=uo(),IL=Jr(),BZ=Hy(),Jy=lo(),qZ=dt(),xL=100,Vf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Jy.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,ha.parseXmlRoot)(c,"<fetch/>"),m=(0,ha.parseXmlRoot)(d,"<grid/>"),p=ML(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:GZ(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:FL(m,f),filters:BL(f),sort:UL(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,ha.projectElementBag)(f):void 0,layoutBag:d?(0,ha.projectElementBag)(m):void 0}}fromArtifact(t){(0,Jy.installDomShim)();let{fetchxml:r,layoutxml:n}=OL(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,Jy.installDomShim)();let{fetchxml:s,layoutxml:l}=OL(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,qZ.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,Wr.childObjects)(n,"columns","","column",r),(0,Wr.childObjects)(n,"sort","","sort",r),(0,Wr.childObjects)(n,"linkEntities","","linkEntity",r),VZ(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Wr.isJsonObject)(i)?Yy(i,"/filters",r):r.push((0,Wr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};js.ViewAdapter=Vf;function VZ(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Wr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,Wr.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,Wr.isJsonObject)(i)?Yy(i,`/linkEntities/${n}/filters`,t):t.push((0,Wr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Yy(e,t,r){(0,Wr.childObjects)(e,"conditions",t,"condition",r),(0,Wr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Yy(i,`${t}/groups/${o}`,r))}function GZ(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function FL(e,t){var r;let n=Gf(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)?xL: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 Gf(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 ML(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Ft(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=Ft(n,"filter").find(c=>!Wf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Qy(u)}:{}})}return r}function UL(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 BL(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Ft(t,"filter").filter(i=>!Wf(i)).map(Qy);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Wf(e){if(e.getAttribute("isquickfindfields")==="1"||qL(e))return!0;if(Ft(e,"filter").length>0)return!1;let t=Ft(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Ft(r,"value").length>0||zZ(r))}function qL(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"?qL(n):n.tagName!=="condition"))return!0}return!1}var WZ=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function zZ(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&&!WZ.has(i))return!0}return!1}function Qy(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(Qy(l))}return{type:n,conditions:i,groups:o}}function Ft(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 Xy=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function jZ(e,t){let r=Gf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Xy(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function HZ(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(Xy(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new $L.ValidationError("view",e.id,a.map(s=>(0,Wr.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 OL(e){var t,r;let n=KZ(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(!PL(e.fetchBag)||!PL(e.layoutBag))return{fetchxml:see({...e,columns:n,sort:i,filters:o}),layoutxml:lee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=RL(e.fetchBag,"fetch",a),l=RL(e.layoutBag,"grid",a),u=FL(l,s),c=!qf(n,u),d=!qf(i,UL(s)),f=!qf(o,BL(s)),m=e.linkEntities,p=m!==void 0&&!qf(m,ML(s)),h=p?jZ(s,u):void 0;return p&&iee(a,s,m),p&&(aee(e,s,n,h),HZ(e,s,n,h)),c?(LL(a,s,n,u),ZZ(a,l,n)):p&&LL(a,s,n,u),d&&ree(a,s,i),f&&nee(a,s,o),{fetchxml:(0,ha.serializeNode)(s),layoutxml:(0,ha.serializeNode)(l)}}function KZ(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:xL,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function PL(e){return!!e&&(e.c.length>0||e.a.length>0)}function RL(e,t,r){let n={n:t,a:(0,Ky.mergeAttrs)(e.a,[]),c:(0,Ky.spliceChildren)(e.c,[])};return(0,Ky.rebuildRaw)(n,(0,ha.domEngine)(r),null)}function LL(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=Gf(t);for(let p of n)u.has(l(p))||(YZ(s,p),p.relatedEntity&&c.has(p.name)&&JZ((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Gf(t),m=new Set(Ft(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||!GL(s,p.relatedEntity)))continue;let g=QZ(e,s,p.relatedEntity),b=e.createElement("attribute");VL(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),XZ(s,h),m.add(p.name)}}function VL(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 JZ(e,t){if(e){for(let r of Ft(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function YZ(e,t){if(t.relatedEntity){for(let r of Ft(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Ft(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Ft(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function GL(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Ft(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 QZ(e,t,r){let n=GL(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function XZ(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 ZZ(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=eee(n);if(tee(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 eee(e){return Ft(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function tee(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 ree(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 Ft(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 nee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Ft(n,"filter"))Wf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(zu(e,r))}}function qf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function iee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Ft(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,P)=>P!==g&&!s[P]&&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){kL(e,g,p);return}let b=e.createElement("link-entity");kL(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var oee=new Set(["inner","outer"]);function aee(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(Xy(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 $L.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,Wr.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 kL(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):oee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Ft(t,"filter").find(o=>!Wf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?zu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function see(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(zu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){VL(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(zu(r,e.filters)),new XMLSerializer().serializeToString(r)}function zu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(zu(e,n));return r}function lee(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 uee(){return{adapter:new Vf,api:BZ.viewApi,publish:(e,t,r)=>(0,IL.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,IL.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}js.viewRegistration=uee});function zf(e,t){return e==="SetFieldValue"&&t!==void 0&&cee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var cee,Zy=k(()=>{"use strict";cee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function zL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function eb(e){return e==="AllForms"||zL(e)?1:2}function tb(e){return zL(e)?e:null}function jL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Hs.WorkflowCategory.BusinessRule,type:Hs.WorkflowTypeCode.Definition,mode:1,scope:Hs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:eb(e.scope),processtriggerformid:tb(e.scope)}}var Hs,HL=k(()=>{"use strict";Hs=Ee(Yi());});function KL(e,t=0){return(Mt[e[t+0]]+Mt[e[t+1]]+Mt[e[t+2]]+Mt[e[t+3]]+"-"+Mt[e[t+4]]+Mt[e[t+5]]+"-"+Mt[e[t+6]]+Mt[e[t+7]]+"-"+Mt[e[t+8]]+Mt[e[t+9]]+"-"+Mt[e[t+10]]+Mt[e[t+11]]+Mt[e[t+12]]+Mt[e[t+13]]+Mt[e[t+14]]+Mt[e[t+15]]).toLowerCase()}var Mt,JL=k(()=>{Mt=[];for(let e=0;e<256;++e)Mt.push((e+256).toString(16).slice(1))});function rb(){return jf>Hf.length-16&&((0,YL.randomFillSync)(Hf),jf=0),Hf.slice(jf,jf+=16)}var YL,Hf,jf,QL=k(()=>{YL=require("crypto"),Hf=new Uint8Array(256),jf=Hf.length});var XL,nb,ZL=k(()=>{XL=require("crypto"),nb={randomUUID:XL.randomUUID}});function dee(e,t,r){if(nb.randomUUID&&!t&&!e)return nb.randomUUID();e=e||{};let n=e.random??e.rng?.()??rb();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 KL(n)}var cr,ek=k(()=>{ZL();QL();JL();cr=dee});var ib=k(()=>{ek()});var tk=k(()=>{"use strict";});function rk(e){return e!=null&&fee.has(e)}function Kf(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 fee,ob=k(()=>{"use strict";fee=new Set(["Picklist","State","Status"])});var Jf=v(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.WorkflowConditionOperator=dn.WorkflowAttributeType=dn.SystemStep=dn.FieldRequiredLevelTypes=dn.AttributeDateTimeBehavior=void 0;dn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};dn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};dn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};dn.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"};dn.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 Yf(e){return e!=null&&ik.includes(e)}function ab(e){return e===oe.WorkflowAttributeType.Integer}function sb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:pee.includes(t)?ik.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 ok(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=ju[e.operator]??oe.WorkflowConditionOperator.Equal;return sb(t,r)}function ak(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||!nk.test(o)||!nk.test(a)||o.length>1&&o.startsWith("0")||o.length>mee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,ju,ik,pee,nk,mee,lb=k(()=>{"use strict";oe=Ee(Jf());ju={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},ik=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],pee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];nk=/^\d*$/,mee=28});var sk=k(()=>{"use strict";});function Ln(e){return!hee.has(e)}function ub(e){return e==="Equals"||e==="DoesNotEqual"}function Qf(e){return uk.has(e)?gee:Cee.has(e)?yee:ck.has(e)?bee:Aee.has(e)?wee:vee}function dk(e){return Qf(e)[0]}function fk(e,t){return Qf(t).includes(e)}function lk(e){return uk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":ck.has(e)?"date":Eee.has(e)?"boolean":"other"}function Xf(e,t){let r=lk(e),n=lk(t);return r==="other"||n==="other"?e===t:r===n}var hee,gee,yee,bee,vee,wee,uk,Cee,ck,Eee,Aee,Zf=k(()=>{"use strict";sk();hee=new Set(["ContainsData","DoesNotContainData"]);gee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],yee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],bee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],vee=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],wee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],uk=new Set(["String","Memo","EntityName"]),Cee=new Set(["Integer","BigInt","Money","Decimal","Double"]),ck=new Set(["DateTime"]),Eee=new Set(["Boolean"]),Aee=new Set(["Lookup","Owner","Customer"])});function gk(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 Ak(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function _ee(e){return{__class:Ek,parameterName:"primaryEntity",entityName:e}}function pk(e){return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:yk,parameters:[e]}}function mk(e,t,r=Fe.WorkflowAttributeType.String){return{__class:vk,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:_ee(t),attributeName:e}}function Tee(e,t=Fe.WorkflowAttributeType.String){return{__class:wk,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function Dee(e){return{__class:Ck,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function Sk(e,t){let r=See[e.operator],n=pk(mk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=Dee(e.right.value??"0"):e.right.kind==="field"?i=mk(e.right.field??"",t,e.right.workflowType):i=Tee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=pk(i);return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:bk,parameters:[r,n,o]}}function Nk(e){return typeof e=="object"&&e.__class===db}function Iee(e){return typeof e=="object"&&e.__class===Ck}function ep(e){return Nk(e)&&e.method===yk&&e.parameters.length>0?ep(e.parameters[0]):e}function hk(e){if(typeof e!="object"||e.__class!==vk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Ek)return null;let r=e.attributeName;return r?{field:r,workflowType:Ak(e.type)}:null}function _k(e){if(!e)return null;let t=ep(e);if(!Nk(t)||t.method!==bk||t.parameters.length!==3)return null;let r=t.parameters[0],n=Nee[String(r)];if(!n)return null;let i=hk(ep(t.parameters[1]));if(!i)return null;let o=ep(t.parameters[2]);if(Iee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=hk(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===wk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:Ak(o.type)}}}return null}function pb(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=fb&&r<=Ks}function ga(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&&!pb(t)?"invalidDayCount":null}function Js(e){return ga(e)===null}var Fe,yk,bk,cb,vk,wk,db,Ck,Ek,See,Nee,fb,Ks,Hu=k(()=>{"use strict";Fe=Ee(Jf());Zf();yk="0",bk="3",cb="0",vk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",wk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",db="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Ck="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Ek="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";See={"+":0,"-":1,"*":2,"/":3},Nee={0:"+",1:"-",2:"*",3:"/"};fb=0,Ks=2147483647});function Pee(e){return e.startsWith("__")&&!Oee.has(e)}function Ree(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Pee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function Bk(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function ba(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function tp(e){return Bk(e)||ba(e)}function Lee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ku(){return{list:[]}}function mb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:cr(),languageCode:r,description:t}]}}function gb(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function op(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:gb(t),attributeName:e}}function ya(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function xee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?Gk:Vk:qk}function Wk(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function Fee(e,t){let r=Wk(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${Dk}_${Tk}`,entityName:Tk,relatedAttributeName:Dk},attributeName:$ee}:op(kee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:vb,parameters:[xee(e),n]}}function zk(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==vb)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===Vk?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===Gk?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===qk?{bpfField:"ProcessName"}:null}function rp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===vb){let r=(t.parameters??[])[0];if(typeof r=="string"&&Mee.has(r.replace(/^"+|"+$/g,"")))return!0}return ba(e)?rp(e.operand):Bk(e)?rp(e.left)||(e.right??[]).some(rp):!1}function jk(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 Uee(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 Ik(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return jk(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 Bee(e){let t=bb[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(ba(e))return r&&Ok(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:Ok(e.left,r,n[0])}function Ok(e,t,r){return zk(e)||jk(e)?t||Ik(r):!1}function yb(e){if(!e||!tp(e))return!1;let t=e.conditionOperatoroperator;if(!ba(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&yb(e.left)&&r.every(yb)}return Bee(e)}function Pk(e){return!e||Uee(e)?!1:rp(e)||!yb(e)}function Hk(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??z.WorkflowAttributeType.Lookup,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:ya(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Vee(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Gee(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Vee(t)}function Wee(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function jee(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function ete(e){let t=Zee.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=Xee.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Qee.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function tte(e){let t=ete(e.trim());return t!==void 0&&Kk(t)?t:e}function Kk(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(!Hee.test(i)||o.length>0&&!Kee.test(o)&&!Jee.test(o)&&!Yee.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 rte(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||zee.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=jee(e);return n==null?r:{value:n,type:t}}return qee.includes(t)?Kf(e)?{value:e.trim(),type:t}:r:Yf(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&Kk(e)?{value:e.trim(),type:t}:r}function Rk(e){return e==="ContainsData"||e==="DoesNotContainData"}function Lk(e){return nte.has(e)}function kk(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function $k(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=ju[e.operator]??z.WorkflowConditionOperator.Equal,i=Gee(e,r),o=sb(r,n);if(e.source==="BusinessProcess"){let l=Fee(e,t);if(Rk(e.operator))return kk(l,n);let u=Wk(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[ya(e.value??"",u)]}}let a=op(e.field,t,r,i);if(Rk(e.operator))return kk(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=Lk(o)&&Lk(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[op(e.valueField,t,l,Wee(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[Hk(e.lookupValue)]}else if(e.valueType==="Clear")s=[ya(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[ip(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=rte(e.value??"",o);s=[ya(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function ite(){return ya(!0,z.WorkflowAttributeType.Boolean)}function ote(e,t,r){if(e.length===0)return null;let n=$k(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[$k(e[i],r)]}}return n}function np(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:tte(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=_k(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function ate(e){let t=bb[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=ba(e)?e.operand:e.left,i=ba(e)?[]:e.right??[],o=zk(n);if(o){let g=i[0];return{id:cr(),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"}:np(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:cr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function xk(e){if(!e||!tp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(ba(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...ate(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";tp(o.left)&&r(o.left,a),(o.right??[]).filter(tp).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 ip(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return op(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return Sk(i,n);if(o!=null)return o}return e==="Lookup"&&a?Hk(a):e==="Clear"?ya(null,s??z.WorkflowAttributeType.String):ya(t??"",z.WorkflowAttributeType.String)}function hb(e,t){return{propertyName:e,propertyValueExpr:t}}function Ys(e){return`Step_${e.value++}`}function fn(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 Fk(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):fn(t,r)}function ste(e){return e===Uk.StateCode.Activated?"Active":"Draft"}function lte(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 ute(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function Jk(e,t=1033){return new Qs({languageCode:t}).serialize(e)}function Yk(e){return new Qs().deserialize(e)}var Uk,z,Oee,bb,vb,qk,Vk,Gk,kee,$ee,Tk,Dk,Mee,qee,zee,Hee,Kee,Jee,Yee,Qee,Xee,Zee,nte,wb,Qs,Cb=k(()=>{"use strict";ib();Uk=Ee(Yi());tk();ob();lb();Hu();z=Ee(Jf());Oee=new Set(["__class"]);bb={};for(let e of Object.keys(ju))bb[ju[e]]=e;vb="23",qk="BpfProcess",Vk="ActiveStageCategory",Gk="SelectedStageCategory",kee="processid",$ee="stagecategory",Tk="processstage",Dk="stageid";Mee=new Set(["ActiveStage","SelectedStage","Stage"]);qee=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];zee=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];Hee=/^\d{4}-\d{2}-\d{2}$/,Kee=/^\d{2}:\d{2}$/,Jee=/^\d{2}:\d{2}:\d{2}$/,Yee=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Qee=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Xee=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Zee=/^(\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$/;nte=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);wb={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};Qs=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>wb[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??cr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ku(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ys(this.stepCounter),stepLabels:{list:[]},specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:gb(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=mb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:Fk(n?.id,"ActionStep",this.idCounter),name:n?.name??Ys(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??cr(),uniqueName:n?.uniqueName??`id_${cr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=gb(this.entityName),n=t.stepName??Ys(this.stepCounter),i=t.stepLabels??Ku(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:fn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:fn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:fn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:fn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode);return{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:fn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??Ys(this.stepCounter),n=fn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??ote(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ys(this.stepCounter):Ys(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?Fk(o.branchId,"ConditionBranchStep",this.idCounter):fn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:Ku(),conditionExpression:s??(a?ite():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Ku(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ku(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??cr():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:Ree(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:ute(r,i?.formId),status:ste(t.statecode),rootCondition:n,wfomRoot:i,...lte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Lee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=xk(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)??cr(),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,...Pk(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=xk(n.conditionExpression);return i.length===0&&!Pk(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||cr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...np(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=np(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=np(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==z.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var Qk=k(()=>{"use strict";});function mte(e){return typeof e=="object"&&e!==null?e:null}function Xs(e){let t=mte(e);if(!t)return!1;if(t.__class===fte){let r=t;return String(r.method)===pte?!0:Array.isArray(r.parameters)&&r.parameters.some(Xs)}if(t.__class===dte)return Xs(t.operand);if(t.__class===cte){let r=t;return Xs(r.left)||Array.isArray(r.right)&&r.right.some(Xs)}return!1}var cte,dte,fte,pte,Xk=k(()=>{"use strict";Qk();cte="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",dte="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",fte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",pte="23"});function Nb(e){return hte.has(e.type)}function Eb(e,t,r,n,i,o,a){let s=i.get(r);!s||!t1.has(s.attributeType)||n!=="Value"||a?.operator&&!ub(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 gte(e,t){let r=t.get(e.field);return!!r&&t1.has(r.attributeType)&&ub(e.operator)}function Ab(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Sb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Ks}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Ks}}}function Zk(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);zf(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 sp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(Nb(t))return!0}else if(sp(t))return!0;return!1}function _b(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=_b(r,t);if(n)return n}}return null}function yte(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 bte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||yte(e.rawConditionExpression))}function wte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||Xs(e.rawConditionExpression)}function Zs(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=Zs(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=Zs(n,t);if(i)return i}}return null}function Tb(e,t){return{...e,trueBranch:e1(e.trueBranch,t),falseBranch:e1(e.falseBranch,t)}}function e1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Tb(r,t):r)}function _o(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?_o(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?_o(n,t,r):n)}}function ap(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n)}}function r1(e,t,r,n){return _o(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Db(e){return e.length===1&&e[0].kind==="condition"}function Ete(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Db(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function Ate(e){return!!e&&Ete(e)<Cte}function Ste(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Db(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 n1(e,t,r){let n=Ste(e,t);return!n||!Ate(n)?e:_o(e,t,i=>i1(i,r))}function i1(e,t){if(Db(e.falseBranch))return{...e,falseBranch:[i1(e.falseBranch[0],t)]};let r=Ib(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function o1(e,t){let r=Zs(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return _o(e,r.node.id,o=>({...o,falseBranch:i}))}function a1(e,t,r){let n=Zs(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return _o(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 Ib(e){return{kind:"condition",id:cr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function s1(e,t){let r={kind:"action",id:cr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:cr(),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 l1(e){if(!e)return[];let t=[];return u1(e,t),[...new Set(t)]}function u1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?u1(r,t):"field"in r&&r.field&&t.push(r.field)})}function c1(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 f1(e,n,i,!0),r==="Entity"&&d1(e,n),sp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function d1(e,t){wte(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"&&d1(r,t)})}function f1(e,t,r,n=!1){let i=n&&bte(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?ga(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&&!gte(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&&!Js(a.expression)?t.push(s==="invalidDayCount"?Sb(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&&rk(r.get(a.field)?.attributeType)&&!Kf(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=ok(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&Yf(l)&&!ak(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:ab(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:ab(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(Ab(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)&&Eb(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"&&vte.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")f1(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&&!Xf(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:ga(a.expression);!a.rawExpression&&!Js(a.expression)&&t.push(s==="invalidDayCount"?Sb(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"&&!Ab(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&&(Eb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),Zk(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:ga(l.expression);!l.rawExpression&&!Js(l.expression)&&t.push(u==="invalidDayCount"?Sb(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"?Ab(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&&(Eb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),Zk(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var hte,t1,vte,Cte,Ob=k(()=>{"use strict";ib();Zy();Zf();Hu();Xk();lb();ob();hte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);t1=new Set(["Lookup","Customer","Owner"]);vte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Cte=10});var p1={};Hr(p1,{DAY_COUNT_MAX:()=>Ks,DAY_COUNT_MIN:()=>fb,DEFAULT_DESERIALIZE_LABELS:()=>wb,WorkflowJsonMapper:()=>Qs,addElseIfInTree:()=>n1,appendToBranch:()=>r1,areFieldKindsCompatible:()=>Xf,attributeTypeToWorkflowType:()=>gk,buildWorkflowEntity:()=>jL,collectUsedFields:()=>l1,createEmptyAction:()=>s1,createEmptyCondition:()=>Ib,deserializeWorkflowJson:()=>Yk,findNode:()=>_b,findParent:()=>Zs,getDefaultOperatorForFieldType:()=>dk,getExpressionModelIssue:()=>ga,getOperatorsForFieldType:()=>Qf,hasAnyTriggerGeneratingAction:()=>sp,isDayCountValid:()=>pb,isExpressionModelComplete:()=>Js,isOperatorCompatible:()=>fk,isTriggerGeneratingAction:()=>Nb,moveBranchItemInTree:()=>a1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>tb,processTriggerScopeFromScope:()=>eb,removeElseIfInTree:()=>o1,removeNodeFromTree:()=>Tb,serializeToWorkflowJson:()=>Jk,supportsClearForActionType:()=>zf,updateActionInTree:()=>ap,updateConditionInTree:()=>_o,validateBusinessRule:()=>c1});var m1=k(()=>{"use strict";Zy();HL();Cb();Cb();Ob();Ob();Zf();Hu();Hu();});var Pb=v(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});lp.cloneJson=void 0;function Nte(e){return JSON.parse(JSON.stringify(e))}lp.cloneJson=Nte});var _1=v(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.BUSINESS_RULE_NULL_GUID=To.businessRuleRegistration=To.BusinessRuleAdapter=void 0;var h1=dt(),Ju=(m1(),Fr(p1)),g1=Jr(),y1=Q(),_te=Pb(),ii=en(),Tte=Im(),Dte=dt(),Ite=Ho(),Ote=new Set(["ShowErrorMessage","Recommendation"]);function C1(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)?C1(n):Ote.has(String(n.type))):!1}function Pte(e){return E1((0,_te.cloneJson)(e))}function E1(e){var t,r;let n=i=>(i??[]).map(o=>Rte(o)?E1(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 Rte(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 Lte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new y1.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 y1.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 kte="00000000-0000-0000-0000-000000000000";To.BUSINESS_RULE_NULL_GUID=kte;var $te=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),xte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Fte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Mte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function kn(e,t){return e===void 0?t:{...e,...t}}var va=["kind","id","type","displayName","field","stepName","stepLabels"],b1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Ute={Recommendation:[...va,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...va,"lock"],ShowErrorMessage:[...va,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...va,...b1],SetDefaultValue:[...va,...b1],SetBusinessRequired:[...va,"required"],SetVisibility:[...va,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function A1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Rb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",A1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function S1(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 Bte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function qte(e){return kn(e.bag,{id:e.id,field:e.field,...Rb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Vte(e){let t=S1(e,Bte);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 v1(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 w1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Gte=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Wte=new Set,zte="INVALID_CLEAR_FOR_FIELD";function jte(e){let t=n=>{var i;return(0,ii.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,ii.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 up=class{toArtifact(t){let r=this.residualBag(t,xte),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 kn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,Ju.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return C1(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,Ju.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Ite.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,h1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,Ju.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Pte(Lte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,h1.newId)()),u}assignMissingIds(t){return(0,Dte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,ii.isJsonObject)(n)?(N1(n,"/rootCondition",r),r):(r.push((0,ii.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,ii.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:jte(n.rootCondition),o;return r.length===0?o=Gte:r.some(a=>a.requiredLevel!==void 0)?o=Wte:o=new Set([zte]),(0,Ju.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,ii.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 S1(t,r)}buildWorkflowEntity(t,r){return(0,Ju.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Fte),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,Mte),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,Ute[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(Vte),...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",...v1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...v1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return w1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return kn(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 kn(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",A1(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(!$te.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Kte(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 kn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(qte),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return kn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return kn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return kn(t.bag,{...r,type:"SetFieldValue",...Rb(t)});case"SetDefaultValue":return kn(t.bag,{...r,type:"SetDefaultValue",...Rb(t)});case"SetBusinessRequired":return kn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return kn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return w1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};To.BusinessRuleAdapter=up;function N1(e,t,r){(0,ii.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,ii.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,ii.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?N1(o,`${t}/${n}/${a}`,r):Hte(o,`${t}/${n}/${a}`,r)})}function Hte(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,ii.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Kte(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Jte(){return{adapter:new up,api:Tte.businessRuleApi,publish:(e,t,r)=>(0,g1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,g1.boundEntityPublishScope)(t)}}To.businessRuleRegistration=Jte});var W1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.appRegistration=Do.AppAdapter=Do.HEADER_NAV_BOOLEAN_RULE=void 0;var Bi=en(),It=so(),Qu=uo(),Yte=Jr(),x1=Ud(),Lb=Od(),kb=lo(),Qte=dt(),Xte=se(),F1=Ho(),M1=Q(),U1=Rd();Object.defineProperty(Do,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return U1.HEADER_NAV_BOOLEAN_RULE}});var pp="7.0.0.0",T1=`<SiteMap IntroducedVersion="${pp}"></SiteMap>`,D1="/_imgs/imagestrips/transparent_spacer.gif",I1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",B1=["Entity","Url","DefaultDashboard","Page","GenPageId"],Yu="sitemapId",O1="sitemapName",Zte="sitemapNameUnique",P1="aiDescription",R1="[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}",ere=new RegExp(`^(?:\\{${R1}\\}|${R1})$`);function L1(e,t){if(!ere.test(e.trim()))throw new M1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function k1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new M1.ValidationError("app",t,[q1(e)]);return e}function q1(e){return(0,Bi.issue)("/headerAndNavigationRefresh",U1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function tre(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,Xte.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 rre(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 mp=class{constructor(t=F1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=cp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,It.emptyBag)()}}fromArtifact(t){(0,kb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,It.rebuildRaw)(i,(0,Qu.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,kb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,Qu.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:T1,T1),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:[[Yu,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[O1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Zte,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[P1,(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,kb.installDomShim)();let w=(0,Qu.serializeNode)(this.fromArtifact(t)),E=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?E.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let P=(s=t.bag)!==null&&s!==void 0?s:(0,It.emptyBag)();return{sitemapId:xb(P,Yu)||(t.sitemapId?L1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:xb(P,O1)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:xb(P,P1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Lb.HEADER_AND_NAVIGATION_REFRESH]:k1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Lb.APP_SETTING_ON:Lb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(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,Qte.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:L1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:k1(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(Mb):Array.isArray(r.areas)?r.areas.forEach(Mb):Array.isArray(r.groups)?Mb(r):Array.isArray(r.subAreas)?G1(r):"type"in r&&hp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Bi.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,Bi.isJsonObject)(i))return r.push((0,Bi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Bi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Bi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Bi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Bi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let E=tre(g);if(!E)return;let S=s.get(E);if(S===void 0){s.set(E,w);return}r.push((0,Bi.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,x1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,rre(t))}applyServerIdentity(t,r){let n=r[Yu];if(!n)return;t.bag||(t.bag=(0,It.emptyBag)());let i=t.bag.a.find(o=>o[0]===Yu);i?i[1]=n:t.bag.a.push([Yu,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=cp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(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}=cp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=cp(t,null),i=nre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:$b(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!==D1&&(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,It.emptyBag)(),l=dp(a)?[["IntroducedVersion",pp]]:[],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,It.mergeAttrs)(a.a,l),c:(0,It.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",pp]),t.icon!==void 0?a.push(["Icon",t.icon]):fp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Fb((0,It.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,It.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",pp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Fb((0,It.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,It.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),i=dp(n),o=ore(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>B1.includes(c));sre(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]):fp(o,"Icon",D1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",I1]):s.push("VectorIcon"):t.type==="GenPage"&&!ire(o,"VectorIcon")&&a.push(["VectorIcon",I1]);let u=Fb((0,It.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,It.mergeAttrs)(o,a,s),c:u}}};Do.AppAdapter=mp;function cp(e,t){let r=(0,Qu.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,It.rawFromNode)((0,Qu.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function $1(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 $b(e,t){var r;let n=$1(e,"Titles")[0];if(!n)return"";let o=$1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function nre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function dp(e){return e.a.length===0&&e.c.length===0}function ire(e,t){return e.some(([r])=>r===t)}function fp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function xb(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function ore(e,t){let r=are(t);return e.filter(([n])=>!B1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function are(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 sre(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 Fb(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]=lre(e[i],t,n),o}return r?[ure(t,n),...e]:e}function lre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&cre(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,It.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(V1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function ure(e,t){return{n:"Titles",a:[],c:[V1(e,t)]}}function V1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function cre(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function dre(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function hp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${dre(8)}`)}function Mb(e){var t;hp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])G1(r)}function G1(e){var t;hp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])hp(r,"subarea")}function fre(e=F1.DEFAULT_LCID){return{adapter:new mp(e),api:x1.appApi,languageSensitive:!0,publish:(t,r)=>(0,Yte.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Do.appRegistration=fre});var z1={};Hr(z1,{ActionType:()=>Bb,AppActionOrigin:()=>Kb,AppActionVisibilityType:()=>Hb,ButtonType:()=>Vb,CannotUpdateAppActionColumns:()=>pre,Context:()=>Wb,IconType:()=>qb,Location:()=>Gb,OnClickEventType:()=>jb,Scope:()=>zb,VisibilityType:()=>Ub});var Ub,Bb,qb,Vb,Gb,Wb,zb,jb,Hb,Kb,pre,j1=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Ub||(Ub={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Bb||(Bb={}));(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"})(Vb||(Vb={}));(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"})(Gb||(Gb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Wb||(Wb={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(zb||(zb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(jb||(jb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Hb||(Hb={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Kb||(Kb={}));pre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Z1=v(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.assertOneWritePerRow=Ot.commandApi=Ot.COMMAND_DUPLICATE_ROW_CODE=Ot.COMMAND_ROW_NOT_IN_BAR_CODE=Ot.COMMAND_TABLE_MISMATCH_CODE=void 0;var Jb=Lt(),Pr=ye(),qi=Q(),Rr=se();Ot.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Ot.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Ot.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var mre="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Yb(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Rr.odataPathLiteral)(t)}')${(0,Rr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Pr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Rr.normalizeGuid)(o,"entityMetadataId"):""}function Qb(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Rr.odataLiteral)(e)}'`}function Xu(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function H1(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new qi.SdkError(Ot.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 K1(e,t,r){let n=await Yb(e,t);if(r){let i=(0,Rr.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Xu(t))}return n}Ot.commandApi={async get(e,t){let r=t,n=await Yb(e,r),i=Qb(r,n),o=`/appactions${(0,Rr.odataQuery)([["$expand",mre],["$filter",i]])}`,a,s=await(0,Jb.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,Rr.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Pr.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=H1(n,r),o=await K1(e,i,n.entityMetadataId);return J1(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=H1(o,t),s=await K1(e,a,o.entityMetadataId);return J1(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Yb(e,t),n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Pr.deleteRecord)(e,"appactions",o.appactionid)}};async function J1(e,t,r,n,i){let o=r.entityMetadataId?(0,Rr.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await gre(e,t,r,o,n,i),s={};try{await bre(e,a,o,s)}catch(l){throw(0,qi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Xb(e){return e.replace(/[{}]/g,"").toLowerCase()}function X1(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=Xb(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new qi.SdkError(Ot.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.`)}}Ot.assertOneWritePerRow=X1;var hre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Y1(e,t){let r=hre[t].exec(e);return r?Xb(r[1]):void 0}async function gre(e,t,r,n,i,o){var a,s;X1(t,r);let l=vre(r.rows),u=new Set(l.map(f=>Xb(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Y1(m,"entities")===n))throw new qi.SdkError(Ot.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"}). `+Xu(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Y1(p,"appactions");if(h===void 0||!u.has(h))throw new qi.SdkError(Ot.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. `+Xu(t))}if(i&&f.exists){let h=(0,Rr.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Pr.isVersionToken)(g))throw Q1(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new qi.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,Rr.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Pr.isVersionToken)(p))throw Q1(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 yre(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new qi.SdkError(Ot.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. `+Xu(t))}return c}function Q1(e,t,r,n){return new qi.SdkError(Pr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Xu(e))}async function yre(e,t,r){let n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Rr.normalizeGuid)(a.appactionid,"appactionid"));return o}async function bre(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Pr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Pr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Pr.readEtag)(s)}else{let o=(0,Pr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Pr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Pr.readCreatedId)(l,"appactionid");u&&(n[(0,Rr.normalizeGuid)(u,"appactionid")]=(0,Pr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Pr.deleteRecord)(e,"appactions",i,o),delete n[i]}function vre(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 h$=v(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.commandRegistration=el.CommandAdapter=void 0;var lt=(j1(),Fr(z1)),e$=Jr(),bt=en(),n$=Z1(),i$=dt(),tl=se(),o$=Q(),tv="$ClientSvg:",rv=".svg",wre=2,Cre=1,Ere=1,a$="entityMetadataId",Are=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"]),gp=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 o$.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=Dre(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:Nre(g,f,c$(h),c)});return{id:c,entityLogicalName:c,commandBars:Tre(p),bag:{a:[[a$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(t),appActions:Zb(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Zb(r).map(l=>l.appactionid):[]),i=Zb(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?qre(l.row):m$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,n$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(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,i$.assignMissingIds)(t)}normalize(t){let r=Rre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,bt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,bt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>f$(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,bt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,bt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,bt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;vp(l.bag)||((0,bt.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."})),s$((0,bt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};el.CommandAdapter=gp;function vp(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function s$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;vp(n.bag)||(0,bt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,bt.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,bt.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,bt.isJsonObject)(n.action)?(0,bt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,bt.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,bt.childObjects)(n,"children",o,"control",r);s.length>0&&s$(s,`${o}/children`,r)})}function nv(e){return{a:Object.entries(e)}}function Sre(e){return Object.fromEntries(e.a)}function Zu(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function iv(e){let t=Zu(e.bag,a$);return typeof t=="string"?t:""}function Nre(e,t,r,n){var i,o;let a=[],s=[];for(let l of bp(e))l.type===lt.ButtonType.Group?a.push({id:u$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:bp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>yp(u,t,r,n)),bag:nv(l)}):s.push(yp(l,t,r,n));return s.length>0&&a.unshift({id:Bre(n,r),title:"",controls:s}),a}function ov(e){let t=e.bag?Zu(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function yp(e,t,r,n){var i,o,a,s,l;let u=u$(e.name,n),c={id:u,type:Ire(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:nv(e)},d=l$(e);d&&(c.icon=d);let f=_re(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 bp(m))if(g.type===lt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=nv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let E=[];for(let S of bp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let P=yp(S,t,r,n);p.push(P),E.push(ov(P))}h.push({id:b,bag:w,childIds:E})}else p.push(yp(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function l$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(tv)?e.fonticon.slice(tv.length)+rv:e.fonticon}function _re(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 t$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function bp(e){return[...e].sort((t,r)=>t$(t)-t$(r))}function Tre(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function u$(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 Dre(e){switch(e){case lt.Location.Form:case lt.Location.QuickForm:return"MainTab";case lt.Location.HomePageGrid:case lt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function c$(e){switch(e){case"MainTab":return lt.Location.Form;case"HomeTab":return lt.Location.HomePageGrid;default:return lt.Location.SubGridStandard}}function Ire(e){switch(e){case lt.ButtonType.Dropdown:return"FlyoutAnchor";case lt.ButtonType.Split:return"SplitButton";default:return"Button"}}function Ore(e){switch(e){case"FlyoutAnchor":return lt.ButtonType.Dropdown;case"SplitButton":return lt.ButtonType.Split;default:return lt.ButtonType.Standard}}function Pre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function d$(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 Zb(e,t=new Set){var r,n,i,o;let a=[],s=iv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=c$(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=>!d$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Pre(m)){let h=kre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])p$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function f$(e,t){if(!(0,bt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>f$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!vp(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,i$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Rre(e){let t=new Set,r=(o,...a)=>{if((0,bt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),vp(o.bag)?Zu(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,bt.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,bt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,bt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function p$(e,t,r,n,i,o,a,s=new Set){var l;let u=Lre(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=>!d$(h,s)),f=(h,g,b)=>{p$(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=>[ov(S),S])),g=new Set,b=0,w;for(let[S,P]of m.entries()){let L=P.id||(S===0?ev(u.appactionid):sv("flyout-group",`${u.appactionid}#${S}`)),I=r$(L,t,u.appactionid,n,i,P.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let O of P.childIds){let x=h.get(O);!x||g.has(O)||(g.add(O),f(x,D,b),b+=1)}}let E=w??ev(u.appactionid);for(let S of c){let P=ov(S);g.has(P)||(g.add(P),f(S,E,b),b+=1)}return}let p=e.flyoutGroupId||ev(u.appactionid);o.push(r$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Lre(e,t,r,n,i,o){let a=av(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=l$(s);return e.location!==void 0&&(s.location=e.location),s.type=Ore(e.type),s.buttonlabeltext=e.label,xre(s,e.icon,l),Mre(s,e.action),Fre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function kre(e,t,r,n,i){let o=av(e,t,r,n,i);return o.row.type=lt.ButtonType.Group,o.row.grouptitle=e.title,o}function r$(e,t,r,n,i,o){let a=av({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command flyout group id")})`,s.type=lt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function av(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Sre(e.bag),a=!0;let u=Zu(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Zu(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new o$.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=$re(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==lt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function $re(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:lt.Context.Entity,contextvalue:r.entityLogicalName,scope:lt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,tl.normalizeGuid)(n,"Command context entity metadata id")})`),i}function xre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,tl.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(rv)?tv+t.slice(0,t.length-rv.length):t,e.IconWebResourceId=null}function Fre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,tl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Cre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Ere)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Mre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=wre,t.webResourceId){let r=(0,tl.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function Ure(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 sv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Ure(`${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 ev(e){return sv("flyout-group",e)}function Bre(e,t){return sv("loose-group",`${e}|${t}`)}function m$(e){let t={...e};for(let r of Are)delete t[r];return t}function qre(e){let t=m$(e);for(let r of lt.CannotUpdateAppActionColumns)delete t[r];return t}function Vre(){return{adapter:new gp,api:n$.commandApi,publish:(e,t,r)=>(0,e$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,e$.boundEntityPublishScope)(t)}}el.commandRegistration=Vre});var y$=v(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.chartApi=void 0;var Gre=Lt(),Lr=ye(),wa=se(),g$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Wre="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";wp.chartApi={async get(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]);return{raw:(0,Lr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]),i=(0,Lr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,wa.odataQuery)([["$select",Wre],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,wa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Gre.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Lr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Lr.ensureSuccess)(await e.post(o,(0,Lr.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,Lr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Lr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,wa.normalizeGuid)(t,"id"),a=(0,Lr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Lr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Lr.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,Lr.readEtag)(l)}},delete(e,t){return(0,Lr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var k$=v(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.chartRegistration=nl.ChartAdapter=void 0;var lv=so(),b$=en(),oi=uo(),v$=Jr(),zre=y$(),uv=lo(),jre=dt(),Hre=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Kre=new Map(Hre.map(e=>[e.toLowerCase(),e]));function S$(e){var t;return e&&(t=Kre.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Jre(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Yre(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${rl(h.series.attribute)}" aggregate="${rl(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${rl(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${rl(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${rl(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,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="${rl(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var Cp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,uv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,oi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,oi.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:Ep(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:T$(d),categories:D$(d),presentation:N$(f),dataBag:u?(0,oi.projectElementBag)(d):void 0,presentationBag:c?(0,oi.projectElementBag)(f):void 0,rowBag:Qre(t.charttype,t.type)}}fromArtifact(t){(0,uv.installDomShim)();let{datadescription:r,presentationdescription:n}=Xre(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:w$(t.rowBag,"charttype"),type:w$(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,uv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,jre.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,b$.childObjects)(n,"series","","series",r),(0,b$.childObjects)(n,"categories","","category",r),r}};nl.ChartAdapter=Cp;function Qre(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 w$(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 Ep(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return S$(t[r].getAttribute("ChartType"));return"Column"}function N$(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 Ap(e){return e.getElementsByTagName("fetch")[0]}function _$(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 T$(e){let t=Ap(e);if(!t)return[];let r=_$(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=S$(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 D$(e){var t;let r=Ap(e);if(!r)return[];let n=_$(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 Xre(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!C$(e.dataBag)||!C$(e.presentationBag)){let c=Yre({...e,series:n,categories:i});return{datadescription:c,presentationdescription:yne(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=E$(e.dataBag,"datadefinition",o),s=E$(e.presentationBag,"Chart",o),l=e.chartType||Ep(s),u=T$(a);if(!cv(n,u)){let c=dv(a);Zre(o,a,n);let d=dv(a),f=d.length>0?d:n.map(()=>"");I$(o,s,f,c,l)}return cv(i,D$(a))||ene(o,a,i),e.chartType&&e.chartType!==Ep(s)&&R$(s,e.chartType),e.presentation&&!cv(e.presentation,N$(s))&&L$(s,e.presentation),{datadescription:(0,oi.serializeNode)(a),presentationdescription:(0,oi.serializeNode)(s)}}function C$(e){return!!e&&(e.c.length>0||e.a.length>0)}function I$(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 dv(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 E$(e,t,r){let n={n:t,a:(0,lv.mergeAttrs)(e.a,[]),c:(0,lv.spliceChildren)(e.c,[])};return(0,lv.rebuildRaw)(n,(0,oi.domEngine)(r),null)}function Zre(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,sne(n),r,une,{aliasPrefix:"aggregate_column",addRef:nne,removeRef:ane})}function ene(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,lne(n),r,cne,{aliasPrefix:"groupby_column",addRef:ine,removeRef:one})}function O$(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=dne(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),A$(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||rne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),A$(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),pne(m)}}function tne(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 rne(e,t){let r=tne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function P$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function nne(e,t,r){let n=P$(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 ine(e,t,r){let n=P$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function one(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 ane(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"&&!hne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function sne(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 lne(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 une(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function cne(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 dne(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 A$(e,t,r,n){n?fne(e,t,n).appendChild(r):t.appendChild(r)}function fne(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 pne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!mne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function mne(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 hne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function R$(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(!gne(r[i])){r[i].setAttribute("ChartType",t);return}}}function gne(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 L$(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 yne(e,t){let r=(0,oi.parseXmlRoot)(Jre(),"<Chart/>"),n=e.chartType||Ep(r);R$(r,n),e.presentation&&L$(r,e.presentation);let i=dv((0,oi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&I$(r.ownerDocument,r,i,i.slice(0,1),n),(0,oi.serializeNode)(r)}function cv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rl(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function bne(){return{adapter:new Cp,api:zre.chartApi,publish:(e,t,r)=>(0,v$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,v$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}nl.chartRegistration=bne});var M$=v(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.dashboardApi=Ca.dashboardEntity=void 0;var vne=Lt(),Io=ye(),il=se(),wne=mg(),$$=Xl();function x$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ca.dashboardEntity=x$;var F$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",Cne={select:F$,required:["name","type","objecttypecode","istabletenabled"]},Ene="formid,name,type,objecttypecode",Ane=0,Sne=10;Ca.dashboardApi={async get(e,t){let r=(0,il.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,il.odataQuery)([["$select",F$]]),i=(0,Io.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,$$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Io.readEtag)(i)}},async list(e,t){let r=[`(type eq ${Ane} or type eq ${Sne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,il.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,il.odataQuery)([["$select",Ene],["$filter",r.join(" and ")]])}`;return(await(0,vne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=x$(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Io.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Io.ensureSuccess)(await e.post(o,(0,Io.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Io.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Io.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,wne.patchSystemForm)(e,(0,il.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,Cne)},readContentThenToken(e,t){return Ca.dashboardApi.get(e,t)},async delete(e,t){let r=(0,il.normalizeGuid)(t,"id");return await(0,$$.assertSystemFormKind)(e,r,"dashboard"),(0,Io.deleteRecord)(e,"systemforms",r)}}});var Q$=v(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.dashboardRegistration=ai.TILE_CLASS_ID=ai.DashboardAdapter=void 0;var tc=so(),pn=uo(),fv=Jr(),ec=en(),W$=M$(),pv=lo(),Ea=dt(),z$=se(),j$=Ho(),Nne=Ny(),U$="0",mv="10",_ne=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"]]),Tne="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Np=class{constructor(t=j$.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,pv.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,pn.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:Dne(t.type),entityLogicalName:(a=(0,W$.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:Ine(l),components:B$(l,this.lcid),bag:(0,pn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,pv.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?mv:U$,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,Nne.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"?mv:U$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,pv.installDomShim)();let c=(0,pn.parseXmlRoot)(Vne(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Ea.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:B$(c,this.lcid),bag:(0,pn.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,Ea.newId)())}return t}validate(t){let r=[],n=(0,ec.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,ec.isJsonObject)(u)&&r.push((0,ec.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,ec.isJsonObject)(o.position)){let l=rc(o.position);i.has(l)?r.push((0,ec.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ai.DashboardAdapter=Np;function Dne(e){return String(e??"")===mv?"Interactive":"Standard"}function Ine(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 B$(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)=>{One(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function One(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Pne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Pne(e,t,r){var n,i;let o=J$((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=kne(a),u=$ne(s,l,a),c=Rne(a);return{id:a.getAttribute("id")||o,type:u,name:K$(e,r),classId:s,position:t,colspan:_p(e,"colspan",1),rowspan:_p(e,"rowspan",1),parameters:l,bag:(0,pn.projectElementBag)(e),...c?{icProperties:c}:{}}}function H$(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 Rne(e){let t=H$(e);return t?(0,pn.serializeNode)(t):void 0}function Lne(e,t,r){let n=H$(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,tc.rebuildRaw)((0,tc.rawFromNode)((0,pn.nodeLikeFromDom)(i)),(0,pn.domEngine)(e),null);n&&(0,pn.serializeNode)(n)===(0,pn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function K$(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 kne(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 $ne(e,t,r){var n;let i=_ne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Tne?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function _p(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 J$(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function xne(e,t){let r={n:"form",a:(0,tc.mergeAttrs)(e.bag.a,[]),c:(0,tc.spliceChildren)(e.bag.c,[])};return(0,tc.rebuildRaw)(r,(0,pn.domEngine)(t),null)}function q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=xne(e,r);return Une(r,n,e.components,t),Fne(r,n,e.components,t),(0,pn.serializeNode)(n)}function Fne(e,t,r,n){let i=Y$(t);for(let o of r)i.has(rc(o.position))||Mne(e,t,o,n)}function Mne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Gne(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||ai.TILE_CLASS_ID[r.type]||ai.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&V$(r.bag,"id")?String(V$(r.bag,"id")):Sp((0,Ea.newId)()),m=r.id?Sp(r.id):Sp((0,Ea.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],E=w?ae(w,"cell").reduce((x,K)=>x+_p(K,"colspan",1),0):0;(!w||E+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 P=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),P.appendChild(L),S.appendChild(P);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Sp(c));let D=e.createElement("parameters"),O=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(O)){let K=(0,z$.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=O[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function V$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Une(e,t,r,n){var i;let o=Y$(t),a=new Set(r.map(s=>rc(s.position)));for(let s of r){let l=o.get(rc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Bne(e,l,s.name,n),qne(e,u,s.parameters),G$(l,"colspan",s.colspan),G$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Lne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function Y$(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;J$((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(rc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function rc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Bne(e,t,r,n){if(r===K$(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 qne(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,z$.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function G$(e,t,r){_p(e,t,1)!==r&&e.setAttribute(t,String(r))}function Vne(e=2){let t=`{${(0,Ea.newId)()}}`,r=`{${(0,Ea.newId)()}}`,n=`{${(0,Ea.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>`}ai.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 Sp(e){return`{${e.replace(/[{}]/g,"")}}`}function Gne(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Wne(e=j$.DEFAULT_LCID){return{adapter:new Np(e),api:W$.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,fv.publishBoundEntity)(t,n):(0,fv.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,fv.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ai.dashboardRegistration=Wne});var gv=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.readEveryInOrder=kr.readInOrder=kr.plainRead=kr.resolveReadConcurrency=kr.MAX_READ_CONCURRENCY=void 0;var X$=Q();kr.MAX_READ_CONCURRENCY=8;function zne(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>kr.MAX_READ_CONCURRENCY)throw new X$.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${kr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}kr.resolveReadConcurrency=zne;var jne=e=>({ok:!0,value:e}),hv=e=>({ok:!1,error:e});function Hne(e){let t=(async()=>e())().then(jne,hv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}kr.plainRead=Hne;async function Z$(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new X$.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(hv);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:hv(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 Kne(e,t,r,n){return Z$(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}kr.readInOrder=Kne;function Jne(e,t,r,n){return Z$(e,t,r,n,"continue")}kr.readEveryInOrder=Jne});var gx=v(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});Dp.genPageApi=void 0;var Tp=Lt(),dx=Wl(),Be=ye(),ve=se(),$n=Dd(),Ye=Q(),fx=dt(),ex=gv();function Yne(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 si="uxagentprojects",Sa="uxagentprojectfiles",oc="agentconversationmessages",ac="uxagentprojectid",Ut="uxagentprojectfileid",Na="agentconversationmessageid",nc=`${ac},name`,Qne=`${Ut},filename,filetype`,px=2e8,mx=200000001,_a={"MSCRM.IncludeUnpublished":"true"},yv={};function Aa(e,t){return{"MSCRM.VersioningChangeset":e,..._a,...t}}async function wv(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{..._a}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function sc(e,t,r=_a){let n=`/${Sa}(${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=Yne(o);if(a)return{status:"available",data:(0,$n.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,$n.utf8ToBase64)(o)};throw new Ye.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 hx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Xne(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Ye.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=`/${Sa}(${t})/filecontent`,s=(0,$n.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Aa(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":hx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function ic(e,t,r=_a){let n=`/${Sa}`+(0,ve.odataQuery)([["$select",Qne],["$filter",`_${ac}_value eq ${t}`]]);return(await(0,Tp.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 bv(e,t){let r=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Tp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{..._a}})}async function tx(e,t){var r,n,i;let{row:o,etag:a}=await wv(e,si,t,nc),s=new Map;for(let{row:l,etag:u}of await ic(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Ut])!==null&&r!==void 0?r:""),Ut),{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 rx(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 Ye.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 Ye.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 Cv(e){let t=(0,$n.base64ToUtf8)(e);return(0,$n.utf8ToBase64)(t)===(0,$n.bytesToBase64)((0,$n.base64ToBytes)(e))?t:void 0}function Zne(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?{[Na]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${si}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?px:mx}}async function eie(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=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Na} eq ${f}`).join(" or ")]]),u=await(0,Tp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{..._a}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Na])!==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"?px:mx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Ye.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 vv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${si}`,body:(0,Be.withClientMintedId)({name:t.name},ac,e),headers:Aa(n)};case"createRow":return{method:"POST",path:`/${Sa}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${ac}@odata.bind`]:`/${si}(${e})`},Ut,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Aa(n)};case"renameRow":return{method:"PATCH",path:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Aa(n,{"If-Match":"*"})};case"content":{let i=Cv(t.data);if(i===void 0)throw new Ye.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:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Aa(n,{"x-ms-file-name":hx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Sa}(${t.fileId})`,headers:Aa(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${si}(${e})`,body:{name:t.name},headers:Aa(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${oc}`,body:Zne(e,t.turn,r,n)};default:{let i=t;throw new Ye.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function nx(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Cv(r.data)!==void 0)}async function ix(e,t,r,n,i){await(0,dx.postChangeSet)(e,r.map(o=>vv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function ox(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 Xne(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=vv(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=>vv(t,l,n,i));if(e.supportsAtomicBatch)await(0,dx.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 ax(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await tx(e,t),c=new Map;for(let E of r)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,ve.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[E,S]of c){let P=u.rows.get(E);P&&(P.filename!==S.name||P.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${P.filename}' (type ${P.filetype})`)}for(let E of r){if(E.kind!=="content")continue;let S=await sc(e,(0,ve.normalizeGuid)(E.file.id,"file id")),P=(0,$n.bytesToBase64)((0,$n.base64ToBytes)(E.data));(S.status!=="available"||S.data!==P)&&d.push(S.status==="available"?`file '${E.file.name}' holds ${(0,$n.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,$n.base64ToBytes)(P).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(r.filter(E=>E.kind==="content").map(E=>(0,ve.normalizeGuid)(E.file.id,"file id")));for(let[E,S]of c)!f.has(E)&&(await sc(e,E)).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 tx(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(E=>{var S,P;return((S=u.rows.get(E))===null||S===void 0?void 0:S.etag)!==((P=m.rows.get(E))===null||P===void 0?void 0:P.etag)}),g=p.length!==i.size||p.some(E=>!i.has(E)),b={},w=[];for(let[E,S]of m.rows){let P=c.has(E)||!o?S.etag:(s=o.get(E))!==null&&s!==void 0?s:null;b[E]=P,P!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(E=>!E)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):tie({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(E=>`Generative page '${t}' was written, but its file '${E}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function sx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await wv(e,si,o,nc),l=await ic(e,o),u={},c=[];if(n>1)await(0,ex.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Ut])!==null&&m!==void 0?m:""),Ut);return(0,ex.plainRead)(async()=>({fileId:p,content:await sc(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[Ut])!==null&&i!==void 0?i:""),Ut);u[p]=m;let h=await sc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await bv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Dp.genPageApi={get(e,t,r){return sx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return sx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${si}(${i})`+(0,ve.odataQuery)([["$select",nc]]),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 ic(e,i,yv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Ut])!==null&&n!==void 0?n:""),Ut);l[w]=b,u.push({...g,content:await sc(e,w,yv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Ut])}@${String(w)}`).sort().join("|"),f=()=>new Ye.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 ic(e,i,yv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Ye.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=`/${si}`+(0,ve.odataQuery)([["$select",nc]]);return(await(0,Tp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{..._a}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[ac])!==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,fx.newId)(),a=rx(o,i,void 0);cx(e,a),ux(e,o,i);let s=lx(),l=[],u=!0;nx(e,a)?await ix(e,o,a,i,s):{warnings:l,turnRecorded:u}=await ox(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 ax(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 Ye.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 eie(e,l,s);ux(e,l,u);let c=await ic(e,l),{row:d,etag:f}=await wv(e,si,l,nc);if(n&&f&&n!==f)throw new Ye.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 Ye.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,O;return[(0,ve.normalizeGuid)(String((D=I[Ut])!==null&&D!==void 0?D:""),Ut),{filename:String((O=I.filename)!==null&&O!==void 0?O:""),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 Ye.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 Ye.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 Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}));for(let[I,D]of Object.entries(i)){let O=I.toLowerCase();if(!p.has(O))continue;let x=b.get(O);if(!D||!x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${O}' before writing: ${D?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(D!==x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${O}' 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=rx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(cx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}))};let E=lx(),S=[],P=!0;nx(e,w)?await ix(e,l,w,u,E):{warnings:S,turnRecorded:P}=await ox(e,l,w,u,E);let L=await ax(e,l,w,u,h,b,S);return P?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await bv(e,n);await(0,Be.deleteRecord)(e,si,n);let o=new Set(i.map(l=>{var u;return String((u=l[Na])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await bv(e,n)){let u=String((r=l[Na])!==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,oc,l)}catch(u){u instanceof Ye.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Ye.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 ${oc} rows regarding '${n}'.`)}};function lx(){return`uxagentproject_${(0,fx.newId)()}`}function tie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function ux(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 Ye.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 cx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Ye.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=>Cv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Ye.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 Lx=v(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.genPageRegistration=al.GenPageAdapter=void 0;var rie=gx(),nie=Jr(),Ie=en(),Lp=dt(),kp=Dd(),iie=se(),Ta=Q(),Tx=Tg(),Ev=Km(),Oo=2e8,Dx=200000001,Gi={source:{name:"src/pages/page.tsx",fileType:Oo},output:{name:"src/pages/page.compiled",fileType:Dx},config:{name:"config.json",fileType:Oo},prompt:{name:"firstPrompt.json",fileType:Oo}},Ix=Object.keys(Gi),oie=["dataSources","model","connectorBindings","actionBindings"],aie=["userMessage","agentMessage"],yx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},lie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Ox(e,t,r){let n=(0,iie.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 Ip(e,t){return Ox(e,sie[t],"id")}function uie(e,t){let r=Ox(e,lie,"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 bx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Lp.newId)()}function Vi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ol(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Op(e){return JSON.parse(JSON.stringify(e))}function cie(e){let t=Vi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function uc(e){if(!e||e.status!=="available")return;let t=(0,kp.base64ToUtf8)(e.data);return(0,kp.utf8ToBase64)(t)===e.data?t:void 0}function Px(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ol((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,Tx.isLoadableGenPageOutput)(r)}function die(e,t){var r;try{return Px(e,t,uc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Pp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function vx(e,t){if(t===Oo&&e.includes("page.tsx"))return"source";if(t===Dx&&e.includes(".compiled"))return"output";if(t===Oo&&e===Gi.config.name)return"config";if(t===Oo&&e===Gi.prompt.name)return"prompt"}function wx(e){let t=e.toLowerCase();return Ix.some(r=>Gi[r].name.toLowerCase()===t)}function Av(e){return Object.fromEntries(e)}function Rx(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),Av(i)}function Cx(e){var t,r,n;return Rx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},oie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Ex(e){var t,r;return Rx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},aie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function Ax(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=Av(n)),!0}function Sx(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=Av(n)),!0}function cc(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 fie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function Nx(e){return cc(e)?[]:fie.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 _x(){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 Rp(e){return{status:"available",data:(0,kp.utf8ToBase64)(e)}}function lc(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 $p=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Vi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,E;let S=Vi(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((E=S.filetype)!==null&&E!==void 0?E:Oo),content:cie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let E=Vi(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((b=E.message)!==null&&b!==void 0?b:""),createdOn:String((w=E.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=vx(g.name,g.fileType);b?((s.has(b)||g.name!==Gi[b].name)&&(u=!1),s.set(b,g)):(wx(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(lc(n,i));let c=lc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=uc(f.content);if(g===void 0)return a(lc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Pp(uc(p.content));if(!g||!Ax(c,d,g))return a(lc(n,i))}let h=s.get("prompt");if(h){let g=Pp(uc(h.content));if(!g||!Sx(c,d,g))return a(lc(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&&!ol((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Ta.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=Nx(t);if(b.length>0)throw new Ta.ValidationError("genPage",t.id,b);let w=[],E=r===void 0,S=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(cc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=ge=>{var je;return(je=I[ge])!==null&&je!==void 0?je:Ip(S.id,ge)},O=(ge,je,de)=>{w.push({id:D(ge),name:Gi[ge].name,fileType:Gi[ge].fileType,content:je,unchanged:de})};if(S.source!==void 0){O("source",Rp(S.source),!E&&r?.source===S.source&&I.source!==void 0);let ge=uc((l=S.bag)===null||l===void 0?void 0:l.output);Px(S,r,ge)?O("output",{status:"retain"},!0):O("output",Rp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Ta.ValidationError("genPage",S.id,[_x()]);if(I.output!==void 0){if(!E&&!ol((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Ta.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.")]);O("output",{status:"retain"},!0)}}let x=Cx(S),K=!E&&r!==void 0&&ol(Cx(r),x);(E||I.config!==void 0||!K)&&O("config",Rp(JSON.stringify(x)),K&&I.config!==void 0);let Re=Ex(S),qt=!E&&r!==void 0&&ol(Ex(r),Re);(I.prompt!==void 0||Object.keys(Re).length>0&&!qt)&&O("prompt",Rp(JSON.stringify(Re)),qt&&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(O=>O.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ol(D,I)})}let P=[];if(S.newTurn){let I=S.newTurn.id,D=O=>I?{id:uie(I,O)}:{};P.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&P.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...P.length>0?{messages:P,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:Op(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!cc(t)&&!t.newTurn)return t;let u=Op(t);if(delete u.newTurn,!cc(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=Ix.find(p=>Gi[p].name===d.name&&Gi[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,kp.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,Ax(u,c,(s=Pp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Sx(u,c,(l=Pp(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"&&yx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Lp.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 Ta.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Ta.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,Ev.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Ev.buildGenPageLegacyEnums)(a):void 0,d=(0,Tx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Ta.ValidationError("genPage",t.id,d.diagnostics.map(pie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=die(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=bx(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:bx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Oo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=Op(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=Op(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:Ip(i,"source"),output:Ip(i,"output"),config:Ip(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Lp.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,Lp.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&&Vi(Vi(n.bag).rows).source!==void 0&&r.push(_x()),r.push(...Nx(t)),n.newTurn!==void 0){let s=Vi(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"||!yx.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"||!Ev.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=cc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Vi(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&&(wx(f)||vx(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=Vi(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}};al.GenPageAdapter=$p;function pie(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 mie(){return{adapter:new $p,api:rie.genPageApi,publish:(e,t)=>(0,nie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}al.genPageRegistration=mie});var $x=v(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});Fp.reconcileBpfSecurityRoles=void 0;var kx=Lt(),Nv=Q(),xp=ye(),dc=se(),hie="Global",Sv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function gie(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,dc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,xp.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 Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,kx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Sv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Sv[u]);if(c){let d=(0,dc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function yie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,xp.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 Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,kx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,dc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function bie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:hie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function vie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function wie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await gie(e,t.toLowerCase());for(let s of r){let l=(0,dc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new Nv.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Sv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,dc.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 yie(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 bie(e,l,f);for(let p of m)await vie(e,l,p)}}Fp.reconcileBpfSecurityRoles=wie});var Kx=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.bpfApi=void 0;var dr=Yi(),xx=Wl(),Cie=Lt(),Qe=Q(),ut=ye(),mn=se(),Eie=$x(),Aie=_m(),fc=Dm(),Sie={"Content-Type":"application/json",Accept:"application/json"},Tv={...Sie,Prefer:"return=representation"},Nie=`category eq ${dr.WorkflowCategory.BusinessProcessFlow} and type eq ${dr.WorkflowTypeCode.Definition} and businessprocesstype eq ${dr.BusinessProcessType.BusinessFlow}`,_ie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Tie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Die=["xaml","name","description","processorder"];async function _v(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,Eie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Iv(e,t,r){let n={statecode:dr.StateCode.Activated,statuscode:dr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await Hx(e,i,n,r,null);try{return(0,ut.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?zx(s):s}}var Wx=new WeakSet;function zx(e){return typeof e=="object"&&e!==null&&Wx.add(e),e}function jx(e){return typeof e=="object"&&e!==null&&Wx.has(e)}function Fx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||ut.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function Hx(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ut.resendWhile)(ut.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...Tv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ut.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?zx(s):s}}async function Mx(e,t,r){return(0,ut.readEtag)(await Iv(e,t,r))}function Ux(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. `+Mp(e))}async function pc(e,t){var r;let n=`/workflows(${t})${(0,mn.odataQuery)([["$select","statecode"]])}`,i=(0,ut.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 Dv(e,t,r,n,i=null){if((n??await pc(e,t))!==dr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:dr.StateCode.Draft,statuscode:dr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await Hx(e,a,o,r,i))}catch(c){return await Bx(e,t,c,jx(c))}if(ut.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Bx(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,ut.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ut.readEtag)(u)}}async function Bx(e,t,r,n){let i;try{i=await pc(e,t)}catch{i=void 0}if(i===dr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===dr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===dr.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 Iie(e,t){let r=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,r,null),"restored"}catch{return Ov(e,r)}}async function Oie(e,t,r){let n=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,n,r),"restored"}catch(i){return i instanceof Qe.SdkError&&i.code===ut.VERSION_CONFLICT_CODE?"changed":Ov(e,n)}}async function Ov(e,t){try{let r=await pc(e,t);return r===dr.StateCode.Activated?"restored":r===dr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function qx(e,t,r,n){return r?{outcome:await Oie(e,t,r),attempted:!0}:n?{outcome:await Ov(e,(0,mn.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await Iie(e,t),attempted:!0}}function Pie(e,t){let r=new Qe.SdkError(fc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,fc.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 Vx(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 Rie(e,t){try{return await pc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Lie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Dv(e,t,r),o=n?i:r;if(o)return await(0,fc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Rie(e,t)}function Mp(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 Gx(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. ${Mp(e)}`)}function kie(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.) ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function $ie(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. ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function xie(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 Pv(e){let t={};for(let r of Die)e[r]!==void 0&&(t[r]=e[r]);return t}var Fie=["name,processorder","description,name,processorder"];function Mie(e){let{xaml:t,...r}=Pv(e);return typeof t=="string"&&Fie.includes(Object.keys(r).sort().join(","))}async function Uie(e,t,r,n){let{xaml:i,...o}=Pv(r),[,a]=await(0,xx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,mn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ut.readEtag)((0,xx.partResponse)(a))}Up.bpfApi={async get(e,t){let n=`/workflows(${(0,mn.normalizeGuid)(t,"id")})${(0,mn.odataQuery)([["$select",Tie]])}`,i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.readEtag)(i)}},async list(e,t){let r=[Nie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,mn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,mn.odataQuery)([["$select",_ie],["$filter",r.join(" and ")]])}`;return(await(0,Cie.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,mn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ut.ensureSuccess)(await e.post(i,r.record,{headers:Tv}),e.apiUrl(i)),a=(0,ut.readEtag)(o);if(!a)throw Gx(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 Mx(e,n,a)),await _v(e,r)}catch(l){let u=await Lie(e,n,s);throw u==="survived"?kie(n,l):u==="unknown"?$ie(n,l):l instanceof Qe.SdkError&&l.code===ut.VERSION_CONFLICT_CODE?xie(n,l):l}if(!s)throw Gx(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,mn.normalizeGuid)(t,"id"),a=(0,ut.requireEtag)(n,"bpf",o),s=await pc(e,o);if(s===dr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Mie(i.record)){let m=await Uie(e,o,i.record,a);return await _v(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await Dv(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw Ux(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ut.ensureSuccess)(await e.patch(p,Pv(i.record),{headers:{...Tv,"If-Match":m}}),e.apiUrl(p))}catch(b){throw Fx(b)&&(d=null),b}let g=(0,ut.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw Ux(o,"definition write");try{g=await Mx(e,o,g)}catch(b){throw Fx(b)&&(d=null),b}f=!0}return await _v(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await qx(e,o,d,jx(m));if(p!=="restored")throw Vx(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,mn.normalizeGuid)(t,"id"),n=await(0,Aie.assertWorkflowKind)(e,r,dr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Dv(e,r,null,void 0,n);try{await(0,fc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,fc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await qx(e,r,o,!1);if(s==="changed")throw Pie(r,a);if(s!=="restored")throw Vx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var PF=v(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});ll.bpfRegistration=ll.BpfAdapter=void 0;var Bp=Yi(),Bie=Kx(),Rv=so(),Da=uo(),sF=lo(),zr=en(),$r=dt(),xn=Q(),qie=100,Lv='<?xml version="1.0" encoding="utf-16"?>',Jx=1033,lF="mxswa:Workflow",Vie="mxswa:ActivityReference.Properties",Gie="mcwo:StepLabel",Wie="mcwb:Control",Yx="mcwb:Control.ControlDisplayName",uF="mcwb:Control.DataFieldName",cF="DataFieldName",Qx="ControlDisplayName",dF="Literal",Vp="x:Null",Xx="x:String",kv="x:Key",$v="DisplayName",Wp="Activities",zie="StepLabels",fF="StageId",pF="StageCategory",mF="NextStageId",hF="ProcessStepId",qp="IsProcessRequired",gF="EntityComposite",yF="StageComposite",bF="StepComposite";function mc(e){return(0,zr.isJsonObject)(e)?e:{}}function ui(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 Ia(e,t){var r;return(r=ui(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function di(e){return Ia(e,Vie)}function fr(e,t){var r;return(r=ui(e).find(n=>n.getAttribute(kv)===t))!==null&&r!==void 0?r:null}function sl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function vF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function hc(e){var t;let r=(t=e.getAttribute($v))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function wF(e,t){var r;let n=(r=e.getAttribute($v))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute($v,i>=0?n.slice(0,i+2)+t:t)}function CF(e,t){let r=fr(e,zie),n=Ia(r,Gie);n&&n.setAttribute("Description",t)}function jie(e){let t=fr(e,pF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:Number(r)}function Hie(e){let t=fr(e,mF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:r}function EF(e){let t=AF(e);if(!t)return;let r=NF(t,cF,uF);return r===""?void 0:r}function xv(e,t){let r=ui(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ui(n))r.push(i)}return null}function AF(e){let t=fr(di(e),Wp);return t?xv(t,Wie):null}function SF(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 NF(e,t,r){var n;return SF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":Xie(e,r)}function Zx(e,t,r,n){if(SF(e,t)){e.setAttribute(t,n);return}if(Ia(e,r)){Kie(e,r,n);return}throw new xn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Kie(e,t,r){let n=Ia(e,t),i=n?xv(n,dF):null;if(!i)throw new xn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function _F(e){return hc(e)}function zp(e){let t=Ia(e,lF),r=[];for(let n of ui(t).filter(i=>sl(i,gF))){let i=fr(di(n),Wp);for(let o of ui(i).filter(a=>sl(a,yF)))r.push({el:o,entity:_F(n)})}return r}function Fv(e){let t=fr(di(e),Wp);return ui(t).filter(r=>sl(r,bF))}function Jie(e){let t=di(e),r=ci(fr(t,qp)).trim().toLowerCase(),n=EF(e),i={id:ci(fr(t,hF)),name:hc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Yie(e,t){let r=di(e),n=jie(r),i=Hie(r),o={id:ci(fr(r,fF)),name:hc(e),entityLogicalName:t,steps:Fv(e).map(Jie)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Qie(e){return zp(e).map(({el:t,entity:r})=>Yie(t,r))}function li(e){return new xn.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 Xie(e,t){var r;let n=Ia(e,t),i=n?xv(n,dF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Mv(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(Mv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function TF(e){return fr(di(e),Wp)}function Zie(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,$r.newId)(),{body:a}=jp(Uv(i,(0,$r.newId)(),t.id,o));return Mv(e,zp((0,Da.parseXmlRoot)(a,"<Activity/>"))[0].el)}function eoe(e,t){let{body:r}=jp(Uv("account",(0,$r.newId)(),(0,$r.newId)(),t.id));return Mv(e,Fv(zp((0,Da.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function DF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function IF(e,t,r,n){let i=fr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw li(`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!==Vp&&ci(i).trim()!==""){let s=t.createElement(Vp);s.setAttribute(kv,r),o.replaceChild(s,i)}return}if(i.tagName===Xx){ci(i).trim()!==n&&vF(i,t,n);return}let a=t.createElement(Xx);a.setAttribute(kv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function toe(e,t,r){IF(e,t,pF,r===void 0?void 0:String(r))}function roe(e,t,r){IF(e,t,mF,r)}function OF(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 eF(e){return ci(fr(di(e),fF))}function tF(e){return ci(fr(di(e),hF))}function rF(e,t,r){var n,i,o,a;let s=di(e);r.name!==hc(e)&&(wF(e,r.name),CF(s,r.name));let l=ci(fr(s,qp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=fr(s,qp);if(!u)throw li(`setting '${qp}' on a step whose xaml does not expose that slot`);vF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=EF(e))!==null&&o!==void 0?o:"")){let u=AF(e);if(!u)throw new xn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";Zx(u,cF,uF,c),c!==""&&NF(u,Qx,Yx)===""&&Zx(u,Qx,Yx,c)}}function nF(e,t,r,n){var i;let o=di(e);if(!o)throw new xn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==hc(e)&&(wF(e,r.name),CF(o,r.name)),toe(o,t,r.category),roe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw li("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw li("stage actions or conditional branching");let a=TF(e);if(!a)throw new xn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new xn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Fv(e);if(OF(l,s.map(d=>d.id),tF)){l.forEach((d,f)=>rF(d,t,s[f]));return}let u=new Map(l.map(d=>[tF(d),d]));if(ui(a).some(d=>!sl(d,bF)))throw li("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:eoe(t,d)});DF(a,c),c.forEach((d,f)=>rF(d,t,s[f]))}function noe(e,t,r){let n=Ia(e,lF);if(!n)throw new xn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw li("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new xn.InvalidArgumentError("a BPF must have at least one stage");let i=zp(e),o=i.map(f=>f.el);if(OF(o,r.stages.map(f=>f.id),eF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw li(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);nF(f,t,h,h.nextStageId)});return}let a=ui(n).filter(f=>sl(f,gF));if(a.length!==1)throw li("adding, removing or reordering stages on a multi-table process");let s=a[0],l=_F(s),u=TF(s);if(!u)throw new xn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ui(u).some(f=>!sl(f,yF)))throw li("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 li(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[eF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Zie(t,f,l)});DF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;nF(f,t,r.stages[m],p)})}function jp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function ioe(e){var t,r,n,i,o,a;(0,sF.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,Rv.mergeAttrs)(s.a,[]),c:(0,Rv.spliceChildren)(s.c,[])};return{root:(0,Rv.rebuildRaw)(m,(0,Da.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Lv,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=Uv(e.entityLogicalName,(0,$r.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,$r.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,$r.newId)()),{body:d}=jp(c);return{root:(0,Da.parseXmlRoot)(d,"<Activity/>"),prolog:Lv,eol:"lf"}}function ooe(e){let{root:t,prolog:r,eol:n}=ioe(e);noe(t,t.ownerDocument,e);let i=(0,Da.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function aoe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Gp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,sF.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}=jp(o),u=(0,Da.parseXmlRoot)(l,"<Activity/>");a.stages=Qie(u),a.bag={xaml:(0,Da.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,$r.newId)(),name:t.name,uniquename:aoe(t),primaryentity:t.entityLogicalName,xaml:ooe(t),category:Bp.WorkflowCategory.BusinessProcessFlow,type:Bp.WorkflowTypeCode.Definition,businessprocesstype:Bp.BusinessProcessType.BusinessFlow,scope:Bp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:qie};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 xn.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(oF):[oF({id:(0,$r.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,$r.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=mc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,$r.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,zr.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,zr.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=mc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,zr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,zr.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,zr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,zr.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 mc(h).id=="string"?h.id.trim():"";w===""?r.push((0,zr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,zr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!iF(i,d.branch.nextStageId)&&r.push((0,zr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!iF(i,d.nextStageId)&&r.push((0,zr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,zr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=soe(i);return s>=0&&r.push((0,zr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};ll.BpfAdapter=Gp;function soe(e){let t=new Map(e.map(r=>[mc(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 iF(e,t){return e.some(r=>mc(r).id===t)}function oF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(aF):[aF({id:(0,$r.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 aF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 Uv(e,t,r,n){return`${Lv}<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="${Jx}" /></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="${Jx}" /></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 loe(){return{adapter:new Gp,api:Bie.bpfApi,languageSensitive:!0}}ll.bpfRegistration=loe});var RF=v(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});Hp.buildRegistrations=void 0;var uoe=SL(),coe=WL(),doe=_1(),foe=W1(),poe=h$(),moe=k$(),hoe=Q$(),goe=Lx(),yoe=PF();function boe(e){let t=new Map;return t.set("form",(0,uoe.formRegistration)(e)),t.set("view",(0,coe.viewRegistration)()),t.set("businessRule",(0,doe.businessRuleRegistration)()),t.set("app",(0,foe.appRegistration)(e)),t.set("command",(0,poe.commandRegistration)()),t.set("chart",(0,moe.chartRegistration)()),t.set("dashboard",(0,hoe.dashboardRegistration)(e)),t.set("genPage",(0,goe.genPageRegistration)()),t.set("bpf",(0,yoe.bpfRegistration)()),t}Hp.buildRegistrations=boe});var jF=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 Wi=Lt(),hn=ye(),qe=se(),LF=dt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var UF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},voe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>UF[e]===t).map(([e])=>e)),woe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Bv(e){return woe[e]}var Kp=1e6;function Coe(e,t){let r=Bv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Kp} (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>Kp?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(Kp).length||Number(s)>Kp?n():s}}return n()}function Eoe(e,t){let r=Bv(t);return r?e===r.enabled:e!=="0"}async function Aoe(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,Wi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function Soe(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 kF=new WeakMap;async function Noe(e,t){var r,n;let i=kF.get(e);if(i||(i=new Map,kF.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,Wi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function _oe(e,t,r){var n,i;let o=await Noe(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,Wi.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 Toe=4,Doe=500,$F=20,xF=3e4;function Ioe(e){if(e===void 0)return Toe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${$F}; got ${e}.`);return Math.min($F,Math.max(1,Math.floor(e)))}function Ooe(e){if(e===void 0)return Doe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${xF}; got ${e}.`);return Math.min(xF,Math.max(0,Math.floor(e)))}async function Poe(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 _oe(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 Jp(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 BF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Bv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Jp(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,hn.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=Jp;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,hn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=qF;async function Roe(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Jp(e,i,t);r[n]={enabled:BF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Roe;async function Loe(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=Ioe(n.verifyAttempts),a=Ooe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=UF[p];g&&s.push({feature:p,setting:g,requestedValue:Coe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await Soe(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 Aoe(e,t)),c),f=new Map,m=async p=>{if(voe.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Jp(e,h);f.set(h,{enabled:BF(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 Poe(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 E=Eoe(g,p)?await m(p):void 0;E&&!E.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 '${E.setting}' reads '${E.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=Loe;var VF="GptPowerPrompt",koe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function GF(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=GF;async function $oe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,hn.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,Wi.describeMalformedValue)(o)}`);return o}function qv(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,Wi.describeMalformedValue)(i)}`);return i}async function WF(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${VF}'`],["$top",1]])}`,n=(0,hn.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,Wi.describeMalformedValue)(i)}`);let o=qv(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,Wi.describeMalformedValue)(a)}`)}function zF(e){return`${e} row summary`}async function xoe(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,hn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await WF(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===zF(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Foe(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,hn.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,Wi.describeMalformedValue)(s)}`);let l=qv(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 $oe(e,t.entityLogicalName),c=await WF(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 '${VF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,LF.newId)(),f=(0,LF.newId)(),m=JSON.stringify(GF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:zF(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:koe,RunConfiguration:""};(0,hn.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,hn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,hn.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=Foe;async function Moe(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,hn.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,Wi.describeMalformedValue)(a)}`);let s=qv(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 xoe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await FF(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 (${MF(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 FF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Boe);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"} (${MF(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=Moe;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 Uoe="0x8004f01f";function Boe(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()===Uoe}function qoe(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 FF(e,t,r,n=()=>!1){let i;try{let o=await(0,hn.resendWhile)(qoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,hn.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 MF(e){return e instanceof Error?e.message:String(e)}});var JF=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.findArtifact=ul.resolveArtifact=void 0;var Bt=se(),zi=Td(),Voe=Ud(),Goe=Lt(),Woe=ye(),HF=Q();async function KF(e,t,r){let n="/uxagentprojects"+(0,Bt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Bt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Goe.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function zoe(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Voe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Bt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Woe.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,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.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,zi.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Bt.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,zi.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Bt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Bt.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,zi.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Bt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Bt.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,zi.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Bt.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,zi.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Bt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return KF(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}ul.resolveArtifact=zoe;async function joe(e,t,r){var n,i,o,a,s,l;let u=(0,Bt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Bt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,zi.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await KF(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new HF.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=Hoe(t,u,c,r),f=t!=="app",m=await(0,zi.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new HF.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}ul.findArtifact=joe;function Hoe(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,Bt.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 QF=v(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});Qp.seedRecordGraph=void 0;var YF=Td(),Koe=cd(),Yp=se(),Joe=Q();async function Yoe(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,Koe.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let O=D.parentEntity.toLowerCase(),x=(s=d(O))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Joe.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,Yp.assertODataName)(await u(O),`entity set for parent '${D.parentEntity}'`),Re=(0,Yp.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Re})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Yp.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Yp.odataLiteral)(x)}'`).join(" or "),O=await(0,YF.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of O??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],E=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let O=D.toLowerCase(),x=E.get(O);if(x!==void 0)return x;let K=w.push(L)-1;return E.set(O,K),K}return w.push(L)-1}),P=w.length?await(0,YF.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):P[S[I]]})}return{createdIds:c}}Qp.seedRecordGraph=Yoe});var sM=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.getEntityPrivileges=Zt.addEntityPrivilegesToRole=Zt.deleteSecurityRole=Zt.createPersonaRole=Zt.createSecurityRole=Zt.SDK_ROLE_MARKER=void 0;var Fn=ye(),Pt=se(),jr=Q(),Xp={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Gv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},XF={user:1,businessUnit:2,parentChild:3,organization:4},Vv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Zt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Qoe(e){return Object.prototype.hasOwnProperty.call(Xp,e)?Xp[e]:void 0}function Xoe(e){return Object.prototype.hasOwnProperty.call(Gv,e)}var ZF=new WeakMap,eM=new WeakMap;async function nM(e,t){var r,n;(0,Pt.assertODataName)(t,"entity logical name");let i=ZF.get(e);i||(i=new Map,ZF.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Pt.odataPathLiteral)(t)}')${(0,Pt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Fn.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 jr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Zoe(e){var t,r,n;let i=eM.get(e);if(i)return i;let o=`/businessunits${(0,Pt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Fn.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 jr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Pt.normalizeGuid)(l,"businessUnitId");return eM.set(e,u),u}async function iM(e,t){var r;let n=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=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Xoe(o))throw new jr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await nM(e,i.entity);for(let s of i.access){let l=Qoe(s);if(!l)throw new jr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new jr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Vv[o];if(u[c]===!1)throw new jr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Pt.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 jr.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=XF[o]>XF[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 eae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Gv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Fn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function tM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Pt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Fn.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 tae(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,Pt.normalizeGuid)(l,"teamId");if(!await tM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Fn.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,Pt.normalizeGuid)(l,"userId");if(!await tM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Fn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function rM(e,t,r){var n,i;let o=`/roles${(0,Pt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Pt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Fn.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:"")===Zt.SDK_ROLE_MARKER};if(l.some(d=>!u(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(l.length>1)throw new jr.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,Pt.normalizeGuid)(c,"roleId"):void 0}function rae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Pt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Pt.normalizeGuid)(n,"userId"))}}function oM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function aM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new jr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Pt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Zoe(e),a=await iM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=rae(t.assignTo),l=await rM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Zt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Fn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Pt.normalizeGuid)((0,Fn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await rM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await eae(e,l,a,u);let c=await tae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:oM(a),assignedTeams:c.teams,assignedUsers:c.users}}Zt.createSecurityRole=aM;async function nae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.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:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return aM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Zt.createPersonaRole=nae;async function iae(e,t){let n=`/roles(${(0,Pt.normalizeGuid)(t,"roleId")})`;(0,Fn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Zt.deleteSecurityRole=iae;async function oae(e,t,r){let n=(0,Pt.normalizeGuid)(t,"roleId");if(r.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 iM(e,r),o={Privileges:i.map(s=>({Depth:Gv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Fn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),oM(i)}Zt.addEntityPrivilegesToRole=oae;var aae=new Map(Object.keys(Xp).map(e=>[Xp[e],e]));async function sae(e,t){return(await nM(e,t)).map(n=>{let i=Object.keys(Vv).filter(a=>n[Vv[a]]!==!1),o=aae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}Zt.getEntityPrivileges=sae});var SM=v(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.createMakerSdk=mr.MakerSdk=mr.PUSH_NOT_ATTEMPTED_CODE=mr.ALREADY_EXISTS_CODE=void 0;var lM=Im(),uM=Jr(),Z=Q(),gn=$a(),lae=DC(),wM=$C(),cl=qC(),uae=Pm(),cae=lE(),dl=dE(),dae=NE(),fae=PE(),pae=lA(),cM=iS(),Rt=cd(),Wv=vg(),dM=hN(),Zp=Xl(),ji=Td(),em=AN(),fl=Od(),mae=Rd(),er=wg(),hae=Tg(),gae=$g(),fM=Dg(),yae=RF(),tm=dt(),bae=Ho(),fi=Pb(),yn=xm(),zv=gv(),vae=3e5,pr=ye(),Oa=se(),pl=jF(),pM=JF(),wae=QF(),Cae=Hy(),gc=sM(),CM=Symbol("cds-maker-sdk.committedWrite");function Eae(e){return typeof e=="object"&&e!==null&&(e[CM]=!0),e}function Aae(e){return typeof e=="object"&&e!==null&&e[CM]===!0}var Sae={fileConcurrency:1},jv="SOLUTION_COMPONENT_UNCLASSIFIED",Nae=2,_ae=4,Tae="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 mM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Tae}:{}}}function hM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Po(t)}}function gM(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,pr.nowIso)(),isDirty:!1}}var Dae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function Iae(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,Oa.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 Oae(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 wM.WorkspaceManager(Rae,e.instanceUrl,(0,uae.assertStorageContract)(t))}mr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Pae="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";mr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Rae="<injected workspaceStorage>",rm=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,zv.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:bae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:vae,this.compiler={load:(0,hae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Oae(t),this.versions=new cl.VersionManager(this.workspace),this.dataverse=new cae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new pae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,yae.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,yn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,pr.nowIso)()},b)}return(0,fi.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:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.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,fi.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,er.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(mM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(gM(a,o,s))}catch(a){i.push(hM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,pr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,zv.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(mM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(gM(a.type,o,s))}catch(a){n.push(hM(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,Sae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,zv.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,dl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,dae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,dl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,fae.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,dl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Rt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Rt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Wv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Wv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Rt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Rt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Rt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Rt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Rt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Rt.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,Oa.xmlText)(t)}</entity></entities></importexportxml>`;(0,pr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Rt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Rt.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,Rt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Rt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Rt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,gc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,gc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,gc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,gc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,gc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,ji.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,ji.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,ji.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,ji.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,ji.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,ji.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,ji.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,wae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,pM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,pM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,gae.deleteAppCascade)(this.dataverse,t,r),i=(0,Oa.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,ji.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,ji.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,em.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,em.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,em.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,em.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,fl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,fl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:mae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,fl.setAppSetting)(this.dataverse,t,fl.HEADER_AND_NAVIGATION_REFRESH,r?fl.APP_SETTING_ON:fl.APP_SETTING_OFF)}getSolution(t){return(0,er.getSolution)(this.dataverse,t)}createPublisher(t){return(0,er.createPublisher)(this.dataverse,t)}createSolution(t){return(0,er.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,er.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,er.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,er.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,er.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,er.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,er.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,er.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,wM.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,yn.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=gn.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,lae.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=gn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Hi(s)&&Hi(i)?{...s,...i}:i;return gn.JsonPointer.set(a,n,(0,fi.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=gn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Hi(l)||!Hi(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,fi.cloneJson)(i[f]),p=(0,tm.isValueMapKey)(f)||(0,tm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Hi(h)?this.assignMissingIds(t,h):h):Hi(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))gn.JsonPointer.set(s,gn.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,tm.pointerTouchesValueMap)(n)?(0,fi.cloneJson)(i):this.assignMissingIds(t,(0,fi.cloneJson)(i)),c=xae(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=gn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=gn.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");gn.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),vM(c);let f=gn.JsonPointer.resolve(l,bM(n));return Array.isArray(f)&&f!==c&&vM(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(gn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return gn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,bM(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,pl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,pl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,pl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,pl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,pl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,pl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Cae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,uM.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&&Aae(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,fi.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=Iae(a),f;if(d)try{await(0,uM.publishXml)(this.dataverse,d)}catch(p){f=Po(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||!Dae.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,yn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Po(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,pr.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||!kae(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,yn.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,pr.isVersionToken)(o)||!EM(a,t.heldSiblings)||!AM(a)||!(o!==t.heldEtag||!(0,yn.deepEqual)(a??void 0,t.heldSiblings))||!(0,yn.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,pr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Po(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,yn.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,yn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,pr.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,Oa.normalizeGuid)(r,"id")})${(0,Oa.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:Po(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,yn.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,yn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Po(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),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,dl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg: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 O=await this.createWithMintedId(m,d,f,g,p);if("adopted"in O)return await this.persistAdoption(d,f,p,O.adopted);w=O.written}b=!0;let E=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),E=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,P=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,E,P.artifact,h&&E===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,yn.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,E,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,E,{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:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(P.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},E===f?h:void 0),{type:d,id:E,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var O;let x=(O=m.publishScope)===null||O===void 0?void 0:O.call(m,E,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let E=(0,Z.readPartialTokens)(w);if(E&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},P={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(P).length>0?{siblingEtags:P}:{}},h)}if(w instanceof Z.SdkError&&w.code===mr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===lM.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===lM.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===pr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,fM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Eae(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==cl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${cl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Wv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,dM.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(mr.ALREADY_EXISTS_CODE,Hv(r,n,u)+(this.createRecovery==="adoptExact"?` ${yM(Pae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==pr.VERSION_CONFLICT_CODE||(0,fM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,dM.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(mr.ALREADY_EXISTS_CODE,`${Hv(r,n)} ${yM(l.refused)}`)}throw new Z.SdkError(mr.ALREADY_EXISTS_CODE,Hv(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,yn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=dl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(O=>O.entityLogicalName===L).map(O=>O.fieldName);try{let O=await(0,dl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(O.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,O,x;return(O=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&O!==void 0?O:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,E=!((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),P=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:$ae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...E!==void 0?{baseLanguageCode:E}:{},...P?{pcf:P}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,cM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,cM.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(mr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,tm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case er.SolutionComponentType.SavedQuery:return"view";case er.SolutionComponentType.SavedQueryVisualization:return"chart";case er.SolutionComponentType.AppModule:return"app";case er.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case er.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,Zp.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(jv,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Zp.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,Oa.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,Oa.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,pr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,Zp.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(jv,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Nae)return"businessRule";if(a===_ae){let s=(0,Zp.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(jv,`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}};mr.MakerSdk=rm;function Lae(e){return new rm(e)}mr.createMakerSdk=Lae;function Po(e){return e instanceof Error?e:new Error(String(e))}function EM(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 AM(e){return Object.values(e??{}).every(pr.isVersionToken)}function kae(e,t){return EM(e,t)&&AM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function yM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Hv(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 $ae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function vM(e){e.length===0||!e.every(t=>Hi(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function xae(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=>Hi(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Hi(n)&&n.id===t.after);return r<0?e.length:r+1}});var NM=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.ARTIFACT_TYPES=void 0;nm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var TM=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0})});var IM=v(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0})});var PM=v(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0})});var LM=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0})});var $M=v(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0})});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(ce=>{"use strict";var Fae=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ge=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Fae(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Mae=SM();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Mae.createMakerSdk}});Ge(NM(),ce);Ge(TM(),ce);Ge(IM(),ce);Ge(PM(),ce);Ge(LM(),ce);Ge($M(),ce);Ge(FM(),ce);Ge(UM(),ce);Ge(qM(),ce);Ge(GM(),ce);Ge(zM(),ce);Ge(HM(),ce);Ge(JM(),ce);Ge(QM(),ce);Ge(ZM(),ce);Ge(Rd(),ce);Ge(tU(),ce);Ge(nU(),ce);Ge(oU(),ce);Ge(sU(),ce);Ge(uU(),ce);Ge(dU(),ce);Ge(pU(),ce);Ge(Q(),ce);var mU=Al();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return mU.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return mU.projectConnectorOperationSchema}})});var Jv=v(pi=>{"use strict";var Uae=pi&&pi.__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]})),Bae=pi&&pi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),bU=pi&&pi.__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)&&Uae(t,e,r);return Bae(t,e),t};Object.defineProperty(pi,"__esModule",{value:!0});pi.NodeFileSystemStorage=void 0;var vt=bU(require("fs")),tr=bU(require("path")),gU=Q(),yU=Rm();async function vU(e){let t;try{t=await vt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await vt.promises.unlink(e)}catch{await vt.promises.rmdir(e)}return}if(!t.isDirectory()){await vt.promises.unlink(e);return}for(let r of await vt.promises.readdir(e))await vU(tr.join(e,r));await vt.promises.rmdir(e)}var Kv=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(tr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!vt.existsSync(r);){n.unshift(tr.basename(r));let i=tr.dirname(r);if(i===r)return tr.resolve(t);r=i}return tr.resolve(vt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=tr.resolve(this.root),i=tr.resolve(t);if(i!==n&&!i.startsWith(n+tr.sep))throw new gU.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):tr.resolve(this.realPathThroughNearestAncestor(tr.dirname(i)),tr.basename(i));if(a!==o&&!a.startsWith(o+tr.sep))throw new gU.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!vt.existsSync(r))return null;try{return await(0,yU.retryTransientIoAsync)(()=>vt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=tr.dirname(n);await vt.promises.mkdir(i,{recursive:!0});let o=tr.join(i,`.${tr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await vt.promises.writeFile(o,r,"utf8"),await(0,yU.retryTransientIoAsync)(()=>vt.promises.rename(o,n))}catch(a){try{vt.existsSync(o)&&await vt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);vt.existsSync(r)&&await vt.promises.unlink(r)}async deleteByPrefix(t){await vU(this.pathFor(t,!1))}async ensureContainer(t){await vt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return vt.existsSync(this.pathFor(t))}};pi.NodeFileSystemStorage=Kv});var wU=v(xr=>{"use strict";var qae=xr&&xr.__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]})),Vae=xr&&xr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Gae=xr&&xr.__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 Vae(t,e),t};Object.defineProperty(xr,"__esModule",{value:!0});xr.loadNodeTypeScript=xr.createNodeWorkspaceStorage=xr.NodeFileSystemStorage=void 0;var Wae=Jv(),zae=Jv();Object.defineProperty(xr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return zae.NodeFileSystemStorage}});function jae(e){return new Wae.NodeFileSystemStorage(e)}xr.createNodeWorkspaceStorage=jae;async function Hae(){return await Promise.resolve().then(()=>Gae(require("typescript")))}xr.loadNodeTypeScript=Hae});var Ki={};module.exports=Fr(Ki);Ji(Ki,Ee(hU()),module.exports);Ji(Ki,Ee(wU()),module.exports);diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex 8b5d7b4e5..00ed38040 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -20,18 +20,34 @@// A language is also one the form's READ may not carry. The platform decides which languages' labels go into the FormXML a caller reads, and it can// return fewer than the form stores (live: a form built with Spanish captions in an English-language organization, the Spanish captions stored, reads// back with every label in English). When no label of the form's FormXML is in the language a label is compared in, that label is not missing — the read-// cannot show it — and it is listed under `unverified` as well, with the languages the read does carry and what to do (check it in Power Apps with that-// language, or, for a label written as a string, verify in a language the read carries); a label map is compared at the languages the read carries and-// listed for the others. A language the read does carry is compared strictly, as ever. Translations are not read another way (a translation export,-// RetrieveLocLabels): what a caller's FormXML cannot show is not verified.+// cannot show it — so it is read from a TRANSLATION EXPORT of the app's solution instead: one `ExportTranslation` request (readerFor's translationLabels,+// lib/translation-labels.js), made only when such a caption is there to check and shared by the whole run, which carries every provisioned language — the+// published layer — keyed by the id of each tab and section. A caption it shows right passes and one it shows different, or not at all, is a mismatch.+// What it cannot settle (the export fails or cannot be read, or has no row for the element) is listed under `unverified` as before, with the reason, the+// languages the read does carry and what to do (check it in Power Apps with that language, or, for a label written as a string, verify in a language the+// read carries); a label map is compared at the languages the read carries, and for the others the same way. A language the read does carry is compared+// strictly, as ever, from the read. COST: the export is one request — 7.5–11.2 s for a solution of one table, more as the solution grows, because it+// exports every label of it — sent once and never again on a throttled or unavailable answer; a run with no such caption makes none.//// Result JSON: { ok, present, total, missing, errors } and, only when a check could not be decided, `unverified: [ "<kind>:<name> (<reason>)" ]`.// `unverified` does not change `ok` or the exit status.+//+// Every `WARNING:` line this prints on stderr is also in the result, as the optional `warnings: [ "<message>" ]`: the same messages, without the prefix,+// in the order they were printed, and left out when there is none. They are the spec's own (validateAppSpec's — among them the findings that verification+// alone downgrades from errors to warnings: a relationship-name collision and the two column rules) and, last, a page workspace the run could not remove.+// A caller that reads only the JSON would otherwise lose what a person reads on stderr. `warnings` does not change `ok` or the exit status, and it is there+// on a failed verification and on a refused spec ({ ok: false, errors, warnings }) as on a passed one. A run that stops on an unexpected error prints that+// error on stderr and no JSON, as ever.+//+// The result is pure ASCII: every character above U+007E — the em dash of a warning, a Spanish label or a Japanese form name in a message, an accented folder name — is a `\uXXXX`+// escape, which any JSON parser reads back as the original text. A raw one is garbled by the code page of the console that captures it (Windows PowerShell 5.1 reads a child's+// stdout as OEM text), and an agent reads this off a console. stderr is for people and is not escaped.const fs = require('node:fs');const path = require('node:path');const { parseArgs, validateFlags, readLanguageCodeFlag, readJsonArg, emitResult, dataverseOrigin } = require('./lib/dataverse-auth.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');+const { readTranslationLabels, isTranslationExport } = require('./lib/translation-labels.js');const { verifySpec } = require('./lib/verify-spec.js');const { readBaseline } = require('./lib/deployed-baseline.js');const { appUniqueName } = require('./lib/sdk-build.js');@@ -47,6 +63,9 @@ const { depthFromMask } = require('./lib/role-privileges.js');const { appEntityComponentsFor, appMainFormsFor, appComponentRows } = require('./lib/app-components.js');const { readChoiceAttributes } = require('./lib/view-filter-labels.js');const { sameFormXmlAcrossLayers } = require('./lib/formxml-layers.js');+// The app's id and the ids of the roles associated with it live in lib/app-roles.js: the design document reads the same relationship. Still exported from here.+const { appIdFor, appRoleIdsFor } = require('./lib/app-roles.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// An SDK on a THROWAWAY workspace — a temporary folder `dispose()` removes — and never on the app folder's own.//@@ -110,36 +129,6 @@ async function sitemapXmlFor(sdk, appUnique) {return (sms && sms[0] && sms[0].sitemapxml) || '';}-// Resolve the app module id from its unique name.-async function appIdFor(sdk, appUnique) {- const rows = await sdk.queryRecords('appmodule', { select: ['appmoduleid'], filter: `uniquename eq '${odataLit(appUnique)}'`, top: 1 });- return rows && rows[0] && rows[0].appmoduleid;-}--async function appRoleIdsFor(sdk, appUnique) {- try {- const appId = await appIdFor(sdk, appUnique);- if (!appId) return { ok: false, reason: `app '${appUnique}' could not be resolved` };- if (!sdk.dataverse || typeof sdk.dataverse.get !== 'function') return { ok: false, reason: 'SDK dataverse reader is unavailable' };- // The SDK has associate/disassociate helpers for `appmoduleroles_association`, but no modeled- // read for that N:N membership. Read the relationship navigation property directly so verify- // proves the deployed app<->role rows the model-driven app launcher uses, rather than inferring- // access from role existence or from the build result.- // See appmodule relationships: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule- const res = await sdk.dataverse.get(`/appmodules(${appId})/appmoduleroles_association?$select=roleid`);- if (!res || res.status < 200 || res.status >= 300) return { ok: false, reason: `HTTP ${res && res.status}` };- return {- ok: true,- roleIds: ((res.body && res.body.value) || [])- .map((r) => r && r.roleid)- .filter(Boolean)- .map((id) => String(id).toLowerCase()),- };- } catch (err) {- return { ok: false, reason: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };- }-}-// How many pages readerFor's pageCodes reads at once. A page read is its rows' bytes and its conversation, a handful of requests, so a few at a// time keeps a verify of a large app quick without opening a wide fan of requests against one environment.const PAGE_READ_CONCURRENCY = 4;@@ -353,6 +342,11 @@ function readerFor(sdk, appUnique, opts) {const row = rows && rows[0];return (row && row.formxml) || null;},+ // translationLabels(solutionUniqueName): the captions of the solution's forms in EVERY provisioned language, from ONE translation export of the solution+ // (lib/translation-labels.js) — what a tab's or a section's caption is compared with in a language the form's own read does not carry. Answers+ // { ok: true, languages, lookup } or { ok: false, reason } and never throws. verifySpec asks for it at most once a pass, and only when a caption needs it; it is not cached+ // here, because the reader is reused across verifies and the export is the published layer, which a later verify must see change.+ translationLabels: (solutionUniqueName) => readTranslationLabels(sdk.dataverse, solutionUniqueName),// servedMainForms(entity): the Main forms the platform serves the user running verify for a table,// first to last — the order a user without a remembered form opens them in (AB#6736948). The public// RetrieveFilteredForms function is the platform's own answer to "which forms may this user open,@@ -399,6 +393,14 @@ function readerFor(sdk, appUnique, opts) {// differs — a tile, a cell, an attribute, a label in a language it carries — is a change, and a FormXML that is not// one well-formed XML document is one too. Two equal texts are the same dashboard, as before.//+ // For a user whose own language is the organization's second one, the published read carries both languages, the+ // user's own first, and words a caption another way than the draft read does, on a dashboard nothing has written since+ // its publish — so no text says that it is the published one. The platform does: the published row and the draft each+ // answer an `@odata.etag`, the same one until the draft is written (live-measured; the row's `queryRecords` answer carries+ // it beside the FormXML). When the two are the same and the published read carries more than one language, the reads+ // are compared in everything but their captions: a tile that differs is still a change. With another token, none, or a+ // published read of one language (a user of the base language), the rule above decides, as it always did.+ //// Equal FormXML before and after does not prove the fetch between them read it: a draft saved and then put// back (A, then B, then A again) leaves both checks reading A while the fetch read B, and B's tiles passed. So// each check also takes the draft's `@odata.etag`, which RetrieveUnpublished returns in the body and which@@ -416,8 +418,8 @@ function readerFor(sdk, appUnique, opts) {if (!draft || draft.status < 200 || draft.status >= 300) throw new Error(`the draft of dashboard ${dashboardId} could not be read (HTTP ${draft && draft.status})`);const draftXml = draft.body && draft.body.formxml;if (!row || typeof row.formxml !== 'string' || typeof draftXml !== 'string') throw new Error(`the FormXML of dashboard ${dashboardId} could not be read`);- if (!sameFormXmlAcrossLayers(row.formxml, draftXml)) throw new Error(`dashboard ${dashboardId} has changes that are not published — publish it, then verify`);const version = draft.body['@odata.etag'];+ if (!sameFormXmlAcrossLayers(row.formxml, draftXml, { published: row['@odata.etag'], saved: version })) throw new Error(`dashboard ${dashboardId} has changes that are not published — publish it, then verify`);if (typeof version !== 'string' || version === '') throw new Error(`the version of dashboard ${dashboardId} could not be read`);return { xml: row.formxml, version };};@@ -583,6 +585,11 @@ function readerFor(sdk, appUnique, opts) {return base;}+// An agent reads the result off a console, and Windows PowerShell 5.1 decodes a child's stdout with the OEM code page: the UTF-8 bytes of an em dash in a warning reach it as three other+// characters, and a Spanish label or a Japanese form name in a message as others still. `ascii` writes every character above U+007E as a `\uXXXX` escape instead — the same JSON to any+// parser, and nothing a code page can garble (asciiJson in lib/dataverse-auth.js). It is for the result only: stderr is for people and is written as it is.+const RESULT_AS_ASCII = { ascii: true };+async function main() {const argv = process.argv.slice(2);const { positional, flags } = parseArgs(argv);@@ -595,6 +602,7 @@ async function main() {needValue: ['env', 'spec', 'workspace', 'language-code', 'languageCode'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -613,6 +621,7 @@ async function main() {try {languageCode = readLanguageCodeFlag(flags);} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${err.message}\n${USAGE}\n`);process.exit(1);}@@ -628,8 +637,17 @@ async function main() {// `required: "true"` made not required) must still reach its deployment. The warning names the column and the fix for the next build. Not the// structural profile: that would also skip the checks of pages and forms that verification relies on.const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn' });- if (!v.ok) { emitResult(false, { ok: false, errors: v.errors }); return; }- for (const w of v.warnings || []) process.stderr.write(`WARNING: ${w}\n`);+ // A warning is printed for a person and kept for the result JSON in one step, so the two cannot differ: a caller that reads only the JSON must not+ // lose what stderr says. The spec's are found before it is judged, so a spec that is refused reports the warnings it also has.+ const warnings = [];+ const warn = (message) => {+ warnings.push(message);+ process.stderr.write(`WARNING: ${message}\n`);+ };+ // A refused spec ends the run right after its warnings, so they are made blocking first (lib/output-redaction.js).+ if (!v.ok) makeWritesBlocking(process.stdout, process.stderr);+ for (const w of v.warnings || []) warn(w);+ if (!v.ok) { emitResult(false, { ok: false, errors: v.errors, ...(warnings.length ? { warnings } : {}) }, RESULT_AS_ASCII); return; }const workspaceDir = workspaceArg || path.join(path.dirname(specPath), '.maker-workspace');// Only the build's baseline is READ from here, so nothing is created: a folder that does not exist (or cannot be// inspected) is simply one with no baseline. A LINK at the folder is still refused, as everywhere else the plugin@@ -642,7 +660,8 @@ async function main() {return;}}- const httpClient = createAzHttpClient(env);+ // The one request this run sends once whatever answers it is the translation export (isTranslationExport): a long action, which a re-send would run a second time.+ const httpClient = createAzHttpClient(env, { sendOnce: isTranslationExport });// The SDK works in a throwaway workspace (see throwawaySdk), never the app folder's `.maker-workspace`: verify// must run against any environment the app is deployed to, whichever one that folder was built against.const session = await throwawaySdk(env, httpClient, 'verify-');@@ -668,7 +687,7 @@ async function main() {try {if (genpage && typeof genpage.dispose === 'function') {const leftOnDisk = leftOnDiskWarning(await genpage.dispose({ waitMs: PAGE_READS_END_WAIT_MS }));- if (leftOnDisk) process.stderr.write(`WARNING: ${leftOnDisk}\n`);+ if (leftOnDisk) warn(leftOnDisk);}} catch { /* best-effort */ }session.dispose();@@ -676,6 +695,8 @@ async function main() {// Show `detail` on a failing check. Without it a READ that failed (throttling, auth expiry, a 5xx)// is indistinguishable from an artifact that is genuinely absent — verifySpec records the cause// but the operator saw only "✗ view: Active Orders" and would chase a phantom deployment drift.+ // The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);for (const c of r.checks) process.stderr.write(` ${c.present ? '✓' : '✗'} ${c.kind}: ${c.name}${!c.present && c.detail ? ` — ${c.detail}` : ''}\n`);process.stderr.write(`\n${r.ok ? '✓ verify PASS' : `✗ verify FAIL — ${r.missing.length} missing`} (${r.checks.length - r.missing.length}/${r.checks.length} present)\n`);// What verify could not DECIDE is neither a pass nor a failure: listed beside the verdict, with its reason, so a green run never reads as@@ -687,7 +708,9 @@ async function main() {}// Include `errors` (alias of missing) so emitResult's failure note reports an accurate count.const missing = r.missing.map((m) => `${m.kind}:${m.name}${m.detail ? ` (${m.detail})` : ''}`);- emitResult(r.ok, { ok: r.ok, present: r.checks.length - r.missing.length, total: r.checks.length, missing, errors: missing, ...(unverified.length ? { unverified } : {}) });+ // `warnings` repeats the `WARNING:` lines printed above for a caller that reads only this JSON. Like `unverified` it is left out when there is none, and it changes+ // neither `ok` nor the exit status.+ emitResult(r.ok, { ok: r.ok, present: r.checks.length - r.missing.length, total: r.checks.length, missing, errors: missing, ...(unverified.length ? { unverified } : {}), ...(warnings.length ? { warnings } : {}) }, RESULT_AS_ASCII);}if (require.main === module) {diff --git a/plugins/model-apps/scripts/write-app-spec-doc.js b/plugins/model-apps/scripts/write-app-spec-doc.jsindex 3d898e636..73e3fe4fc 100644--- a/plugins/model-apps/scripts/write-app-spec-doc.js+++ b/plugins/model-apps/scripts/write-app-spec-doc.js@@ -11,21 +11,33 @@// node write-app-spec-doc.js --spec @<working-dir>/app-spec.json [--env <orgUrl>] [--out <path>]//// Output: { "ok": true, "docPath": "...", "bytes": N, "warnings": [...] }-// `warnings` echoes the design gaps rendered into the document (no jobs, unmapped jobs, no pages) so-// the orchestrator can surface them in chat rather than leaving them buried in a file the user may-// not open.+// `warnings` echoes the design gaps rendered into the document (no jobs, unmapped jobs, no pages, a new table no role is+// given access to, and — with --env — what the environment says about who can open the app) so the orchestrator can+// surface them in chat rather than leaving them buried in a file the user may not open.+//+// --env <orgUrl> labels the document with the environment AND reads, read-only, which security roles the app has associated+// with it there (lib/app-roles.js), so the document can say who can already open the app and keep that apart from the privileges+// on the tables the spec introduces. A spec with no personas[] authors no role, and who can open an app that already exists is+// decided by the roles associated with it — so without the read the document says what the spec authors and nothing more.+// The read never costs the document: a read that cannot be made (no sign-in, no permission, a URL that is no Dataverse+// environment) is reported in the document and in `warnings` as "not checked", and the command still writes it and exits 0.const path = require('node:path');const { assertSafeOutputDir, writeFileSafe } = require('./lib/safe-fs.js');-const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');+const { parseArgs, validateFlags, readJsonArg, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');const { migrateAppSpec } = require('./lib/app-spec.js');const { renderAppSpecDoc } = require('./lib/app-spec-doc.js');+const { appAccessModel, uncoveredTables, uncoveredTablesWarning } = require('./lib/app-access.js');+const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');+const { appRolesOf } = require('./lib/app-roles.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');-// The same three gaps the document calls out, returned as data. Kept here (not in the pure renderer)+// The design gaps the document calls out, returned as data. Kept here (not in the pure renderer)// because the renderer's contract is "markdown in one string"; the CLI is what talks to the caller.// Shape-guarded for the same reason the renderer is: this runs against work-in-progress specs during// authoring, and it must not be the thing that crashes the flow.-function designGaps(spec) {+// `opts` is what the renderer was given: { envUrl, appAccess } — `appAccess` the answer of a read of the environment (lib/app-roles.js), absent without --env.+function designGaps(spec, opts = {}) {const out = [];const s = spec && typeof spec === 'object' ? spec : {};const personas = Array.isArray(s.personas) ? s.personas.filter((p) => p && typeof p === 'object') : [];@@ -33,7 +45,11 @@ function designGaps(spec) {.filter((j) => j && typeof j === 'object').map((j) => ({ persona: p.persona, job: j })));if (!jobs.length) {- out.push('no jobs-to-be-done captured (personas[] is empty) — the app has no recorded purpose and will open only for admins');+ // What is true of the spec — it records no jobs and, with no personas, authors no role — and not what the deployed app does: who can open it is decided+ // by the roles associated with it (lib/app-access.js), which a spec that authors none leaves as they are.+ out.push(personas.length+ ? 'no jobs-to-be-done captured (the personas declare no jobs) — the app has no recorded purpose'+ : 'no jobs-to-be-done captured (personas[] is empty) — the app has no recorded purpose, and this spec authors no security role, so it does not say who can open the app');}const unmapped = jobs.filter(({ job }) => !(Array.isArray(job.surfaces) && job.surfaces.length));if (unmapped.length) {@@ -49,15 +65,70 @@ function designGaps(spec) {if (undescribed.length) {out.push(`${undescribed.length} table icon(s) have no description (${undescribed.join(', ')}) — the user cannot approve an icon they cannot picture`);}+ const withoutAccess = uncoveredTables(s);+ if (withoutAccess.length) out.push(uncoveredTablesWarning(withoutAccess));++ // What the environment said (--env), from the same model the document is written from. The administrator-only conclusion is drawn here, and only here, on that+ // evidence: the app has no role (or does not exist yet) AND no persona of this spec gets it — a persona that opts out (`appAccess: false`) is a role the build+ // does not associate.+ const model = appAccessModel(s, opts && opts.appAccess);+ const where = opts && typeof opts.envUrl === 'string' && opts.envUrl.trim() ? opts.envUrl.trim() : 'the environment';+ const app = model.appUnique ? `app '${model.appUnique}'` : 'the app';+ const noPersonaGetsApp = model.personas.gets.length === 0;+ if (model.state === 'unreadable') {+ out.push(`the roles associated with ${app} could not be read from ${where} (${model.reason}) — who can open it was not checked`);+ } else if (model.state === 'absent' && noPersonaGetsApp) {+ out.push(`${app} does not exist in ${where} yet and this spec associates no role with it, so once built it opens only for administrators and other makers until a role is associated with it`);+ } else if (model.state === 'read') {+ if (!model.roles.length && noPersonaGetsApp) {+ out.push(`${app} exists in ${where} with no role associated with it, so only administrators and other makers can open it, and this spec associates none with it`);+ }+ // A grant whose role is certainly not among the app's. One that names only a name and has a role of that name among them is not said: which role it is cannot be told.+ for (const grant of model.grants) {+ if (grant.status === 'not-associated') {+ out.push(`roleGrants[] role "${grant.label}" is not among the roles associated with ${app}, so its users get the privileges but may not be able to open the app`);+ }+ }+ }return out;}-function main() {+// What the environment holds of the app's roles, for the app this spec names. Never throws and never writes: a read that cannot be made is an answer+// ({ state: 'unreadable', reason }) the document words as "not checked" — `--env` has only ever labelled the document, and must not start to fail it.+async function discoverAppAccess(env, spec) {+ const s = spec && typeof spec === 'object' ? spec : {};+ const named = s.app && typeof s.app === 'object' && !Array.isArray(s.app) ? s.app : {};+ const prefix = s.solution && typeof s.solution === 'object' ? s.solution.publisherPrefix : undefined;+ const hasText = (v) => typeof v === 'string' && v.trim() !== '';+ // appUniqueName derives `<prefix>_<name>` and does not refuse a spec that has no name: it would look up an app called "contoso_undefined".+ if (!hasText(named.uniqueName) && !(hasText(named.name) && hasText(prefix))) {+ return { state: 'unreadable', appUnique: '', reason: 'the spec does not name the app (it needs app.uniqueName, or app.name and solution.publisherPrefix)' };+ }+ // Loaded here, not when the module does: it is the build engine's own derivation (app.uniqueName, else the publisher prefix and the app's name), so the+ // app looked up is the app the build would find — and the engine is a large module that a run without --env has no use for.+ const { appUniqueName } = require('./lib/sdk-build.js');+ const appUnique = appUniqueName(s);+ let origin;+ try {+ origin = requireDataverseOrigin(env);+ } catch (err) {+ return { state: 'unreadable', appUnique, reason: String(err.message).slice(0, 200) };+ }+ try {+ return await withThrowawaySdk({ env: origin, prefix: 'app-doc-' }, (make) => appRolesOf(make(), appUnique));+ } catch (err) {+ // The HTTP client could not be made, or the SDK would not start: appRolesOf answers its own failures, so this is what is left.+ return { state: 'unreadable', appUnique, reason: (err && err.message ? String(err.message) : 'read failed').slice(0, 200) };+ }+}++async function main() {const argv = process.argv.slice(2);const { positional, flags } = parseArgs(argv);const USAGE = 'Usage: node scripts/write-app-spec-doc.js --spec @<app-folder>/app-spec.json [--env <orgUrl>] [--out <path>]';const flagError = validateFlags(argv, { known: ['spec', 'env', 'out'], needValue: ['spec', 'env', 'out'] });if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}@@ -76,10 +147,13 @@ function main() {return;}- const markdown = renderAppSpecDoc(spec, { envUrl: flags.env });+ // The environment is read only when --env was given, and before anything is rendered: both the document and the warnings say what it answered.+ const opts = { envUrl: flags.env };+ if (flags.env) opts.appAccess = await discoverAppAccess(flags.env, spec);+ const markdown = renderAppSpecDoc(spec, opts);// Compute the gaps BEFORE writing: a failure here used to leave a written document behind and then// exit with a raw stack, so the caller saw a crash next to a file that looked fine.- const warnings = designGaps(spec);+ const warnings = designGaps(spec, opts);// Default next to the spec, which is the working directory the skill created in Phase 0.const docPath = flags.out ? path.resolve(flags.out) : path.join(path.dirname(specPath), 'model-app-plan.md');// A link at the document directory, or at the document name, would put the plan wherever@@ -95,6 +169,6 @@ function main() {emitResult(true, { ok: true, docPath, bytes: Buffer.byteLength(markdown, 'utf8'), warnings });}-if (require.main === module) main();+if (require.main === module) main().catch((err) => emitResult(false, err instanceof Error ? err : new Error(String(err))));-module.exports = { main, designGaps };+module.exports = { main, designGaps, discoverAppAccess };diff --git a/plugins/model-apps/scripts/write-page-plan.js b/plugins/model-apps/scripts/write-page-plan.jsindex bec512a3f..771e1c805 100644--- a/plugins/model-apps/scripts/write-page-plan.js+++ b/plugins/model-apps/scripts/write-page-plan.js@@ -29,6 +29,7 @@ const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/datconst { migrateAppSpec } = require('./lib/app-spec.js');const { buildPagePlan, pageKey, pageFile, planFile, pageDataMode, mdText } = require('./lib/page-plan.js');const { pageFileProblems } = require('./lib/page-file-targets.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');function main() {const argv = process.argv.slice(2);@@ -43,6 +44,7 @@ function main() {needValue: ['spec', 'working-dir', 'env', 'app', 'languages'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 27ff42426..b90c7564f 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -1,7 +1,7 @@---name: app-builderversion: 1.0.0-description: Builds and edits a model-driven Power Apps app from a natural-language intent — tables, columns, relationships, adaptive forms with sub-grids, views, Choice-column charts, business rules, business process flows, generative page intents for overview/dashboard surfaces (page `.tsx` generated in generate-pages after plan approval), and an app module + sitemap — via the headless cds-maker-sdk. Runs an interactive, multi-turn authoring flow (env selection, jobs-to-be-done first, then design-only App Spec authoring across confirmed levels, guardrail lint, plan-mode approval, generate-pages, full build) and a narrated build, and can download a deployed app back into an editable spec to change it. Use when the user says "build an app for X", "create a model-driven app", "make me an app to manage Y", "add a business process flow", or "edit/add to my app". This skill stands alone and does not require /genpage — but for a standalone generative page added to an app that already exists, use /genpage instead.+description: Builds and edits a model-driven Power Apps app from a natural-language intent — tables, columns, relationships, adaptive forms with sub-grids, views, Choice-column charts, business rules, business process flows, generative page intents for overview/dashboard surfaces, and an app module + sitemap. Runs an interactive authoring flow with plan approval and can download a deployed app back into an editable spec to change it. Use when the user says "build an app for X", "create a model-driven app", "make me an app to manage Y", "add a business process flow", or "edit/add to my app". Do not use it for a generic web or React app or website, Power Pages, canvas apps, or Power Automate, or when the user rules out Power Platform, Dataverse, or model-driven apps (for example "no Power Platform"). This skill stands alone and does not require /genpage — but for a standalone generative page added to an app that already exists, use /genpage instead.author: Microsoft Corporationargument-hint: "<app description>"user-invocable: true@@ -260,8 +260,12 @@ unless destructive authority was supplied independently.```It writes `<working-dir>/model-app-plan.md` (jobs → surfaces traceability, data model, everysurface, navigation, access model, sample data) and prints `{ ok, docPath, bytes, warnings }`.- **Surface those `warnings`** — they name design gaps such as a job with no covering surface or an- app with no generative pages. Tell the user where the document is; it's theirs to keep, and it's+ **Surface those `warnings`** — they name design gaps such as a job with no covering surface, an+ app with no generative pages, or a new table that no persona and no `roleGrants[]` entry grants a+ privilege on. With `--env` the document also lists, read-only, the roles the app already has+ associated with it, apart from the privileges on the tables the spec adds (opening the app and using+ a table are two questions); a read that fails is reported in the document as "not checked" and does+ not fail the command. Tell the user where the document is; it's theirs to keep, and it'sregenerable after any spec edit.### Phase 1.5 — Generate pages (main loop, headless workers)@@ -446,19 +450,22 @@ reason: re-run it with the flag.FormXML carries, and it can return fewer than the form stores: a form built with Spanish (`3082`) captions in anEnglish-language organization reads back, with the Spanish captions stored, with its labels in English only. Verifynever calls a caption missing in a language the read does not carry, as long as the read carries labels in other-languages — it lists the labels compared in that language as-**unverified** (neither passed nor failed; the run's result and exit status are unchanged), naming the languages the-read does carry, and for a `{ "1033": …, "3082": … }` label map it compares the languages the read carries and lists-the others. Say so, and ask the user to check those captions in Power Apps with that language; do not rebuild to-"fix" them. A language the read does carry is still compared strictly: a stale caption in it fails. A form whose read-carries no label at all is not such a case: the captions the spec declares for it are missing, and fail.+languages — it reads those captions from **one translation export of the app's solution** instead (a single extra request,+made only when there is such a caption: 7–11 s for a solution of one table, more as the solution grows; it shows the+published layer), so a right caption passes and a stale or empty one fails like any other, and a+`{ "1033": …, "3082": … }` label map is compared language by language the same way. When the export fails or cannot say (a+failed request, an archive it cannot read, no row for the form), verify lists the labels compared in that language as+**unverified** (neither passed nor failed; the run's result and exit status are unchanged), with the reason and the+languages the read does carry. Say so, and ask the user to check those captions in Power Apps with that language; do not+rebuild to "fix" them. A language the read does carry is still compared strictly, from the read: a stale caption in it+fails. A form whose read carries no label at all is not such a case: the captions the spec declares for it are missing, and fail.Narrate progress as it runs. Transient env errors (a 429 or 503, a customization lock, a concurrent-operationguard or a SQL timeout the service names by its error code, a timeout or reset of the connection) are**auto-retried** with backoff on `--apply` (the build is idempotent, so a retry reuses what's already created).-A throttled service is waited for as long as it asks (`Retry-After`) — by the page writes and by the build's own re-runs of a phase — inside one budget of five minutes per run for the waiting-the build itself adds: when the next wait does not fit, the build stops with a `throttle-budget-exhausted`-halt that says what the service asked — run it again later and it continues. (The HTTP client's own re-sends of a throttled read or publish keep their own, shorter schedule and are not counted in it.) If the build still **halts** (`BuildHalt`) on an+A throttled service is waited for as long as it asks (`Retry-After`) — by the HTTP client's re-sends of a throttled read or publish, by the page writes and by the build's own re-runs of a phase — inside one budget of five minutes per run for all the waiting+a throttle costs: when the next wait does not fit, the build stops with a `throttle-budget-exhausted`+halt that says what the service asked — run it again later and it continues. (A 5xx, a reset connection or a deadlock is not a throttle: those keep their own, shorter schedule and are not counted in it.) If the build still **halts** (`BuildHalt`) on anunrecoverable error, surface it and ask the user how to proceed via `AskUserQuestion` (adjust thespec / cancel), then re-run. Everything is scoped to a dedicated unmanaged solution; **`--publish`gates the final *bulk* publish**, which also carries the edits made to existing views and forms.@@ -528,10 +535,16 @@ node "${PLUGIN_ROOT}/scripts/verify-model-app.js" --env <envUrl> --spec @<workinPass `--language-code` only if the build was run with it. A line starting `⊘` under the verdict is a check verifycould **not decide** (it is in the JSON result's `unverified` list): it is neither a pass nor a failure, so say what it-was and what settles it — the language of the captions, which `--language-code` gives, or a language the environment's-form read does not carry, whose captions only Power Apps can show — never report the run as "everything deployed" while+was and what settles it — the language of the captions, which `--language-code` gives, or captions in a language the environment's+form read does not carry that the translation export could not settle (the line says why), which only Power Apps can show — never report the run as "everything deployed" whileone is listed.+A `WARNING:` line on stderr — each one is repeated in the JSON result's `warnings` list, which is absent when there is+none — is advice, not a verdict: a spec an earlier release accepted that the build would now refuse (it names the column+or relationship and the fix for the next build), or a page workspace the run could not remove (it names the folder to+delete by hand). It changes neither `ok` nor the exit status, so a run that passes can still carry one: pass each on to+the user. A run that stops on an unexpected error prints that error and no JSON.+Then open the app in the browser. Refine `app-spec.json` and re-run Phase 2 to iterate.**Teardown (cleanup).** To remove everything an App Spec built — e.g. a live-verification probe or a@@ -679,6 +692,13 @@ not everything:**- **Does NOT round-trip:** `forms[]`, `views[]`, `charts[]`, `commands[]` — they come back empty.All four **survive on the live app** (a rebuild preserves them by discovery), so a plain edit issafe; they just aren't editable through the downloaded spec. Change them in Maker or a fresh spec.+- **Roles are not in the spec, and a rebuild leaves them as they are.** A download carries no+ `personas[]`: the roles associated with the app stay as the environment has them. Keep `personas[]`+ out when you extend an app whose roles somebody else owns — a persona's role is converged to exactly+ the privileges declared, and a role the build did not author is refused. Give an existing role a new+ table with a `roleGrants[]` entry (additive; it does not associate the role with the app). Lint and+ the design document name each new table no persona and no grant covers, and `write-app-spec-doc.js+ --env` lists the roles the app has.Then:@@ -793,9 +813,9 @@ child view id. Each step emits `[n/total]`.or sort. A changed column type, and an edited command or dashboard, are not re-applied at all; anexisting chart takes only a changed description, an existing app takes a changed name and description(an app that was never published keeps its text and the build warns it was not applied, and so does one whose name or- description is localized — the SDK writes the two together, so while either is localized the header is not edited at- all, a routing description included, and if the SDK's own read of the header fails while one is, the build stops with- `APP_HEADER_NOT_PLAIN_TEXT` before anything is sent or written: re-run it; the icon is set when the app is created: a+ description is localized — only that text is held back: the other text and a routing description are applied, the SDK+ writes only what changed, and a text that is not plain is never sent, even when the SDK's own read of the header fails;+ the icon is set when the app is created: adifferent `app.icon` is reported as not applied), and an existingbusiness process flow takes the stage and step edits that cannot move a record — a stage added or renamed,a step added, renamed, rebound or moved — and refuses, saying why, one that would remove a stage or a stepdiff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.mdindex 980d4a9a5..d724852df 100644--- a/plugins/model-apps/skills/genpage/SKILL.md+++ b/plugins/model-apps/skills/genpage/SKILL.md@@ -1,7 +1,7 @@---name: genpageversion: 2.3.1-description: Creates, updates, and deploys Power Apps generative pages for model-driven apps using React v17, TypeScript, and Fluent UI V9. Orchestrates specialist agents for planning, entity creation, and code generation. Use it when user asks to build, retrieve, or update a page in an existing Microsoft Power Apps model-driven app. Use it when user mentions "generative page", "page in a model-driven", or "genux". This skill stands alone and does not require /app-builder — but if the user wants a whole app built (tables, forms, views, sitemap) rather than pages for an app that already exists, use /app-builder instead.+description: Creates, updates, and deploys Power Apps generative pages for model-driven apps using React v17, TypeScript, and Fluent UI V9. Orchestrates specialist agents for planning, entity creation, and code generation. Use it when user asks to build, retrieve, or update a page in an existing Microsoft Power Apps model-driven app. Use it when user mentions "generative page", "page in a model-driven", or "genux". Do not use it for a generic or standalone React or web app, website, or dashboard (including a Power Apps code app), for Power Pages, canvas apps, or Power Automate, or when the user rules out Power Platform, Dataverse, or model-driven apps (for example "no Power Platform"). A generative page only runs inside a model-driven app, and this skill cannot scaffold a standalone project. This skill stands alone and does not require /app-builder — but if the user wants a whole app built (tables, forms, views, sitemap) rather than pages for an app that already exists, use /app-builder instead.author: Microsoft Corporationargument-hint: "<page description> | edit"user-invocable: true@@ -876,7 +876,10 @@ recorded it: the worker wrote nothing, and what is there is an earlier attempt'sor `genpage-worker-output.js` returns `"ok":false`, do not re-dispatch that worker.Run the Phase 5b page-builder workflow inline for only the failed page, preservingthe same plan and dispatch inputs. This is the same inline fallback path for missing-and invalid worker output. The workers have no shell, so they cannot run the Griffel+and invalid worker output. A `Task tool: none on this host` line in a worker's result+is not a report of that kind: task tracking is optional for a worker+(`references/agent-interaction-contract.md`), and the page is judged by its file and+this gate. The workers have no shell, so they cannot run the Griffelcheck themselves; run it on every generated page, exactly as in step 9 of Phase 5b,```powershell@@ -1175,21 +1178,36 @@ imports the package and applies the settings in the same import. Each prints one`source` (`"sdk"`, or `"pac"` with a `fallback` that says why the SDK did not do the work). The import issent once: a gateway's answer for an import the platform may have accepted is never answered with a second one.The one exception is the platform's refusal to start it because a publish, or another import, holds the-environment's lock (HTTP 429 with one of the customization-lock error codes whose documented text is "Cannot-start …", such as "Cannot start the requested operation [Import] because there is another [Publish] running"):-the script then waits and sends it again under a new job id — only after it has read that no import job exists-for the refused one — in at most five sends and at most five minutes in all, counted from the first refusal to-the last send (10, 20, 40 and 60 seconds between the sends, or the longer wait the platform asks for in-`Retry-After`, in seconds or as a date, waited whole; the time an import the platform accepted then takes is-not counted) — and says so in its output (`importAttempts`, `importRefusals`). A `Retry-After` that does not-fit in what is left of the five minutes ends the retry at once, with no send made early. When the sends or the-time run out the failure is the platform's refusal, with a sentence that says which: run the import again when-the other operation has finished. Every other refusal is sent once, the generic solution-concurrency one-(error code `0x80071151`, documented as an installation or removal that "failed") included. The code decides, not-the words: the platform has been measured to refuse an import that meets another import or a publish with-`0x80071151` and the same "Cannot start the requested operation [Import] because there is another [Publish]-running" words, and that import is sent once — tell the maker to run it again once the other operation has-finished. A secret value+environment's lock: HTTP 429 with one of the customization-lock error codes whose documented text is "Cannot+start …" (such as "Cannot start the requested operation [Import] because there is another [Publish]+running"), or with the generic solution-concurrency code `0x80071151` and a message that begins "Cannot start"+("Cannot start another [Import] because there is a previous [Import] running" is what the platform has been+measured to answer an import that meets another import). The script then waits and sends it again under a new+job id — but only after the refused send's import job has proved that nothing of the package was applied. For+a lock code the job does not exist (the script reads it after the wait). For `0x80071151` the code alone does not+say that nothing started, so the job is read once, at once: it does not exist, or it is finished and its log+says that the import failed with that error before it processed the solution or any component. The sends are at+most five and the time at most five minutes in all, counted from the first refusal to the last send (10, 20,+40 and 60 seconds between the sends, or the longer wait the platform asks for in `Retry-After`, in seconds or+as a date, waited whole; the time an import the platform accepted then takes is not counted) — and the script+says so in its output (`importAttempts`, `importRefusals`, and for `0x80071151` how the job proved it). A+`Retry-After` that does not fit in what is left of the five minutes ends the retry at once, with no send made+early, and a wait that ends after the five minutes (a timer that resumed late) ends it before the next send.+When the time runs out, or the sends run out on a lock code, the failure is the platform's refusal, with a+sentence that says which: run the import again when the other operation has finished. When the sends run out+on a `0x80071151` refusal, the job of that last send was not read, so nothing shows that it applied nothing:+do not run the import again until you have looked up the import job the failure names (`importjobs(<id>)`)+and it does not exist (404), or it is finished (`completedon` set) and its log (`data`) is that of an import+refused at the lock — the root says `succeeded="failure"` and `errorcode="-2147020463"`, every+`solutionManifest` is `processed="false"`, and no element under the root but `upgradeHandler` and+`validateHandler` has a `processed` other than `"false"` — and the other operation has finished; anything+else means the import may be running or may have applied the package.+When the job of a `0x80071151` refusal+proves nothing — it is still running, the import failed after it began, its log is not what is expected, or it+cannot be read — the import is sent once and the failure says why it was not sent again: do not run the import+again until you have looked up the import job it names (`importjobs(<id>)`, or the solution history in Maker)+and it shows that nothing was imported, and the other operation has finished. Every other refusal is sent once,+`0x80071151` with any other words included. A secret valueand a connection id are kept out of what they print — a text that quotes one is withheld, or has itreplaced by `<redacted>` — with these limits: a value of fewer than six characters that is known not to bea secret is not hidden; one whose type is not known (the `pac` route, a name the package does not define)diff --git a/plugins/pcf/CHANGELOG.md b/plugins/pcf/CHANGELOG.mdindex f27f14b70..246a921bb 100644--- a/plugins/pcf/CHANGELOG.md+++ b/plugins/pcf/CHANGELOG.md@@ -10,3 +10,12 @@ First preview release: ships the `/pcf:pcf` skill, matrix-pinned templates and r- Usage telemetry is enabled on model-apps' shared 1DS tenant, with `/pcf:telemetry on|off|status`, regional routing, base fields only and isolated offline coverage.- Guided canvas app setup, including the **Power Apps component framework for canvas apps** environment setting, Studio import/updates, and manual API-limit review; canvas-specific automated checks remain out of scope.++### Changed++- The bundled SDK is the one model-apps 2.17.0 ships (power-platform-ux d603c799); it no longer carries the SDK's PCF control registration, which this plugin never called.++### Fixed++- 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.diff --git a/plugins/pcf/hooks/validate-write-safety.js b/plugins/pcf/hooks/validate-write-safety.jsindex f33e07892..504c01712 100644--- a/plugins/pcf/hooks/validate-write-safety.js+++ b/plugins/pcf/hooks/validate-write-safety.js@@ -46,6 +46,7 @@ if (process.env.PCF_DISABLE_HOOKS === '1' || process.env.PCF_DISABLE_HOOKS === '}const { readUtf8Stream } = require('../scripts/lib/utf8-stream.js');+const { makeWritesBlocking } = require('../scripts/lib/output-redaction.js');function debug(msg) {if (DEBUG) process.stderr.write(`[write-safety] ${msg}\n`);@@ -54,6 +55,7 @@ function debug(msg) {// Non-blocking warning. Exit 1 (not 2) so Claude Code shows this on stderr to the// USER and still lets the write through — the guard flags, it does not block.function warn(userMsg) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`[pcf] ${userMsg}\n`);process.exit(1);}@@ -140,6 +142,7 @@ readUtf8Stream(process.stdin).then((inputData) => {try {input = JSON.parse(inputData);} catch (err) {+ makeWritesBlocking(process.stdout, process.stderr);debug(`stdin parse failed: ${err.message}`);process.exit(0); // never block on hook-side bugs}@@ -169,9 +172,11 @@ readUtf8Stream(process.stdin).then((inputData) => {}}+ makeWritesBlocking(process.stdout, process.stderr);debug(`OK ${toolName} ${extractWritePaths(toolName, toolInput).join(',')}`);process.exit(0);}).catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);debug(`stdin read failed: ${err.message}`);process.exit(0);});diff --git a/plugins/pcf/scripts/check-auth.js b/plugins/pcf/scripts/check-auth.jsindex 385a18a47..47675bbcb 100644--- a/plugins/pcf/scripts/check-auth.js+++ b/plugins/pcf/scripts/check-auth.js@@ -42,6 +42,7 @@const { execFileAsync } = require('./lib/process-runner.js');const { dataverseRequest, getAuthTokenAsync, parseArgs, validateFlags, tokenFailureKind, tokenFailureMessage } = require('./lib/dataverse-auth');const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./lib/cli-failure.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');// `pac org who` cold-starts the PAC CLI's .NET runtime (~7 s measured on Windows), and longer on a busy// machine; a probe that runs out of time is reported as that, never as "not logged in".@@ -107,7 +108,11 @@ function runQuietAsync(cmd, args, timeoutMs) {};}+// The result is a fixed shape whose strings are not bounded: a refused WhoAmI's whole diagnostic is its `message`, and a+// mistyped flag is quoted in a usage blocker. The process exits right after this one write, so the write is made blocking+// first (lib/output-redaction.js makeWritesBlocking): on Linux and macOS a pipe would otherwise take only what fits at once.function emit(payload) {+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify(payload) + '\n');process.exit(0);}diff --git a/plugins/pcf/scripts/lib/dataverse-auth.js b/plugins/pcf/scripts/lib/dataverse-auth.jsindex d96b89396..b53aa626a 100644--- a/plugins/pcf/scripts/lib/dataverse-auth.js+++ b/plugins/pcf/scripts/lib/dataverse-auth.js@@ -8,6 +8,9 @@const { nearestName } = require('./nearest-name.js');const { execFileAsync, runSync, killProcessTree } = require('./process-runner.js');const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./cli-failure.js');+// Every access token read from the Azure CLI below is noted, so that nothing the process writes can carry it (lib/output-redaction.js). That module requires nothing, so it can be required here at the top, which+// lib/sdk-http-client.js — it requires this file — cannot be.+const outputRedaction = require('./output-redaction.js');// Dataverse environment hosts, one family per cloud (the same families power-pages accepts in// scripts/lib/validation-helpers.js, plus the non-numbered `crm<ring>` labels such as crmtest):@@ -138,7 +141,7 @@ function readAzToken(resource, opts = {}) {// re-call returns the same MSAL-cached token (see the ensureOk 401 note below). Reusing that// non-null token within this Node process removes repeated CLI cold-starts without changing// Dataverse semantics; a caller that just saw a 401 passes `{ fresh: true }` to replace it.- if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); }+ if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); outputRedaction.noteToken(token); }else { authTokenMemo.delete(resource); noteTokenFailure(resource, null); }return token;} catch (e) {@@ -191,7 +194,7 @@ function readAzTokenAsync(resource, opts = {}) {// Shares the synchronous helper's memo deliberately: check-auth can pre-warm the token// without blocking the event loop, and later synchronous Dataverse callers in the same// process still avoid a second Azure CLI cold start.- if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); }+ if (token) { authTokenMemo.set(resource, token); tokenFailures.delete(resource); outputRedaction.noteToken(token); }else { authTokenMemo.delete(resource); noteTokenFailure(resource, null); }resolve(token);}@@ -505,6 +508,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})const maxRetries = 2;for (let attempt = 0; attempt <= maxRetries; attempt++) {if (token.length >= MIN_SCRUBBED_TOKEN_LENGTH) tokensSent.add(token);+ outputRedaction.noteToken(token);const headers = {Authorization: `Bearer ${token}`,Accept: 'application/json',@@ -728,8 +732,11 @@ function readJsonArg(raw) {* ok=false + object → JSON payload to stdout (caller can parse partial-failure* details like `errors: [...]`), short note to stderr, exit 1* ok=false + string → string to stderr, exit 1+ * Both streams are made blocking before the first write (makeWritesBlocking, lib/output-redaction.js): the process exits right after the writes, and on Linux and macOS a pipe's+ * writes are otherwise queued, so `process.exit` cut a large result short. It still never returns: the exit follows the writes at once.*/function emitResult(ok, payload) {+ outputRedaction.makeWritesBlocking(process.stdout, process.stderr);if (ok) {process.stdout.write(JSON.stringify(payload) + '\n');process.exit(0);diff --git a/plugins/pcf/scripts/lib/output-redaction.js b/plugins/pcf/scripts/lib/output-redaction.jsnew file mode 100644index 000000000..04441224d--- /dev/null+++ b/plugins/pcf/scripts/lib/output-redaction.js@@ -0,0 +1,638 @@+'use strict';+// Keeps every access token a process obtained out of everything the plugin WRITES.+//+// THE THREAT. A service that rejects or fails a request may repeat the bearer token it was sent in the diagnostic it answers with — whole, or by a part of it (https://www.rfc-editor.org/rfc/rfc7519#section-3) — and+// spelled however the text was made on its way: PLAIN; FOLDED (a gateway wraps a long value onto several lines, a column is wrapped at any width, a console prints a long string in pieces joined by `' +`, a console+// that prints in colours puts its codes between the pieces); or ESCAPED (a JSON body escapes a character as `\u0073` or a line break as `\r\n`, a body that was JSON inside JSON doubles every backslash, util.inspect+// escapes a control character as `\x0b`, and a literal backslash can stand right before a part of the token). A token the process obtained must not reach anything the plugin writes in any of those spellings. The+// service is NOT assumed to be an adversary that has the token and crafts text to defeat the reader (it would not need to: it has the token); a text that tries is refused, not guessed at (see COST).+//+// THE EXPOSURE. A token reaches a script's output when something the process reads quotes it. The SDK quotes a failed part of a `$batch` answer into the error it raises, returns a refused read as a warning, and hands a+// successful answer's data on; and the scripts print that text, journal it and write it into files. The Dataverse HttpClient (lib/sdk-http-client.js) takes the token out of an answer that is not a success — where the text+// holds it literally — but a success is returned byte for byte: a change set the service refuses as a whole is answered HTTP 200 with the one part that failed, and the strict readers that prove from a `$batch` answer what+// a change set did count the bytes each part declares, so the answer cannot be rewritten (what they prove, and the page backend's retry that follows from it, would change). The answer is the caller's.+//+// WHY AT THE OUTPUT. The text has more roads out of the SDK than anyone can list — the message and stack of an error, an object it keeps beneath it (frozen, or with accessors that must not be run to look), a warning in a+// result, a reason, the data of an answer — and every one of them ends in the same few places: the two streams a script prints on and the files it writes. There the text is a string, nothing is walked and no getter is run;+// the SDK's errors, its warnings and the service's answers stay exactly what they were; and a path nobody thought of cannot miss the token. Every token the process OBTAINED is known (a token is noted where it is read from the Azure+// CLI, lib/dataverse-auth.js, and where a client sends it), and none of them is written. The text is read AFTER a formatter made it (an error printed by `console.error` is formatted inside the console, from objects that+// must not be walked), so the reader reads what every formatter in the plugin adds between two characters of a string — white space, the joins and colour codes of util.inspect, escapes — as a fold (see below).+//+// EVERY OUTPUT PATH (sink), and what covers it:+// - stdout and stderr: `process.stdout.write` and `process.stderr.write` are wrapped (guardStream) the moment the first token is obtained — never before, so a process that has no token is untouched. Every `console.*` call+// (in colours too), every script's result printer and warning printer, the build's progress lines, a library's own `console.warn` and the SDK bundle's end there. A text is cleaned as a STRING; bytes (a Buffer) are passed+// as they are: nothing in the plugin writes bytes to a stream, and a test runner's own frames are bytes. `emitResult` (lib/dataverse-auth.js) also cleans its own text, so a result is clean where a caller has replaced the+// stream's `write`. The writes a `process.exit` follows at once are made blocking first (makeWritesBlocking), so that what is written there is whole when the process ends — not only clean.+// - what Node itself prints when an error ends the process (an uncaught exception, an unhandled rejection): it never passes through `process.stderr.write`, so a handler prints it, cleaned, when nothing else handles the error+// (guardFatalErrors).+// - the files the plugin writes: `writeFileSafe` and `appendFileSafe` (lib/safe-fs.js: the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, the plan, the settings template),+// `writeFileAtomic` (lib/apply-snapshot-store.js: the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records) and the SDK's workspace storage — every file the bundle writes goes through its+// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.+// - in the pcf plugin (which carries a copy of this module): its streams and its fatal errors as above (its scripts note their tokens through the same lib/dataverse-auth.js), the receipt `pcf-push.js` writes+// (`pcf-receipt.json`) and the SDK workspace `makePcfSdk` makes; pcf's tests/pcf-push-token.test.js lists every other write of pcf and says why none of them can carry a token.+// - not covered, by design: bytes (a Buffer given to a writer is written as it is); a token another process obtained (`pac` has its own); another encoding of a token (percent-encoding, base64 of a whole header, HTML+// entities — nothing is known to quote a token in one, and a reader that guessed at them would blank ordinary text); a token written in two separate calls to `write` (no script writes a message in pieces); a token a+// formatter CUT SHORT (util.inspect prints at most 10,000 characters of a string, and the end of a part cut off there is not the part); a raw control character other than white space and ESC between two of its characters.+//+// A TOKEN AS A TEXT SPELLS IT. A token is looked for as the text spells it, one character at a time: a character is itself, or an escape of it (`\u0073` for `s`, in either case of hex; `\x73`; `\/` for `/`), and between+// two characters of the token there may be a fold — any white space, a line break and its indentation (the obsolete line folding of https://www.rfc-editor.org/rfc/rfc9112#section-5.2, a column a gateway wrapped), spelled as+// it is or as its escape (`\r\n`, `\t`, `\b`), the quote, plus sign and line break `util.inspect` prints between the pieces of a long string (`'abc\r\n' +` newline `' def'`), a terminal colour code (`\u001b[32m`, also+// among the quote, plus sign and line break), or a STRAY backslash. A run of backslashes before an escape is one escape: a body that was JSON inside JSON holds `\\u0073` and `\\r\\n`. Nothing in a text says whether a+// backslash before a letter is an escape or a literal backslash (`\n` is a line break, or a backslash and the first `n` of a signature), so an escape that can be both is read BOTH ways, and a token found either way is+// the token. The span from the token's first character to its last — the folds and escapes inside it included, an escape always whole — becomes `<token>`, and the white space before and after it stays. In JSON text the+// span is always inside one string and never leaves half of an escape, so what was JSON is still JSON (the baseline and the journal are read back by the next run).+//+// COST. Every needle (the token, and each of its parts of 24 characters or more: needlesOf) is searched in ONE pass over the characters the text spells, as Knuth-Morris-Pratt does, in lockstep, so a text of any size takes time+// that grows with its size and a near miss of a long needle over and over costs no more than any other text; an escape read the other way starts a reading that is followed next to the pass, and at most MAX_READINGS of them+// per needle are alive at once — a real token keeps one or two — so no text makes the search backtrack or grow faster than the text. A text that would need more is not guessed at: the search fails, and every caller fails+// closed (tests/output-redaction.test.js measures all of it). A text that holds no token comes back as the very string.+const { inspect } = require('node:util');++// What takes the place of a token, or of a part of one, in a text.+const TOKEN_MARKER = '<token>';+// Not the token alone: what an error or a gateway repeats of a bearer token is often one part of it. A token is `header.payload.signature` (three base64url parts joined by dots;+// https://www.rfc-editor.org/rfc/rfc7519#section-3), so each part long enough to be distinctive is taken out too.+const MIN_TOKEN_PART_LENGTH = 24;+// What is kept as a token: the floor of the Dataverse client's own scrubbing. A shorter value is a test's, and would be taken out of ordinary words.+const MIN_TOKEN_LENGTH = 16;++// The texts of one token that are taken out of a message: the token itself and each of its parts that is long enough to be distinctive, the longest first, once each.+function needlesOf(token) {+ const needles = new Set([token]);+ for (const part of token.split('.')) if (part.length >= MIN_TOKEN_PART_LENGTH) needles.add(part);+ return [...needles].sort((a, b) => b.length - a.length);+}++// ---- Reading a text as it spells a token ----------------------------------------------------------------------------------------------------------------------------------------------------------++// White space as a regular expression's `\s` reads it: a fold can be made of any of it, and the plugin's own tests normalize a text with that class.+function isSpace(unit) {+ return unit === 0x20 || (unit >= 0x09 && unit <= 0x0d) || unit === 0xa0 || unit === 0x1680 || (unit >= 0x2000 && unit <= 0x200a)+ || unit === 0x2028 || unit === 0x2029 || unit === 0x202f || unit === 0x205f || unit === 0x3000 || unit === 0xfeff;+}++// A needle the reader cannot read: it holds white space, which the reader skips, a backslash, which it reads as the start of an escape, or an ESC, which it reads as the start of a terminal colour code. Such a token is+// searched for literally (see redactWith).+function unreadable(needle) {+ for (let i = 0; i < needle.length; i += 1) {+ const unit = needle.charCodeAt(i);+ if (unit === 0x5c || unit === 0x1b || isSpace(unit)) return true;+ }+ return false;+}++const hexValue = (unit) => (unit >= 0x30 && unit <= 0x39 ? unit - 0x30 : unit >= 0x41 && unit <= 0x46 ? unit - 0x37 : unit >= 0x61 && unit <= 0x66 ? unit - 0x57 : -1);++// What the reader makes of one item: -1 nothing (a fold), a character's code, or DUAL — an escape that is read two ways, because nothing in a text says whether its backslash is an escape or a literal backslash: as the+// escape (`primaryCode`: the character it stands for, or -1 for one that is white space or a control character) and as the letters after the backslashes (`literalFrom` up to the item's end: `n`, `u0073`, `x41`).+// Variables and not part of a result: this runs for every character of a text that may be megabytes long, and an object for each would be most of its cost.+const DUAL = -2;+let spelledWidth = 1;+let primaryCode = -1;+let literalFrom = 0;++// The item at `at` that begins with a backslash. A RUN of backslashes and what follows it is ONE item, whatever the run's length (JSON inside JSON doubles every backslash), and it is always read whole, so that a match+// never leaves half of an escape behind:+// `\u0073` `\\u0073` (either case of hex) → 's', or the letters `u0073` width of the run + 5 (a white space it spells is nothing)+// `\x73` (how util.inspect escapes a control) → 's', or the letters `x73` width of the run + 3+// `\/` → '/' width of the run + 1+// `\n` `\r` `\t` `\f` `\b` `\v` → nothing (a line break, a control), or the letter itself width of the run + 1+// any other backslash run, before anything else or at the end of the text — a STRAY backslash between two characters of a token: nothing, a fold, width of the run (what follows is read on its own)+// https://www.rfc-editor.org/rfc/rfc8259#section-7 lists the escapes of a JSON string; util.inspect adds `\x..` and `\v` for a JavaScript string. A run read as one item (and not one backslash at a time) is what keeps a+// long run of backslashes from being read again at each of them: the reader stays linear.+function readEscape(text, at) {+ let end = at + 1;+ while (text.charCodeAt(end) === 0x5c) end += 1;+ const run = end - at;+ const letter = text.charCodeAt(end);+ const digits = letter === 0x75 ? 4 : letter === 0x78 ? 2 : 0;+ if (digits > 0) {+ let decoded = 0;+ for (let i = 1; i <= digits && decoded >= 0; i += 1) {+ const value = hexValue(text.charCodeAt(end + i));+ decoded = value < 0 ? -1 : (decoded << 4) | value;+ }+ if (decoded >= 0) {+ spelledWidth = run + 1 + digits;+ primaryCode = isSpace(decoded) ? -1 : decoded;+ literalFrom = end;+ return DUAL;+ }+ } else if (letter === 0x2f) {+ spelledWidth = run + 1;+ return 0x2f;+ } else if (letter === 0x6e || letter === 0x72 || letter === 0x74 || letter === 0x66 || letter === 0x62 || letter === 0x76) {+ spelledWidth = run + 1;+ primaryCode = -1;+ literalFrom = end;+ return DUAL;+ }+ spelledWidth = run;+ return -1;+}++// The most parameter bytes a terminal colour code is read with: util.inspect writes two or three (`\u001b[32m`); a longer one is no code anybody prints, and a bound keeps the reader from scanning on.+const MAX_CODE_PARAMETERS = 32;++// Where the terminal code that begins at `at` (an ESC) ends, or -1 for an ESC that does not begin one: ESC, `[`, up to MAX_CODE_PARAMETERS parameter and intermediate bytes (0x20-0x3f), and one final byte (0x40-0x7e) —+// a control sequence of ECMA-48 (https://ecma-international.org/publications-and-standards/standards/ecma-48/, section 5.4), the shape of every colour code (`\u001b[32m`, `\u001b[1;31m`, `\u001b[39m`).+function codeEnd(text, at) {+ if (text.charCodeAt(at + 1) !== 0x5b) return -1;+ const limit = at + 2 + MAX_CODE_PARAMETERS;+ for (let i = at + 2; i <= limit; i += 1) {+ const unit = text.charCodeAt(i);+ if (unit >= 0x40 && unit <= 0x7e) return i + 1;+ if (!(unit >= 0x20 && unit <= 0x3f)) return -1;+ }+ return -1;+}++// What may stand between the quote, the plus sign and the line break that join the pieces of a long string: spaces, tabs and — on a console that prints in colours — the codes that end one piece's colour and begin the next's.+function skipJoin(text, at) {+ let i = at;+ for (;;) {+ const unit = text.charCodeAt(i);+ if (unit === 0x20 || unit === 0x09) {+ i += 1;+ continue;+ }+ const end = unit === 0x1b ? codeEnd(text, i) : -1;+ if (end < 0) return i;+ i = end;+ }+}++// A long string as `util.inspect` prints it — `console.error(error)` prints the body an error keeps that way — is cut after each line break and the pieces are joined as source code joins them; on a console that prints in+// colours (a terminal, or FORCE_COLOR=1) each piece is wrapped in its own colour codes:+// message: 'Rejected bearer abcdefgh\r\n' + message: \u001b[32m'Rejected bearer abcdefgh\r\n'\u001b[39m ++// ' ijklmnop\r\n' + \u001b[32m' ijklmnop\r\n'\u001b[39m ++// ' qrstuvwx' \u001b[32m' qrstuvwx'\u001b[39m+// The closing quote, the codes, the plus sign, the line break, the indentation and the same quote again stand where the string has no character, so they are skipped like a fold. Anything else after a quote is the quote, a+// character of its own.+function readContinuation(text, at, quote) {+ let i = skipJoin(text, at + 1);+ if (text.charCodeAt(i) !== 0x2b) return quote;+ i = skipJoin(text, i + 1);+ if (text.charCodeAt(i) === 0x0d) i += 1;+ if (text.charCodeAt(i) !== 0x0a) return quote;+ i = skipJoin(text, i + 1);+ if (text.charCodeAt(i) !== quote) return quote;+ spelledWidth = i + 1 - at;+ return -1;+}++// `skip` says what an ASCII character is to the reader: 0 a character like any other, 1 white space, 2 a quote that may begin a continuation (it is 0 where a needle holds that character), 3 an ESC — a terminal code, or a+// lone ESC, is a fold: a console that prints in colours puts codes between the pieces of a string, and a colourful log line can put one anywhere.+function readSpelled(text, at, skip) {+ const unit = text.charCodeAt(at);+ spelledWidth = 1;+ if (unit === 0x5c) return readEscape(text, at);+ if (unit < 128) {+ const kind = skip[unit];+ if (kind === 0) return unit;+ if (kind === 1) return -1;+ if (kind === 3) {+ const end = codeEnd(text, at);+ if (end > 0) spelledWidth = end - at;+ return -1;+ }+ return readContinuation(text, at, unit);+ }+ return isSpace(unit) ? -1 : unit;+}++// The longest proper prefix of `needle.slice(0, i + 1)` that is also its suffix, for each i: where a search for the needle goes on after a mismatch, so that it never reads a character twice+// (https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm).+function failureTable(needle) {+ const table = new Int32Array(needle.length);+ for (let i = 1, k = 0; i < needle.length; i += 1) {+ while (k > 0 && needle.charCodeAt(i) !== needle.charCodeAt(k)) k = table[k - 1];+ if (needle.charCodeAt(i) === needle.charCodeAt(k)) k += 1;+ table[i] = k;+ }+ return table;+}++// How many readings of ONE needle that took an escape's letters (and not the escape) the search follows at once. A random token keeps one or two alive on any text, and a needle that is one letter over and over keeps+// one per letter; more than this needs a text made to match the needle almost everywhere — i.e. made by someone who has the token. The bound keeps the cost linear on any text: past it the search does not guess which+// reading to drop (a dropped one could be the token), it fails, and every caller fails closed (a stream writes WITHHELD, a file is not written).+const MAX_READINGS = 128;+const TOO_MANY_READINGS = 'output-redaction: a text holds too many ways to read a token for it to be checked';++// Everything the search needs of a set of tokens, made once and not for each text: the needles it can read and each one's failure table, the first character of each (a text is only looked at closely where one could start,+// or where a needle is already being matched), what the reader skips, and the tokens that still need a literal search for a needle of their own that the reader cannot read.+function prepare(tokens) {+ const live = [...new Set(tokens.filter((token) => typeof token === 'string' && token !== ''))];+ if (live.length === 0) return null;+ const needles = [...new Set(live.flatMap(needlesOf))].filter((needle) => !unreadable(needle));+ const skip = new Uint8Array(128);+ for (const unit of [0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20]) skip[unit] = 1;+ for (const unit of [0x22, 0x27, 0x60]) skip[unit] = 2;+ skip[0x1b] = 3;+ const firstUnits = new Uint8Array(65536);+ for (const needle of needles) {+ firstUnits[needle.charCodeAt(0)] = 1;+ for (let i = 0; i < needle.length; i += 1) {+ const unit = needle.charCodeAt(i);+ if (unit < 128) skip[unit] = 0;+ }+ }+ return {+ needles,+ tables: needles.map(failureTable),+ longest: needles.reduce((length, needle) => Math.max(length, needle.length), 0),+ firstUnits,+ skip,+ literal: live.filter((token) => needlesOf(token).some(unreadable)),+ // The search's working memory, kept with what it is made for: a stream is written in many small pieces, and an array of the longest needle's length made for each would cost more than the search. The search+ // never calls out and never starts another, so one set at a time is all there is.+ starts: new Int32Array(needles.reduce((length, needle) => Math.max(length, needle.length), 1)),+ states: new Int32Array(needles.length),+ // For each needle, the readings that took an escape's letters: how far each is (`states`) and where it began (`begins`), with a second pair the next set is made in, and `slot` — for a state, 1 + its index in the next+ // set — so that two readings that have come equally far are kept once, with the earlier beginning (whatever the later one would find, the earlier one finds with a span that holds it).+ readings: needles.map((needle) => ({+ count: 0,+ states: new Int32Array(MAX_READINGS),+ begins: new Int32Array(MAX_READINGS),+ nextCount: 0,+ nextStates: new Int32Array(MAX_READINGS),+ nextBegins: new Int32Array(MAX_READINGS),+ slot: new Int32Array(needle.length + 1),+ })),+ };+}++// Puts a reading that has come `state` characters into the needle, begun at `begin`, into the next set of `readings`.+function keepReading(readings, state, begin) {+ const index = readings.slot[state] - 1;+ if (index >= 0) {+ if (begin < readings.nextBegins[index]) readings.nextBegins[index] = begin;+ return;+ }+ if (readings.nextCount === MAX_READINGS) {+ for (let i = 0; i < readings.nextCount; i += 1) readings.slot[readings.nextStates[i]] = 0;+ throw new RangeError(TOO_MANY_READINGS);+ }+ readings.nextStates[readings.nextCount] = state;+ readings.nextBegins[readings.nextCount] = begin;+ readings.nextCount += 1;+ readings.slot[state] = readings.nextCount;+}++// A reading that has come `state` characters into `needle`, begun at `begin`, read on through the letters `text[from, end)` of one escape: it ends there (a letter that is not the needle's next character), is a match+// (the span reaches to the end of the escape, so that no half of it is left), or goes on in the next set.+function readLetters(text, from, end, needle, readings, state, begin, spans) {+ let at = state;+ for (let j = from; j < end; j += 1) {+ if (needle.charCodeAt(at) !== text.charCodeAt(j)) return;+ at += 1;+ if (at === needle.length) {+ spans.push([begin, end]);+ return;+ }+ }+ keepReading(readings, at, begin);+}++// An escape that is read two ways (DUAL), spanning `[begin, end)`. For each needle the next set of readings is made of: every reading already followed, taking the escape as the character it stands for (or as nothing) AND+// as its letters; every alignment the main search follows (its state, and each shorter one that is also alive: the failure table's chain), taking the letters; and a new reading beginning at any of the letters. The main+// search then takes the escape's first reading itself. Returns whether any reading is alive.+function forkReadings(text, begin, end, prepared, read, spans) {+ const { needles, tables, longest, starts, states, readings: all } = prepared;+ const primary = primaryCode;+ const from = literalFrom;+ let alive = false;+ for (let n = 0; n < needles.length; n += 1) {+ const needle = needles[n];+ const readings = all[n];+ readings.nextCount = 0;+ for (let i = 0; i < readings.count; i += 1) {+ const state = readings.states[i];+ const began = readings.begins[i];+ if (primary === -1) keepReading(readings, state, began);+ else if (needle.charCodeAt(state) === primary) {+ if (state + 1 === needle.length) spans.push([began, end]);+ else keepReading(readings, state + 1, began);+ }+ readLetters(text, from, end, needle, readings, state, began, spans);+ }+ for (let state = states[n]; state > 0; state = tables[n][state - 1]) readLetters(text, from, end, needle, readings, state, starts[(read - state) % longest], spans);+ const first = needle.charCodeAt(0);+ for (let j = from; j < end; j += 1) if (text.charCodeAt(j) === first) readLetters(text, j, end, needle, readings, 0, begin, spans);+ for (let i = 0; i < readings.nextCount; i += 1) readings.slot[readings.nextStates[i]] = 0;+ [readings.states, readings.nextStates] = [readings.nextStates, readings.states];+ [readings.begins, readings.nextBegins] = [readings.nextBegins, readings.begins];+ readings.count = readings.nextCount;+ if (readings.count > 0 || states[n] > 0) alive = true;+ }+ return alive;+}++// Every needle searched for in ONE pass over the items the text spells, in time that grows with the text: a search that starts again at every character takes seconds on a text that is a needle's first thousand+// characters over and over. A needle's state is how many of its first characters the last items spell — on the escapes' first readings (as the character an escape stands for, or nothing), as Knuth-Morris-Pratt does it.+// An escape that can also be its letters (a literal backslash before an `n`) starts readings that the search follows next to it, a bounded set (forkReadings). A match runs from where the first of its characters is+// spelled to where its last ends — the folds and escapes between them are inside it, and the white space before and after is not. `starts` remembers where each of the last items began, in a ring as long as the longest+// needle, which is all a match can reach back over; an item that cannot start a match while no needle is being matched is counted and not stored, because no match will ever ask for its start. The spans of all the+// needles are then merged where they overlap (a token and its parts do) and each merged span is replaced by one marker; two spans that only touch stay two, as two tokens written one after the other are two.+function takeOutSpelled(text, prepared) {+ const { needles, tables, longest, firstUnits, skip, starts, states, readings: all } = prepared;+ const count = needles.length;+ states.fill(0);+ for (const readings of all) readings.count = 0;+ const spans = [];+ let read = 0;+ let matching = false;+ for (let at = 0; at < text.length;) {+ const begin = at;+ let code = readSpelled(text, at, skip);+ at += spelledWidth;+ if (code === -1) continue;+ let forked = false;+ if (code === DUAL) {+ code = primaryCode;+ let letterStarts = false;+ for (let j = literalFrom; j < at && !letterStarts; j += 1) letterStarts = firstUnits[text.charCodeAt(j)] === 1;+ if (matching || letterStarts) {+ matching = forkReadings(text, begin, at, prepared, read, spans);+ forked = true;+ }+ if (code === -1) continue;+ }+ if (!matching && firstUnits[code] === 0) {+ read += 1;+ continue;+ }+ starts[read % longest] = begin;+ matching = false;+ for (let n = 0; n < count; n += 1) {+ const needle = needles[n];+ const readings = all[n];+ if (!forked && readings.count > 0) {+ let kept = 0;+ for (let i = 0; i < readings.count; i += 1) {+ const state = readings.states[i];+ if (needle.charCodeAt(state) !== code) continue;+ if (state + 1 === needle.length) {+ spans.push([readings.begins[i], at]);+ continue;+ }+ readings.states[kept] = state + 1;+ readings.begins[kept] = readings.begins[i];+ kept += 1;+ }+ readings.count = kept;+ }+ if (readings.count > 0) matching = true;+ const table = tables[n];+ let state = states[n];+ while (state > 0 && needle.charCodeAt(state) !== code) state = table[state - 1];+ if (needle.charCodeAt(state) === code) state += 1;+ if (state === needle.length) {+ spans.push([starts[(read - state + 1) % longest], at]);+ state = table[state - 1];+ }+ states[n] = state;+ if (state > 0) matching = true;+ }+ read += 1;+ }+ if (spans.length === 0) return text;+ spans.sort((a, b) => a[0] - b[0] || b[1] - a[1]);+ let out = '';+ let kept = 0;+ let [from, to] = spans[0];+ for (let i = 1; i <= spans.length; i += 1) {+ const span = spans[i];+ if (span !== undefined && span[0] < to) {+ to = Math.max(to, span[1]);+ continue;+ }+ out += text.slice(kept, from) + TOKEN_MARKER;+ kept = to;+ if (span !== undefined) [from, to] = span;+ }+ return out + text.slice(kept);+}++// `text` with the tokens `prepared` stands for taken out: what the reader finds, and then — only for a token that has a needle the reader cannot read (white space, a backslash or an ESC in it) — a literal search, as the Dataverse+// client's scrubber does it. The reader first, so that a token spelled in one piece is one marker: a literal search first would take out the parts of a token whose dots are inside a fold, and leave `<token>.<token>`+// where the reader finds the whole.+function redactWith(prepared, text) {+ let out = text;+ if (prepared.needles.length > 0) out = takeOutSpelled(out, prepared);+ for (const token of prepared.literal) out = needlesOf(token).reduce((current, needle) => current.split(needle).join(TOKEN_MARKER), out);+ return out;+}++/**+ * `text` with every token in `tokens` taken out of it — whole, and by each of its parts of 24 characters or more — wherever the text spells it: plainly, with a fold in it, with an escape in it (or a stray backslash), or+ * printed over several lines the way `util.inspect` prints a long string, in colours or not. A text that holds none is returned as the same string. Throws a RangeError for a text that holds too many ways to read a token+ * to be checked (MAX_READINGS): a caller must then not write the text.+ * @param {string} text+ * @param {string[]} tokens+ * @returns {string}+ */+function redactTokens(text, tokens) {+ const prepared = prepare(Array.isArray(tokens) ? tokens : []);+ return prepared === null || typeof text !== 'string' || text === '' ? text : redactWith(prepared, text);+}++// ---- The tokens this process obtained -------------------------------------------------------------------------------------------------------------------------------------------------------------++const obtained = new Set();+// Bumped when a token joins, so that what is prepared from the set is made again only then.+let version = 0;+let preparedFor = { version: -1, prepared: null };++/**+ * Notes an access token this process obtained or sent, once, and — the first time — puts the guards on what the process writes (installOutputGuard). Called where a token is read from the Azure CLI and where a client sends+ * one, so a token is known from the moment it exists, and before any text that could repeat it can be written. A value shorter than 16 characters is no access token and is ignored.+ * @param {unknown} token+ */+function noteToken(token) {+ if (typeof token !== 'string' || token.length < MIN_TOKEN_LENGTH || obtained.has(token)) return;+ obtained.add(token);+ version += 1;+ installOutputGuard();+}++/** Every access token this process has obtained, once each, the first obtained first. */+function obtainedTokens() {+ return [...obtained];+}++/**+ * `text` with every token this process has obtained taken out of it. Anything that is not a string — bytes, a number — is returned as it is, and so is a text when no token has been obtained yet. Throws as `redactTokens`+ * does for a text that cannot be checked; every caller then fails closed (the guard on a stream writes a notice instead of the text, a file writer writes nothing and reports the failure).+ * @template T+ * @param {T} text+ * @returns {T}+ */+function redactOutput(text) {+ if (typeof text !== 'string' || obtained.size === 0 || text === '') return text;+ if (preparedFor.version !== version) preparedFor = { version, prepared: prepare([...obtained]) };+ return redactWith(preparedFor.prepared, text);+}++// ---- The streams, an error that ends the process, and the SDK's workspace --------------------------------------------------------------------------------------------------------------------------++// Put on the function that wraps a stream's `write`, so that a stream is wrapped once however many times it is asked.+const GUARDED = Symbol.for('power-platform-skills.output-redaction.guarded');+// What is written where a text could not be cleaned (the cleaning itself failed): not the text, which may hold the token — a failure here is rare enough to be loud.+const WITHHELD = '[output withheld: it could not be checked for an access token]\n';+// A string given with one of these encodings is not text (`write('6162', 'hex')`), so it is not read as text.+const BINARY_ENCODINGS = /^(?:hex|base64|base64url)$/i;++/**+ * Makes `stream.write` take the tokens out of every string it is given. The wrapper is the stream's own `write` property, put where the original was: whatever replaces it later replaces it whole, and a caller that wraps it+ * (`const write = stream.write; stream.write = …`) wraps it with the guard inside. Bytes are passed on as they are. Returns false for a stream that is already guarded or has no `write`.+ * @param {{ write: Function }} stream+ * @param {(text: string) => string} [redact]+ * @returns {boolean}+ */+function guardStream(stream, redact = redactOutput) {+ if (!stream || typeof stream.write !== 'function' || stream.write[GUARDED]) return false;+ const write = stream.write;+ const guarded = function writeWithoutTokens(chunk, ...rest) {+ let given = chunk;+ if (typeof chunk === 'string' && !(typeof rest[0] === 'string' && BINARY_ENCODINGS.test(rest[0]))) {+ try {+ given = redact(chunk);+ } catch {+ given = WITHHELD;+ }+ }+ return write.call(this, given, ...rest);+ };+ guarded[GUARDED] = true;+ stream.write = guarded;+ return true;+}++/**+ * Makes the writes to each of `streams` blocking from here on: a `write` returns when the stream has taken the whole text. For the last writes of a process — the ones a `process.exit` follows at once (`emitResult` in+ * lib/dataverse-auth.js, the printer of an error that ends the process below, a script's own result printer). Nothing else about the stream changes: the text still goes through its `write`, the guard above included.+ * Each plugin's tests keep a tripwire on this (tests/exit-writes-inventory.test.js in model-apps, tests/pcf-exit-writes-inventory.test.js in pcf): a syntactic scan of the source that fails on a new exit that has+ * no such call before it and is not listed with the bound that makes it safe, and on a call that comes after a write in its own block or leaves out a stream written before the exit. It reads the source, not what+ * runs: the tests that record the order of a process's own calls (tests/printers-whole-before-exit.test.js with helpers/write-order-preload.js) are what show that a printer makes its stream blocking before it writes.+ *+ * WHY. Node writes to a pipe asynchronously on Linux and macOS, and synchronously on Windows (https://nodejs.org/api/process.html#a-note-on-process-io). What the pipe does not take at once — more than its buffer holds,+ * 64 KiB on Linux — is queued, and `process.exit` ends the process without waiting for the queue (https://nodejs.org/api/process.html#processexitcode). An agent reads a script's result through a pipe, so a large+ * result reached it cut short: on the Linux and macOS CI jobs the 3.5 MB result of tests/output-token-boundary.test.js ended mid-string (for example "Unterminated string in JSON at position 146176").+ * A blocking handle is what Node itself gives a terminal (`tty.WriteStream` calls `setBlocking(true)`) and, on Windows, a pipe on stdout or stderr (`net.Socket`: "Make stdout and stderr blocking on Windows"); libuv then+ * completes every write synchronously (uv_stream_set_blocking: https://docs.libuv.org/en/v1.x/stream.html). tests/result-whole-before-exit.test.js gives a script the kind of pipe Linux and macOS give it, on every+ * platform: without this, a 3.5 MB result arrived in part on Windows too; with it, whole.+ *+ * SAFE because it is done at the end: the process exits right after, so no other work waits behind a blocking write. A reader that is reading takes the text; one that has stopped reading now holds the script at its last+ * write — as a pipe on Windows always has — instead of receiving a result cut short. A hook is no exception: a host that read a hook's output only after the hook had exited would now wait until its own time limit+ * for the hook ends it, where it used to read a message cut short; a reader that closes its end does not hold it: the write fails at once (EPIPE).+ * On POSIX the flag belongs to the pipe's open file description, which every process holding that end shares, and Node puts it back as+ * it found it when the process exits (ResetStdio, src/node.cc). A write queued BEFORE this call (only when the reader has left more than a pipe's buffer unread, with no turn of the event loop since) stays queued, and the+ * writes after it wait behind it in the stream's own buffer: Node has no synchronous flush of a queued write. That is why this is called before the last writes, not just before `process.exit`.+ *+ * A stream with no such handle — a file (written synchronously already), a worker's stdout, a test's stand-in — is left as it is, and so is a handle that answers with an error code (a terminal on Windows answers EINVAL:+ * libuv blocks only a pipe there). Never throws: the text is written either way.+ * @param {...?{ _handle?: ?{ setBlocking?: Function } }} streams+ */+function makeWritesBlocking(...streams) {+ for (const stream of streams) {+ try {+ const handle = stream && stream._handle;+ if (handle && typeof handle.setBlocking === 'function') handle.setBlocking(true);+ } catch {+ // A handle that throws (a closed or foreign one): the text goes out as it always did.+ }+ }+}++// Node prints an error that ends the process (an exception nothing caught, a promise rejected and never handled) from its own code, and not through `process.stderr.write`, so the wrapper on the stream does not see it+// (measured on Node 20 and 22: a replaced `write` is never called). With a listener the default — print, exit with status 1 — is replaced by this one, which prints the same error, cleaned, and exits with the same status.+// Only when nothing else handles the error: a test runner has its own listener, and a host that added one after this one has taken the decision over. `breakLength: Infinity` keeps `inspect` from cutting a long string+// into pieces joined with `+`, which is the one thing that could make a cleaned text differ from the text a person reads. The write is made blocking first (makeWritesBlocking): this handler exits right after it, so a+// long error (an answer the SDK quoted into it) would otherwise reach a pipe on Linux and macOS cut short.+function guardFatalErrors() {+ if (process.listenerCount('uncaughtException') > 0) return false;+ process.on('uncaughtException', function fatalWithoutTokens(error, origin) {+ if (process.listenerCount('uncaughtException') > 1) return;+ let text;+ try {+ text = inspect(error, { breakLength: Infinity, depth: 10 });+ } catch {+ text = 'an error that could not be printed';+ }+ try {+ // Inside the try, with the write: reading `process.stderr` can itself throw (a host that replaced it with an accessor that does), and the+ // process must still end with status 1, as an error nothing caught always does — a throw out of this handler would end it with 7 instead+ // ("Internal Exception Handler Run-Time Failure": https://nodejs.org/api/process.html#exit-codes).+ makeWritesBlocking(process.stderr);+ process.stderr.write(`${redactOutput(`${origin === 'unhandledRejection' ? 'Uncaught (in promise) ' : 'Uncaught '}${text}`)}\n`);+ } catch {+ // The stream is gone: there is nobody to tell.+ }+ process.exit(1);+ });+ return true;+}++let installed = false;+/**+ * Puts the guards on this process: stdout, stderr and the error that ends the process. Called by `noteToken` the first time a token is noted — not at load, so that a process that never has a token is untouched —+ * and harmless to call again. It never throws: a token has already been obtained, and failing here would fail the read that obtained it.+ */+function installOutputGuard() {+ if (installed) return;+ installed = true;+ for (const attempt of [() => guardStream(process.stdout), () => guardStream(process.stderr), guardFatalErrors]) {+ try {+ attempt();+ } catch {+ // A host with no usable stream: the rest is still guarded.+ }+ }+}++/**+ * `storage` (an SDK WorkspaceStorage) with the tokens taken out of every text it is asked to write. The SDK writes each file of its workspace — an artifact, its metadata, the manifest — through `writeTextAtomic(key, text)`, and+ * through nothing else, so this is every file the SDK writes. Everything else is the storage's own and runs ON the storage: a method is called with the storage as `this` and an accessor is read from it, because a+ * storage may keep its state in `#private` fields, which only the object they were made for can read (a wrapper that is merely a child of the storage would be `this` instead, and fail). The wrapper is a Proxy over an+ * empty child of the storage — not over the storage itself, whose own frozen members would bind what a Proxy may answer — so the SDK still finds the folder (`pathFor`, `getRoot`) and an `instanceof` still holds; a value+ * set through it is set on the storage.+ * @template T+ * @param {T} storage+ * @param {(text: string) => string} [redact]+ * @returns {T}+ */+function guardWorkspaceStorage(storage, redact = redactOutput) {+ if (storage === null || typeof storage !== 'object' || typeof storage.writeTextAtomic !== 'function') return storage;+ const writeTextAtomic = function writeTextAtomicWithoutTokens(key, text, ...rest) {+ return storage.writeTextAtomic(key, typeof text === 'string' ? redact(text) : text, ...rest);+ };+ // One function per member, so that a member read twice is the same function, as it is on the storage.+ const onStorage = new Map();+ return new Proxy(Object.create(storage), {+ get(target, key) {+ if (key === 'writeTextAtomic') return writeTextAtomic;+ const value = Reflect.get(storage, key, storage);+ if (typeof value !== 'function' || key === 'constructor') return value;+ if (!onStorage.has(value)) onStorage.set(value, function onTheStorage(...args) { return value.apply(storage, args); });+ return onStorage.get(value);+ },+ set(target, key, value) {+ return Reflect.set(storage, key, value, storage);+ },+ });+}++module.exports = {+ TOKEN_MARKER,+ needlesOf,+ noteToken,+ obtainedTokens,+ redactTokens,+ redactOutput,+ guardStream,+ makeWritesBlocking,+ guardFatalErrors,+ installOutputGuard,+ guardWorkspaceStorage,+};diff --git a/plugins/pcf/scripts/lib/pcf-dataverse.js b/plugins/pcf/scripts/lib/pcf-dataverse.jsindex 3d1b7b2be..f0fe869f2 100644--- a/plugins/pcf/scripts/lib/pcf-dataverse.js+++ b/plugins/pcf/scripts/lib/pcf-dataverse.js@@ -3,6 +3,7 @@const fs = require('node:fs');const { createAzHttpClient } = require('./sdk-http-client.js');+const { guardWorkspaceStorage } = require('./output-redaction.js');const { odataLit } = require('./odata.js');const CUSTOM_CONTROL_SELECT = ['customcontrolid', 'name', 'version', 'componentstate', 'ismanaged'];@@ -18,7 +19,8 @@ const WHERE_USED_CAVEAT = "registered solution dependencies only — not proof oasync function makePcfSdk(env, workspaceDir, httpClient = createAzHttpClient(env)) {const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');fs.mkdirSync(workspaceDir, { recursive: true });- const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspaceDir), instanceUrl: env, httpClient });+ // Every file the SDK writes into its workspace goes through the storage's `writeTextAtomic`; guarded, none of them can carry an access token this process obtained (lib/output-redaction.js) — as in model-apps' factory.+ const sdk = createMakerSdk({ workspaceStorage: guardWorkspaceStorage(createNodeWorkspaceStorage(workspaceDir)), instanceUrl: env, httpClient });await sdk.initWorkspace();return sdk;}diff --git a/plugins/pcf/scripts/lib/sdk-http-client.js b/plugins/pcf/scripts/lib/sdk-http-client.jsindex 9f74206ef..f7d57df3e 100644--- a/plugins/pcf/scripts/lib/sdk-http-client.js+++ b/plugins/pcf/scripts/lib/sdk-http-client.js@@ -14,6 +14,7 @@// token taken out of it, and so does a transport failure's text (see "The access token, taken out of what a// service says"): the SDK quotes such a body in the message a script prints. A success is returned untouched.const { dataverseOrigin, getAuthToken, makeRequest, tokenFailureMessage } = require('./dataverse-auth.js');+const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');// How Dataverse reports that SQL Server chose a request's transaction as a deadlock VICTIM and rolled// it back. Two live captures, both HTTP 500 (a process-flow delete during a teardown, and PublishXml):@@ -50,7 +51,8 @@ const DEADLOCK_RESENDS = 3;// The longest `Retry-After` honoured in full. Dataverse's service protection limits answer 429 with// `Retry-After` in seconds and ask the caller to wait that long; a request sent sooner is refused again// and spends one of the few attempts. The cap keeps a large value from stalling a build or a teardown-// for minutes per attempt.+// for minutes per attempt. A client given a run's throttle budget (`deps.throttle`) does not use it for a throttled answer: the budget+// bounds all of its waits together, and what the service asked is waited whole when it fits and not at all when it does not.// See: https://learn.microsoft.com/power-apps/developer/data-platform/api-limits#retry-operationsconst RETRY_AFTER_CAP_MS = 60000;@@ -65,8 +67,8 @@ const RAW_VALUE = /\/\$value(?:\?|$)/;* Retry-After: Wed, 30 Sep 2026 10:00:20 GMT* Node lowercases response header names; a test double may not, so the name is matched case-insensitively.* The cap is for this client's own retries, which must not stall a build for minutes per attempt. A caller that has a bound of its own on the whole of what it waits passes `Infinity` and gets the- * service's request as it is, to decide for itself whether it fits: solution-settings.js, when it sends a refused import again, inside one budget for the whole retry; and the page backend, which spends a- * run's throttle budget (lib/throttle-budget.js).+ * service's request as it is, to decide for itself whether it fits: solution-settings.js, when it sends a refused import again, inside one budget for the whole retry; the page backend, which spends a+ * run's throttle budget (lib/throttle-budget.js); and this client itself when it was given that budget, for the throttled answers it waits out (waitOutThrottle).* See: https://www.rfc-editor.org/rfc/rfc9110#field.retry-after*/function retryAfterMs(headers, now = Date.now(), cap = RETRY_AFTER_CAP_MS) {@@ -535,15 +537,12 @@ function transportError(res, message) {// never touched: its bytes are the caller's data. The same rule keeps the Power Apps client's answers clean (lib/power-apps-service-client.js takes `scrub` and `scrubAnswer` from here, which is// why they are exported: there is one scrubber).//-// Not the token alone: what an error or a gateway repeats of a bearer token is often one part of it. A token is `header.payload.signature` (three base64url parts joined by dots;-// https://www.rfc-editor.org/rfc/rfc7519#section-3), so each part long enough to be distinctive is taken out too.-const MIN_TOKEN_PART_LENGTH = 24;+// Not the token alone: what an error or a gateway repeats of a bearer token is often one part of it, so `needlesOf` (lib/output-redaction.js, the one list of what is taken out of a token: the token and each of its dot-separated+// parts that is long enough to be distinctive — https://www.rfc-editor.org/rfc/rfc7519#section-3) is what this scrubber takes out, as what the process writes is kept free of it by the same list.function scrub(text, token) {const message = String(text);if (!token) return message;- const needles = new Set([token]);- for (const part of token.split('.')) if (part.length >= MIN_TOKEN_PART_LENGTH) needles.add(part);- return [...needles].sort((a, b) => b.length - a.length).reduce((out, needle) => out.split(needle).join('<token>'), message);+ return needlesOf(token).reduce((out, needle) => out.split(needle).join(TOKEN_MARKER), message);}// The same for a whole ANSWER: every string of it is scrubbed, keys included, whatever the status: the rest of the answer is left as it is, so the status and the typed `error.code` the SDK reads survive.@@ -572,8 +571,10 @@ function scrubBearer(text, headers) {/*** Build an HttpClient bound to one Dataverse org.* @param {string} orgUrl - e.g. https://contoso.crm.dynamics.com- * @param {object} [deps] - test seam: { getToken(orgUrl)->string|null, request(opts)->Promise }, and one policy a caller may set:- * `sendOnce(method, url)` -> true for a request that must be sent exactly once, whatever answers it (see `once` in `call`).+ * @param {object} [deps] - test seam: { getToken(orgUrl)->string|null, request(opts)->Promise }, and two things a caller may set:+ * `sendOnce(method, url)` -> true for a request that must be sent exactly once, whatever answers it (see `once` in `call`); and+ * `throttle`, the budget a run allows itself for waiting out a throttled service (lib/throttle-budget.js: `fits`, `spend`, `announce`, `decline`, `note`), which every wait this client takes for a throttled answer (HTTP 429) is+ * then drawn from — see `waitOutThrottle`. A client given none waits exactly as it always did, and the pcf plugin, which has none, never passes one.* @returns {{get,post,patch,delete,put,postRaw,patchRaw}}*/function createAzHttpClient(orgUrl, deps = {}) {@@ -636,6 +637,33 @@ function createAzHttpClient(orgUrl, deps = {}) {// for longer in `Retry-After` (retryAfterMs, capped).const retryWaitMs = (res, attempt) => Math.max(backoffMs(attempt), retryAfterMs(res.headers, now()));+ // The run's budget for waiting out a throttle (lib/throttle-budget.js), when the caller gave one — and it must have everything this client calls on it, or it is no budget. This file is copied into the pcf plugin, which has no+ // budget and no such module, so the budget is something a caller hands in and never something this file loads: a client made without one waits exactly as it always did.+ const throttle = ['fits', 'spend', 'announce', 'decline', 'note'].every((name) => deps.throttle && typeof deps.throttle[name] === 'function') ? deps.throttle : null;+ // What THROTTLING is here: the service refusing a request because of its limits — HTTP 429, alone or as every operation of a `$batch`. A 5xx is not: a customization lock or a SQL deadlock victim is a 500, and a gateway's hiccup a 502, 503+ // or 504, each is re-sent on its own schedule (with the Retry-After it carries, capped at a minute), and neither is a reset connection. None of those waits is the budget's.+ //+ // The wait before a throttled request is sent again, for a client that has a budget: the schedule's wait or what the service asked in `Retry-After`, whichever is longer — and the ask WHOLE, not capped at a minute. The cap keeps a large value+ // from stalling a run for minutes on every attempt, which the budget now does for all the attempts together, and a request sent before the service is ready is refused again and spends one of its six attempts. The wait is drawn from the budget,+ // placed on the clock (`at`: the requests this client sends at once are throttled alike and wake together, and what the run waited is the time it spent waiting, not the sum of their waits), and announced when it is long.+ // Resolves true when the wait was taken. It resolves false when the wait does not fit: nothing is waited for, and the caller hands the throttled answer back as it came — as it does when the sends run out — so what the SDK reports is the 429 it is, a+ // refusal that started nothing. That answer says nothing of what the service asked (the SDK's error holds no headers) or of why no more was sent, so the budget is told (`decline`), and the build, which owns the halt, says it.+ // See https://learn.microsoft.com/power-apps/developer/data-platform/api-limits#retry-operations for what a service protection limit asks of the caller.+ async function waitOutThrottle({ res, attempt, method, url, batch }) {+ const at = now();+ // `batch`: an operation refused inside a `$batch` answer carries its own Retry-After, which the outer response need not repeat.+ const asked = Math.max(retryAfterMs(res.headers, at, Infinity), batch ? batchRetryAfterMs(res, at, Infinity) : 0);+ const wait = Math.max(backoffMs(attempt), asked);+ if (!throttle.fits(wait, at)) {+ throttle.decline({ askedMs: asked, waitMs: wait });+ return false;+ }+ const added = throttle.spend(wait, at);+ throttle.announce(`the service throttled ${method} ${new URL(url).pathname} (HTTP 429); waiting ${Math.ceil(wait / 1000)} s before sending it again (${throttle.note()})`, added);+ await sleep(wait);+ return true;+ }+// 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();@@ -722,6 +750,24 @@ function createAzHttpClient(orgUrl, deps = {}) {// (429, 5xx) keeps the status retry above; that trade-off is unchanged.const conditional = isWrite && Object.keys((options && options.headers) || {}).some((h) => h.toLowerCase() === 'if-match');+ // 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) => {+ if (!(res.statusCode >= 200 && res.statusCode < 300)) {+ const text = (value) => (typeof value === 'string' ? scrubText(value) : value);+ return {+ status: res.statusCode,+ headers: scrubValue(res.headers || {}),+ body: ctl.bytes ? scrubBytes(res.body) : ctl.rawBody ? text(res.body) : scrubValue(parseBody(text(res.body))),+ };+ }+ return {+ status: res.statusCode,+ headers: res.headers || {},+ body: ctl.rawBody || ctl.bytes ? res.body : parseBody(res.body),+ };+ };+// Retry: refresh the token once on 401 (no backoff); back off on transient 5xx/429.// 6 attempts with capped jittered backoff rides out a per-entity customization lock that// can stay held for ~20s while a prior metadata op or publish settles.@@ -730,6 +776,8 @@ function createAzHttpClient(orgUrl, deps = {}) {const last = attempt === maxAttempts - 1;const bearer = ensureToken();if (bearer.length >= MIN_SCRUBBED_TOKEN_LENGTH) tokensSent.add(bearer);+ // Noted for everything the process writes, not only for this client's answers: a service may repeat a token it was sent by any client, in an answer that is a success (lib/output-redaction.js).+ noteToken(bearer);const headers = {Authorization: `Bearer ${bearer}`,Accept: 'application/json',@@ -775,6 +823,12 @@ function createAzHttpClient(orgUrl, deps = {}) {continue;}if (TRANSIENT.has(res.statusCode) && !last && !noRetry) {+ // A throttle (HTTP 429) is waited out inside the run's budget when the client has one, and handed back as it came when the wait does not fit (waitOutThrottle). What else is re-sent here — a customization lock or a deadlock+ // 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);+ }await sleep(retryWaitMs(res, attempt));continue;}@@ -803,6 +857,10 @@ function createAzHttpClient(orgUrl, deps = {}) {// has not said that of.const throttled = !once && ((recordDelete && res.statusCode === 429) || ((conditionalDeleteBatch || columnCreateBatch) && isBatchThrottled(res)));if (throttled && !last) {+ if (throttle) {+ if (await waitOutThrottle({ res, attempt, method: method_, url, batch: isBatch })) continue;+ return deliver(res);+ }// 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));continue;@@ -813,21 +871,7 @@ function createAzHttpClient(orgUrl, deps = {}) {await sleep(1000 * 2 ** attempt);continue;}- // 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.- if (!(res.statusCode >= 200 && res.statusCode < 300)) {- const text = (value) => (typeof value === 'string' ? scrubText(value) : value);- return {- status: res.statusCode,- headers: scrubValue(res.headers || {}),- body: ctl.bytes ? scrubBytes(res.body) : ctl.rawBody ? text(res.body) : scrubValue(parseBody(text(res.body))),- };- }- return {- status: res.statusCode,- headers: res.headers || {},- body: ctl.rawBody || ctl.bytes ? res.body : parseBody(res.body),- };+ return deliver(res);}/* istanbul ignore next */throw new Error('Unreachable retry loop');diff --git a/plugins/pcf/scripts/lib/source-literals.js b/plugins/pcf/scripts/lib/source-literals.jsindex de7a4ef7a..9aa45c861 100644--- a/plugins/pcf/scripts/lib/source-literals.js+++ b/plugins/pcf/scripts/lib/source-literals.js@@ -1216,7 +1216,8 @@ function blockBraceAt(out, k) {// left-hand-side expressions that the parser reads as it reads any other (parseExpressionWithTypeArguments, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts), and a `)` ends the last of them when it is a call or a parenthesis:// class C extends mixin(A) { class C extends (Base) { class C extends a.b.mixin(A) { class C extends new Base() { valid// class C implements B() { class C implements (B) { class C extends A, B() { interface I extends A, B() { parse, and only the checker objects (TS2500, TS1174, TS2499)-// A call or a parenthesis that follows the keyword `extends` or `implements` (heritageKeywordAt), `new`, directly or as the last of the names that dots join (`a.b.mixin`), or that follows a comma of such a list (heritageListBefore), may be one, so it is not taken for a head.+// A call or a parenthesis that follows the keyword `extends` or `implements` (heritageKeywordAt), `new`, directly or as the last of the names that dots join (`a.b.mixin`), or that follows a comma of such a list (heritageListBefore), may be one, so it is not taken for a head — but for a `new` that+// names a field of a class and is ended by a line break, whose call is the head of the next member (newNamesField).// Neither is a call that follows anything the names do not go back to: a `)`, a `]`, a `>` (type arguments), a `?.` or a `!`, an escape, a letter beyond ASCII — what is not read is not a head. A comma that no heritage list holds separates the members of an object// literal, and the call after it is a method's head (`{ a: 1, m() { … } }`); and a word that a class's head does not lead to is no keyword but a name, whose call is a head all the same (`class C { implements() { … } }`, `{ extends() { … } }`).function closesBodyHead(out, close) {@@ -1235,13 +1236,31 @@ function closesBodyHead(out, close) {if (before.ch !== '.') {const { token, index } = tokenBeforeAngle(out, name.start + 1);if (token === ',') return !heritageListBefore(out, index);- return token !== 'new' && !heritageKeywordAt(out, token, index - token.length);+ if (token === 'new') return newNamesField(out, index, name.start + 1);+ return !heritageKeywordAt(out, token, index - token.length);}name = wordBefore(out, before.index);}return false;}+// Whether the `new` that ends at `index`, which stands right before the name that starts at `nameStart` of the call that a `{` follows, is the name of a class field that a line break ends, and no operator: the call is then the head of the next member, a method, and its braces are+// its body. The two are the same text up to the `{`:+// class C extends new⏎ Base() { the operator: `Base()` is an element of the heritage, and the braces hold members+// class C { new⏎ render() { a field named `new` and a method: a line break ends a field with no `;` (https://tc39.es/ecma262/#sec-automatic-semicolon-insertion)+// What stands before the `new` tells them apart. A field begins a member of a class, so a member may begin at it and the braces around it are a class's body (the head of one that is read back to its `class`, as a class that is complete is: a block, the body of a function and the braces of an object+// literal have no such field); and it follows no element of a heritage, which is what the operator's `new` does — the keyword that begins the list (`implements⏎ new⏎ Base() {`: for memberMayBeginAt a line break after a word that may name a field ends a member) or a comma of the list.+// A `new` and a name on one line are no field and member (a field's name is followed by a `;`, a `}` or a line break), and what is not told stays the operator, as it was: the braces after the call may hold members.+function newNamesField(out, index, nameStart) {+ const start = index - 'new'.length + 1;+ if (cutsWord(out, start - 1) || !lineBreakBetween(out, index + 1, nameStart)) return false;+ const body = openerBefore(out, start);+ if (body.ch !== '{' || !memberMayBeginAt(out, start, 0) || completedClassStart(out, body.index, start) < 0) return false;+ const before = tokenBeforeAngle(out, start);+ if (before.token === ',') return !heritageListBefore(out, before.index);+ return !heritageKeywordAt(out, before.token, before.index - before.token.length);+}+// Whether `word`, which ends right before a `(` or a name and starts after the character at `before`, is the keyword `extends` or `implements` of a heritage clause, whose elements follow it, and not a name that spells it: a method (`class C { implements() { … } }`), a function// (`function implements() { … }`), a property or a value of an object literal (`{ extends() {} }`, `{ a: implements, m() {} }`). The keyword follows the head of a class or an interface — its name, its type parameters, another heritage clause — and that head is read back from the word to// `class` or `interface` (readHeritageBack, which reads what a head holds). A name stands after what a head has no place for — a `{` that nothing closed, a `;`, a `:`, an `=`, a modifier, a line break after a member — and the scan stops there; a decorator is read through, as the one of a@@ -1271,6 +1290,9 @@ function heritageListBefore(out, comma) {// What readHeritageBack answers: where the `class` or the `interface` that begins the head stands (a heritage is there), NO_HERITAGE (none is), or HERITAGE_UNREAD, where an escape or a window that ended first left it open (a heritage may be there).const NO_HERITAGE = -1;const HERITAGE_UNREAD = -2;+// How many class expressions may stand one in the head of the other with no parenthesis between them (`class extends class extends class {} {} {`), for the scan that reads a head alone (`flat`): it counts the braces that it crosses, and stops at the limit. A head that+// is nested deeper — none that a page has — is read as it was: no class that is complete. The limit is also what keeps the head of every method of an object literal from being read back over all the methods before it, whose braces are crossed too until a `class` is wanted for them.+const HEAD_NESTING = 4;// The scan behind heritageListBefore (`list`: the elements of a list, read back from a comma to the keyword that begins it) and heritageKeywordAt (not `list`: the head of a class or an interface, read back from a keyword to `class` or `interface`). The two read the same tokens; they differ// in the word that ends them: a keyword `extends` or `implements` for a list — which is a heritage's only where a head leads to it, so the scan of the head decides — and `class` or `interface` for a head. A property (`a.class`) is neither.@@ -1278,24 +1300,30 @@ const HERITAGE_UNREAD = -2;// const registry = { Adapter: class extends Base {}, render() { … } }; the comma and `render` come after a class that is complete: the braces of `render` are a method's body// class Q {}⏎function implements() { … } `implements` names a function// completedClassStart reads such braces back to their class; the scan goes on from before its `class`, where what stands is what the class is the value or the element of: a `:` or an `=` (a value: no heritage), an `extends`, an `implements` or a `,` (an element of a list:-// `class C extends class {} implements (B) {` has the heritage of C), a `;` or the start of the source. `flat` reads such a head alone, to its `class`, and crosses no braces: the scan of a list reads a head for each braces that it meets, and one that read the heads-// of all the braces before them would read them all again for each (a run of methods in an object literal).+// `class C extends class {} implements (B) {` has the heritage of C), a `;` or the start of the source. `flat` reads such a head alone, to its `class`. The braces at its own level are crossed only as the bodies of class expressions (`class extends class {} {`: the head of the base is read on from before its `class`, as the head of the element it is). Braces are crossed where+// what stands before them ends a head (endsClassHead: not after `extends`, `implements`, a comma or `new`, where they are an object literal's) and are counted; a `class` that is read takes one off, and the head is read where none is left. A function expression has no `class` for its braces — the scan meets its `function` — so its+// head is not read (no class that is complete), and no more than HEAD_NESTING braces are crossed at a time: the scan of a list reads a head for each braces that it meets, and one that read the heads of all the braces before them would read them all again for each (a run of methods in an object literal).function readHeritageBack(out, from, list, flat = false) {let brackets = 0; // the closing brackets read whose opener is not read yetlet angles = 0; // the same for the `>` that ends type arguments+ let pending = 0; // flat: the braces at the head's own level that are crossed and whose `class` is not read yet+ let nested = false; // flat: the head holds a class expression, read wholelet k = from - 1;for (; k >= 0 && from - k <= LOOKAHEAD; k -= 1) {const c = out[k];if (c === ')' || c === ']' || c === '}') {- // Braces at the head's own level are no part of a head that is read alone.- if (flat && c === '}' && brackets === 0 && angles === 0) return NO_HERITAGE;brackets += 1;} else if (c === '(' || c === '[' || c === '{') {if (brackets === 0) return NO_HERITAGE;brackets -= 1;- if (c === '{' && brackets === 0 && angles === 0 && !flat) {- const head = completedClassStart(out, k, from);- if (head >= 0) k = head;+ if (c === '{' && brackets === 0 && angles === 0) {+ if (!flat) {+ const head = completedClassStart(out, k, from);+ if (head >= 0) k = head;+ } else if (!endsClassHead(out, k, from - LOOKAHEAD) || ++pending > HEAD_NESTING) {+ // The braces are no class's body where nothing that ends a head stands before them (`extends {} {`, `, {} {`: an object literal), or are too many.+ return NO_HERITAGE;+ }}} else if (brackets > 0) {continue;@@ -1322,11 +1350,17 @@ function readHeritageBack(out, from, list, flat = false) {if (flat && word === 'function') return NO_HERITAGE;if (list && (word === 'extends' || word === 'implements')) return readHeritageBack(out, start, false);// A class may be named `interface` (`class interface {}`): the `class` before the name is the head's.- if (!list && (word === 'class' || (word === 'interface' && wordBefore(out, start).word !== 'class'))) return start;+ if (!list && (word === 'class' || (word === 'interface' && wordBefore(out, start).word !== 'class'))) {+ if (pending === 0) return start;+ // The `class` of a class expression whose braces were crossed: it belongs to the head that those braces are the body of, and the one that holds it is read on.+ if (word === 'interface') return NO_HERITAGE;+ pending -= 1;+ nested = true;+ }}k = start;- } else if (isTrivia(c) || ',.!*/\'"`'.includes(c) || (c === '@' && !flat)) {- // The `@` of a decorator on a class expression, which is an element like the class it decorates: `class C implements new @d class {}, B() {`.+ } else if (isTrivia(c) || ',.!*/\'"`'.includes(c) || (c === '@' && (!flat || nested))) {+ // The `@` of a decorator on a class expression, which is an element like the class it decorates: `class C implements new @d class {}, B() {`. A head that is read alone has none of its own, but its class expressions have.continue;} else if ((c === '+' || c === '-') && /[eE]/.test(out[k - 1] || '') && /[\d.]/.test(out[k - 2] || '')) {// The sign of a number's exponent, which belongs to the one token that `1e+5` is.@@ -1352,25 +1386,27 @@ function significantBefore(out, at, floor) {}// Where the class whose body begins with the `{` at `open` starts — the index of its `class` or its `interface` — or NO_HERITAGE where the braces are no class's body, for the scan that readHeritageBack makes back from `from`. A class is complete, and crossed by the scan,-// when what stands before its `{` ends a head and a head that no braces interrupt leads from it back to a `class`: a name (`class Named {`, `class extends Base {`, `class {`), the `)` of a call (`extends mixin(A) {`), a `]`, the `>` of type arguments (`extends Base<T> {`),-// a `!` or a literal. Braces are an object literal's, which a head has no place for, after `extends`, `implements` (but for a class named so: `class implements {}`) or any other word that takes an operand (EXPR_START_WORDS), a comma, a `:`, an `=` or an operator; the braces+// when what stands before its `{` ends a head and a head that no braces interrupt — but the bodies of class expressions, which a head may hold (`class extends class {} {`) — leads from it back to a `class`: a name (`class Named {`, `class extends Base {`, `class {`), the `)` of a call (`extends mixin(A) {`), a `]`, the `>` of type arguments (`extends Base<T> {`),+// a `!` or a literal, or the `}` that ends the body of such a class expression (what the scan makes of it is readHeritageBack's). Braces are an object literal's, which a head has no place for, after `extends`, `implements` (but for a class named so: `class implements {}`) or any other word that takes an operand (EXPR_START_WORDS), a comma, a `:`, an `=` or an operator; the braces// of an arrow function (`=> {`) and of a function (`function () {`) are read back to no `class` either, and a JSX container (`<p>{a}</p>`) to the `<` of its tag, which no program that parses has a `class` before (an element follows an operator or a separator). What is not told is left// to the scan, which then meets the class's own `extends` and `class` as it would the keyword of a list: the guess side, since the braces after the call may hold members.function completedClassStart(out, open, from) {- const floor = from - LOOKAHEAD;+ return endsClassHead(out, open, from - LOOKAHEAD) ? readHeritageBack(out, open, false, true) : NO_HERITAGE;+}++// Whether what stands before the `{` at `open`, no further back than `floor`, ends the head of a class, which the braces are the body of: a name that is no word that takes an operand, a `)`, a `]`, a `>`, a `!`, a literal, or the `}` of a class expression that the head ends in.+// Braces after anything else are an object literal's (`extends {`, `, {`, `= {`, `new {`) or a block's, and are no body of a class.+function endsClassHead(out, open, floor) {const before = significantBefore(out, open, floor);const c = before.ch;- let endsHead = false;- if (')]>!"\'`'.includes(c) && c !== '') {- endsHead = true;- } else if (c !== '' && isNamePart(c)) {- let start = before.index;- while (start > 0 && start > floor && isNamePart(out[start - 1])) start -= 1;- let word = '';- for (let q = start; q <= before.index; q += 1) word += out[q];- endsHead = !EXPR_START_WORDS.has(word) && (word !== 'implements' || wordBefore(out, start).word === 'class');- }- return endsHead ? readHeritageBack(out, open, false, true) : NO_HERITAGE;+ if (c === '') return false;+ if (')]>!"\'`}'.includes(c)) return true;+ if (!isNamePart(c)) return false;+ let start = before.index;+ while (start > 0 && start > floor && isNamePart(out[start - 1])) start -= 1;+ let word = '';+ for (let q = start; q <= before.index; q += 1) word += out[q];+ return !EXPR_START_WORDS.has(word) && (word !== 'implements' || wordBefore(out, start).word === 'class');}// Whether a member may begin at `at`, where a word or a `*` starts. After a separator it does; after a modifier on the same line it does if a member may begin at the modifier (`a in delete <U>(y)</U>` has an operator, not a modifier,@@ -4423,4 +4459,4 @@ function ellipsisFollowedByStatement(mask, k) {return STATEMENT_WORDS.has(word) || word === 'import' || word === 'export';}-module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES };+module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING };diff --git a/plugins/pcf/scripts/lint-pcf.js b/plugins/pcf/scripts/lint-pcf.jsindex a66f0c5d3..af8a2c854 100644--- a/plugins/pcf/scripts/lint-pcf.js+++ b/plugins/pcf/scripts/lint-pcf.js@@ -4,6 +4,7 @@const fs = require('node:fs');const path = require('node:path');const { parseArgs, validateFlags } = require('./lib/dataverse-auth.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const { loadMatrix } = require('./lib/pcf-matrix.js');const { parseManifest, lintManifest, diffManifests, findManifests } = require('./lib/pcf-manifest.js');const { booleanFlagError } = require('./lib/pcf-cli-flags.js');@@ -88,11 +89,15 @@ function parseFile(file) {}function usage(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${message}\n${USAGE}\n`);process.exit(1);}function emitJson(ok, payload) {+ // The findings of every manifest under a folder can be a long text, and the process exits right after printing them: blocking writes+ // put the whole text in the pipe first (on Linux and macOS a pipe's writes are queued, and process.exit does not wait for them — lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(JSON.stringify(payload) + '\n');if (!ok) process.stderr.write(`${payload.error || 'PCF manifest lint failed; see stdout JSON'}\n`);process.exit(ok ? 0 : 1);@@ -101,6 +106,7 @@ function emitJson(ok, payload) {if (require.main === module) {main().catch((err) => {const payload = { ok: false, error: String(err && err.message ? err.message : err) };+ makeWritesBlocking(process.stdout, process.stderr);process.stdout.write(`${JSON.stringify(payload)}\n`);process.stderr.write(`${payload.error}\n`);process.exit(1);diff --git a/plugins/pcf/scripts/pcf-build.js b/plugins/pcf/scripts/pcf-build.jsindex 4419de587..90947c815 100644--- a/plugins/pcf/scripts/pcf-build.js+++ b/plugins/pcf/scripts/pcf-build.js@@ -6,6 +6,7 @@ const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.jconst { loadMatrix } = require('./lib/pcf-matrix.js');const { findControlProject, buildControl, bundleFindings } = require('./lib/pcf-build.js');const { booleanFlagError } = require('./lib/pcf-cli-flags.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = `Usage:node scripts/pcf-build.js --project <dir> [--mode production|development] [--no-clean]`;@@ -14,6 +15,7 @@ const KNOWN = ['project', 'mode', 'no-clean'];const NEED_VALUE = ['project', 'mode'];function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}diff --git a/plugins/pcf/scripts/pcf-ci-build.js b/plugins/pcf/scripts/pcf-ci-build.jsindex 43a64525d..8d8deec7f 100644--- a/plugins/pcf/scripts/pcf-ci-build.js+++ b/plugins/pcf/scripts/pcf-ci-build.js@@ -15,6 +15,7 @@ const { runNodeScript, runNpm } = require('./lib/node-tool.js');const { runPac } = require('./lib/pac-exec.js');const { validateControlName, validatePublisherPrefix } = require('./lib/pcf-names.js');const { parseXml, findAll, attr } = require('./lib/xml-lite.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = `Usage:node scripts/pcf-ci-build.js [--all | --templates | --template <id> | --recipe <id>] [--latest] [--keep] [--package] [--npm-cli <path>]@@ -38,6 +39,7 @@ const EXPECTED_GATE_IDS = ['manifest', 'code', 'lint', 'test', 'build'];const DIAGNOSTIC_LIMIT = 2000;function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}diff --git a/plugins/pcf/scripts/pcf-doctor.js b/plugins/pcf/scripts/pcf-doctor.jsindex 005bd35e1..7ab5f28af 100644--- a/plugins/pcf/scripts/pcf-doctor.js+++ b/plugins/pcf/scripts/pcf-doctor.js@@ -14,6 +14,7 @@ const {collectToolchain,hasErrors,} = require('./lib/pcf-doctor.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = `Usage:node scripts/pcf-doctor.js [--project <dir>] [--hosts model,pages] [--needs build,push] [--npm-cli <path>]`;@@ -24,6 +25,7 @@ const KNOWN_HOSTS = ['model', 'pages'];const KNOWN_NEEDS = ['build', 'push'];function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}diff --git a/plugins/pcf/scripts/pcf-gates.js b/plugins/pcf/scripts/pcf-gates.jsindex 96dd38d1c..83f3c24ad 100644--- a/plugins/pcf/scripts/pcf-gates.js+++ b/plugins/pcf/scripts/pcf-gates.js@@ -9,6 +9,7 @@ const { loadMatrix } = require('./lib/pcf-matrix.js');const { findControlProject, buildControl, bundleFindings, pcfScriptsFailed, resolveOutRoot } = require('./lib/pcf-build.js');const { parseManifest, lintManifest } = require('./lib/pcf-manifest.js');const { gateSources } = require('./lib/pcf-code-gate.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = `Usage:node scripts/pcf-gates.js --project <dir> [--hosts model,pages] [--skip lint,test,build]`;@@ -18,6 +19,7 @@ const NEED_VALUE = ['project', 'hosts', 'skip'];const GATE_IDS = ['manifest', 'code', 'lint', 'test', 'build'];function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}diff --git a/plugins/pcf/scripts/pcf-inventory.js b/plugins/pcf/scripts/pcf-inventory.jsindex 6887d10b1..274672bd4 100644--- a/plugins/pcf/scripts/pcf-inventory.js+++ b/plugins/pcf/scripts/pcf-inventory.js@@ -3,6 +3,7 @@const path = require('node:path');const { parseArgs, validateFlags } = require('./lib/dataverse-auth.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const {WHERE_USED_CAVEAT,makePcfSdk,@@ -18,6 +19,7 @@ const KNOWN = ['env', 'control', 'include-managed', 'where-used', 'workspace'];const NEED_VALUE = ['env', 'control', 'workspace'];function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}@@ -119,6 +121,9 @@ function missingControlMessage(controlName) {}function writeResult(ok, payload) {+ // A listing of an org's controls can be megabytes, and the process exits right after printing it: blocking writes put the whole+ // text in the pipe first (on Linux and macOS a pipe's writes are queued, and process.exit does not wait for them — lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);if (ok) {process.stdout.write(JSON.stringify(payload) + '\n');process.exit(0);diff --git a/plugins/pcf/scripts/pcf-push.js b/plugins/pcf/scripts/pcf-push.jsindex cce914307..c0cd99aab 100644--- a/plugins/pcf/scripts/pcf-push.js+++ b/plugins/pcf/scripts/pcf-push.js@@ -5,6 +5,7 @@ const fs = require('node:fs');const path = require('node:path');const nodeProcess = require('node:process');const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');+const { redactOutput, makeWritesBlocking } = require('./lib/output-redaction.js');const { runPac } = require('./lib/pac-exec.js');const { validatePublisherPrefix, validateSolutionUniqueName, validateNamespace, validateControlName, orgControlName } = require('./lib/pcf-names.js');const { findControlProject } = require('./lib/pcf-build.js');@@ -68,6 +69,7 @@ const HINTS = [];function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}@@ -365,7 +367,9 @@ function writeReceipt(projectDir, data) {let fd = null;try {fd = fs.openSync(tempPath, 'wx');- fs.writeFileSync(fd, `${JSON.stringify(receipt, null, 2)}\n`, 'utf8');+ // The receipt carries the service's own words (`registered.reason` is the text of a refused read), and a service may repeat the access token it was sent in them — folded onto several lines or with a JSON escape,+ // which `scrubSecrets` does not read. So the whole text goes through the one function that keeps every token this process obtained out of what it writes (lib/output-redaction.js), as model-apps' file writers do.+ fs.writeFileSync(fd, redactOutput(`${JSON.stringify(receipt, null, 2)}\n`), 'utf8');fs.closeSync(fd);fd = null;fs.renameSync(tempPath, receiptPath);diff --git a/plugins/pcf/scripts/pcf-scaffold.js b/plugins/pcf/scripts/pcf-scaffold.jsindex 420c75b44..1fc3a6366 100644--- a/plugins/pcf/scripts/pcf-scaffold.js+++ b/plugins/pcf/scripts/pcf-scaffold.js@@ -11,6 +11,7 @@ const {planScaffold,writeScaffold,} = require('./lib/pcf-scaffold.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = `Usage:node scripts/pcf-scaffold.js --list@@ -32,6 +33,7 @@ const KNOWN = [const NEED_VALUE = ['template', 'namespace', 'name', 'out', 'recipe', 'hosts', 'display-name', 'description', 'npm-cli'];function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}diff --git a/plugins/pcf/scripts/pcf-upgrade.js b/plugins/pcf/scripts/pcf-upgrade.jsindex a99443b36..4d491d368 100644--- a/plugins/pcf/scripts/pcf-upgrade.js+++ b/plugins/pcf/scripts/pcf-upgrade.js@@ -4,6 +4,7 @@const path = require('node:path');const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');const { runUpgrade } = require('./lib/pcf-upgrade.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = `Usage:node scripts/pcf-upgrade.js [--project <dir>] [--hosts model,pages] [--apply] [--steps <id,...>] [--allow-dirty] [--no-install] [--npm-cli <path>]`;@@ -13,6 +14,7 @@ const NEED_VALUE = ['project', 'hosts', 'steps', 'npm-cli'];const KNOWN_HOSTS = ['model', 'pages'];function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}diff --git a/plugins/pcf/scripts/telemetry-config.js b/plugins/pcf/scripts/telemetry-config.jsindex eaa29daef..f3f9597ab 100644--- a/plugins/pcf/scripts/telemetry-config.js+++ b/plugins/pcf/scripts/telemetry-config.js@@ -10,6 +10,7 @@ const {} = require('./lib/telemetry/lib/user-config.js');const { pluginLogDir, latestSessionLog } = require('./lib/telemetry/lib/local-log.js');const { isProvisioned } = require('./lib/telemetry/resolver.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = 'USAGE: node scripts/telemetry-config.js [--action <on|off|status>]';@@ -18,6 +19,7 @@ function main(argv = process.argv.slice(2)) {const flagError = validateFlags(argv, { known: ['action'], needValue: ['action'] });const action = flags.action || 'status';if (flagError || positional.length || !['on', 'off', 'status'].includes(action)) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${flagError || 'Action must be on, off or status.'}\n${USAGE}\n`);process.exit(1);}diff --git a/plugins/pcf/scripts/tests/helpers/big-results.js b/plugins/pcf/scripts/tests/helpers/big-results.jsnew file mode 100644index 000000000..c718553e5--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/big-results.js@@ -0,0 +1,18 @@+'use strict';+// The texts of megabytes that tests/pcf-result-whole-before-exit.test.js has the plugin print, built the same way in the process that prints them and in the test that checks what arrived.+const NOTE = 'The platform answered with a diagnostic that says nothing about credentials.';++// A table of `count` rows, as a listing prints one: 30,000 rows are about 3.5 MB, some fifty times what a pipe takes at once (64 KiB on Linux).+const rows = (count) => Array.from({ length: count }, (_, i) => ({ id: i, name: `row ${i}`, note: NOTE }));+// A text of about the same size, as an error that quotes a service's answer is.+const longText = (count) => Array.from({ length: count }, (_, i) => `line ${i}: ${NOTE}`).join(' ');+// `count` custom controls as lib/pcf-dataverse.js listCustomControls returns them; every other one is managed.+const controls = (count) => Array.from({ length: count }, (_, i) => ({+ id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,+ name: `contoso_Contoso.Controls.Control${i}`,+ version: '1.0.0',+ isManaged: i % 2 === 1,+ componentState: 0,+}));++module.exports = { rows, longText, controls };diff --git a/plugins/pcf/scripts/tests/helpers/fake-auth-check-preload.js b/plugins/pcf/scripts/tests/helpers/fake-auth-check-preload.jsnew file mode 100644index 000000000..d2ba4c77e--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/fake-auth-check-preload.js@@ -0,0 +1,28 @@+'use strict';+// Loaded with `node --require` ahead of check-auth.js (this plugin's copy of model-apps' script), for tests/pcf-printers-whole-before-exit.test.js: the+// Azure CLI and PAC answer as for a signed-in [email protected], a Dataverse token is in hand, and WhoAmI is refused with HTTP 500 whose diagnostic is+// FAKE_WHOAMI_DIAGNOSTIC_SIZE characters long (helpers/huge-failure-preload.js hugeFailureText('whoami', size)) — the service's whole message, which the+// result carries as `whoAmI.message`. No process is started and no request is sent; the script and the rest of its helpers are the real ones.+const path = require('node:path');+const { hugeFailureText } = require('./huge-failure-preload.js');++const lib = path.join(__dirname, '..', '..', 'lib');+const authPath = require.resolve(path.join(lib, 'dataverse-auth.js'));+const runnerPath = require.resolve(path.join(lib, 'process-runner.js'));+const auth = require(authPath);+const runner = require(runnerPath);+const diagnostic = hugeFailureText('whoami', Number(process.env.FAKE_WHOAMI_DIAGNOSTIC_SIZE || 0));++require.cache[authPath].exports = {+ ...auth,+ getAuthTokenAsync: async () => 'synthetic-check-auth-token',+ dataverseRequest: async () => ({ status: 500, data: { error: { message: diagnostic } } }),+};+// `az account show` and `pac org who`, as check-auth.js starts them: a callback with the CLI's stdout, and a handle it can cancel.+require.cache[runnerPath].exports = {+ ...runner,+ execFileAsync: (command, args, options, done) => {+ setImmediate(() => done(null, command === 'pac' ? 'Connected as [email protected]\n' : '[email protected]\n', ''));+ return { stdin: { end() {} }, kill() {} };+ },+};diff --git a/plugins/pcf/scripts/tests/helpers/fake-big-org-preload.js b/plugins/pcf/scripts/tests/helpers/fake-big-org-preload.jsnew file mode 100644index 000000000..da125be95--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/fake-big-org-preload.js@@ -0,0 +1,21 @@+'use strict';+// Loaded with `node --require` ahead of pcf-inventory.js or verify-pcf.js, for tests/pcf-result-whole-before-exit.test.js: lib/pcf-dataverse.js — the one module through which those scripts reach an org — answers+// FAKE_BIG_ORG_CONTROLS custom controls (helpers/big-results.js controls), or, with FAKE_BIG_ORG_FAILURE, refuses to make the SDK with an error whose message is that many lines (longText). Every other export is the+// real module's. So a script prints a result of megabytes as a process, with no Dataverse and no Azure CLI.+const path = require('node:path');+const { controls, longText } = require('./big-results.js');++const target = require.resolve(path.join(__dirname, '..', '..', 'lib', 'pcf-dataverse.js'));+const real = require(target);+const count = Number(process.env.FAKE_BIG_ORG_CONTROLS || 0);+const failure = Number(process.env.FAKE_BIG_ORG_FAILURE || 0);++// The script's own `require('./lib/pcf-dataverse.js')` resolves to the same file, so it is handed this object from the module cache.+require.cache[target].exports = {+ ...real,+ makePcfSdk: async () => {+ if (failure) throw new Error(longText(failure));+ return {};+ },+ listCustomControls: async () => controls(count),+};diff --git a/plugins/pcf/scripts/tests/helpers/huge-failure-preload.js b/plugins/pcf/scripts/tests/helpers/huge-failure-preload.jsnew file mode 100644index 000000000..5709ad869--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/huge-failure-preload.js@@ -0,0 +1,30 @@+'use strict';+// Loaded with `node --require` ahead of a script, for tests/pcf-printers-whole-before-exit.test.js: makes a script's OWN failure printers print a text of+// HUGE_FAILURE_SIZE characters — with no command line that long (Windows allows 32,767 characters, Linux 128 KiB per argument):+// HUGE_FAILURE=flag validateFlags (lib/dataverse-auth.js) answers every call with a message that long, which each script prints as its usage error+// (check-auth.js as the message of its usage blocker, on stdout);+// HUGE_FAILURE=throw parseArgs throws an error with that message.+// Everything else is the real module, and the code that prints the text and ends the process is the script's own. A test requires this file for+// hugeFailureText (HUGE_FAILURE is not set in the test's own process, so nothing is replaced there). The same helper as model-apps'+// tests/helpers/huge-failure-preload.js: this plugin's suite runs on its own.+const path = require('node:path');++// The text, recognisable at both ends so that a test can tell a whole one from one cut short.+function hugeFailureText(kind, size) {+ return `${kind}-failure<${'0123456789'.repeat(Math.ceil(size / 10)).slice(0, size)}>`;+}++module.exports = { hugeFailureText };++if (process.env.HUGE_FAILURE) {+ const target = require.resolve(path.join(__dirname, '..', '..', 'lib', 'dataverse-auth.js'));+ const real = require(target);+ const kind = process.env.HUGE_FAILURE;+ const text = hugeFailureText(kind, Number(process.env.HUGE_FAILURE_SIZE || 0));+ // A script takes its helpers from the module cache when it is loaded, so it is handed this object.+ require.cache[target].exports = {+ ...real,+ ...(kind === 'flag' ? { validateFlags: () => text } : {}),+ ...(kind === 'throw' ? { parseArgs: () => { throw new Error(text); } } : {}),+ };+}diff --git a/plugins/pcf/scripts/tests/helpers/push-token-child.js b/plugins/pcf/scripts/tests/helpers/push-token-child.jsnew file mode 100644index 000000000..98f9d4bda--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/push-token-child.js@@ -0,0 +1,58 @@+'use strict';+// A REAL PROCESS that runs `pcf-push.js` end to end — the real SDK bundle, the production Azure CLI-token client and the real result printer — over a fake `pac` and a fake Dataverse that refuses the read that confirms the push+// (HTTP 403) with a diagnostic repeating the access token the process sent, folded onto several lines, so a test can read what reached the process's descriptors and its folders: stdout, stderr, the receipt+// `pcf-receipt.json` and the SDK's workspace. Run by tests/pcf-push-token.test.js:+// node push-token-child.js <project folder> <how the diagnostic spells the token>+// `how` is `folded` (every eight characters, as a gateway wraps a long header), `plain`, `escaped-fold` (the fold written as the JSON escape `\r\n`, as a diagnostic that was itself JSON holds it) or `none` (a diagnostic with no token in it).+const fs = require('node:fs');+const path = require('node:path');+const Module = require('node:module');++const SCRIPTS = path.resolve(__dirname, '..', '..');+const { createAzHttpClient } = require(path.join(SCRIPTS, 'lib', 'sdk-http-client.js'));+const data = require(path.join(SCRIPTS, 'lib', 'pcf-dataverse.js'));+const { TOKEN } = require('./push-token.js');++const [, , project, how = 'folded'] = process.argv;+const ORG = 'https://contoso.crm.dynamics.com';+const spelling = {+ plain: TOKEN,+ folded: TOKEN.match(/.{1,8}/g).join('\r\n '),+ 'escaped-fold': TOKEN.match(/.{1,8}/g).join('\\r\\n '),+ none: 'nothing secret here',+}[how];+if (spelling === undefined) throw new Error(`unknown spelling ${how}`);++fs.mkdirSync(path.join(project, 'StarRating'), { recursive: true });+fs.writeFileSync(path.join(project, 'package.json'), JSON.stringify({ name: 'token-receipt', version: '1.0.0' }));+fs.writeFileSync(path.join(project, 'StarRating.pcfproj'), '<Project Sdk="Microsoft.NET.Sdk"><Import Project="$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props" /><PropertyGroup><Name>StarRating</Name><PcfBuildMode>production</PcfBuildMode></PropertyGroup></Project>');+fs.writeFileSync(path.join(project, 'StarRating', 'ControlManifest.Input.xml'), '<manifest><control namespace="Contoso.Controls" constructor="StarRating" version="1.2.3" display-name-key="StarRating" description-key="StarRating description" control-type="standard"><property name="value" display-name-key="Value" of-type="Whole.None" usage="bound" required="false" /><resources><code path="index.ts" order="1" /></resources></control></manifest>');++// The service: the table's metadata answers, and the read of the registered controls is refused with the diagnostic.+const client = createAzHttpClient(ORG, {+ getToken: () => TOKEN,+ sleep: async () => {},+ request: async ({ method, url }) => {+ if (method !== 'GET') throw new Error('only reads are expected');+ if (/EntityDefinitions\(LogicalName='customcontrol'\)/.test(decodeURIComponent(url))) return { statusCode: 200, headers: {}, body: JSON.stringify({ EntitySetName: 'customcontrols' }) };+ if (/\/customcontrols(?:\?|$)/.test(url)) return { statusCode: 403, headers: {}, body: JSON.stringify({ error: { code: '0x80040220', message: `Header check failed for value ${spelling}` } }) };+ throw new Error(`unexpected read ${url}`);+ },+});++// pcf-push.js is loaded as the script would be, with the two things that would leave this machine replaced: the `pac pcf push` it runs (it succeeds) and the HttpClient its SDK is made with.+const filename = path.join(SCRIPTS, 'pcf-push.js');+const loaded = new Module(filename, module);+loaded.filename = filename;+loaded.paths = Module._nodeModulePaths(SCRIPTS);+const realRequire = loaded.require.bind(loaded);+loaded.require = (id) => {+ if (id === './lib/pac-exec.js') return { runPac: () => ({ status: 0, stdout: 'fake push succeeded', stderr: '' }) };+ if (id === './lib/pcf-dataverse.js') return { ...data, makePcfSdk: (env, workspace) => data.makePcfSdk(env, workspace, client) };+ return realRequire(id);+};+loaded._compile(fs.readFileSync(filename, 'utf8'), filename);+loaded.exports.main(['--project', project, '--env', ORG, '--publisher-prefix', 'new']).catch((error) => {+ process.stderr.write(`the child failed: ${error && error.stack ? error.stack : error}\n`);+ process.exitCode = 3;+});diff --git a/plugins/pcf/scripts/tests/helpers/push-token.js b/plugins/pcf/scripts/tests/helpers/push-token.jsnew file mode 100644index 000000000..d364797dc--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/push-token.js@@ -0,0 +1,16 @@+'use strict';+// A synthetic access token shaped the way Azure issues one — three base64url parts joined by dots, the first two being small JSON documents — for the tests that prove a token never reaches what `pcf-push.js` writes.+const PARTS = [+ Buffer.from('{"alg":"RS256","typ":"JWT","test":"synthetic"}').toString('base64url'),+ Buffer.from('{"aud":"synthetic","test":"not-a-real-credential"}').toString('base64url'),+ 'syntheticSignaturePartNotARealCredential',+];+const TOKEN = PARTS.join('.');+// What must not be readable in anything the push wrote: the token and each part of it.+const SECRETS = [TOKEN, ...PARTS];++// The ways a reader gets a token back out of a text: as it is, with the white space taken out (a fold), and with the JSON escapes of a line break taken out as well (a body that was JSON, written as JSON again).+const views = (text) => [text, text.replace(/\s+/g, ''), text.replace(/\\+[rntf]/g, '').replace(/\s+/g, '')];+const leaksIn = (text, secrets = SECRETS) => secrets.filter((secret) => views(String(text)).some((view) => view.includes(secret)));++module.exports = { PARTS, TOKEN, SECRETS, leaksIn };diff --git a/plugins/pcf/scripts/tests/helpers/queued-stdio-preload.js b/plugins/pcf/scripts/tests/helpers/queued-stdio-preload.jsnew file mode 100644index 000000000..ed0a1efde--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/queued-stdio-preload.js@@ -0,0 +1,12 @@+'use strict';+// Loaded with `node --require` ahead of a script: gives the script the stdout and stderr a pipe gets on Linux and macOS — a `net.Socket` over the pipe, whose writes are QUEUED when the pipe cannot take them at+// once — on every platform. Node makes a pipe on descriptor 1 or 2 synchronous on Windows (lib/net.js: "Make stdout and stderr blocking on Windows"), so a script run there with its own stdout can never show what a+// reader on Linux or macOS gets when `process.exit` follows a large write (https://nodejs.org/api/process.html#a-note-on-process-io). Here `process.stdout` and `process.stderr` are sockets over descriptors 3 and 4+// instead, which Node leaves asynchronous everywhere; the test spawns the script with `stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe']` and reads what it printed from `output[3]` and `output[4]`.+// The same helper as model-apps' tests/helpers/queued-stdio-preload.js: this plugin's suite runs on its own.+const net = require('node:net');++for (const [name, fd] of [['stdout', 3], ['stderr', 4]]) {+ const socket = new net.Socket({ fd, readable: false, writable: true });+ Object.defineProperty(process, name, { configurable: true, enumerable: true, get: () => socket });+}diff --git a/plugins/pcf/scripts/tests/helpers/write-order-preload.js b/plugins/pcf/scripts/tests/helpers/write-order-preload.jsnew file mode 100644index 000000000..6d6c3efcf--- /dev/null+++ b/plugins/pcf/scripts/tests/helpers/write-order-preload.js@@ -0,0 +1,35 @@+'use strict';+// Loaded with `node --require` — after helpers/queued-stdio-preload.js when a test uses both — by the tests that hold a printer to the ORDER of its+// last writes. It records each time this process makes its stdout or stderr blocking (`setBlocking(true)` on the stream's handle: what+// lib/output-redaction.js makeWritesBlocking calls) and each write to either, and when the process exits it writes the record to the file that+// WRITE_ORDER_FILE names, for example `{"code":1,"events":["blocking stdout","blocking stderr","write stderr"]}`.+//+// Why an order: it does not depend on the platform, the runtime or how far a reader reads ahead, so a printer that writes before it makes its stream+// blocking fails such a test on every run. A test of the text that arrives can pass by luck: a reader that pauses its stream still lets the runtime+// read ahead below it, and on Windows a printer that did not make its writes blocking delivered a megabyte whole to a held reader under Node 20 (and+// 65,536 characters of it under Node 22). Nothing else about the streams changes: their own `write` and `setBlocking` are called with what they+// were given, and what they answer is answered.+const fs = require('node:fs');++const file = process.env.WRITE_ORDER_FILE;+if (file) {+ const events = [];+ for (const name of ['stdout', 'stderr']) {+ const stream = process[name];+ const handle = stream && stream._handle;+ if (handle && typeof handle.setBlocking === 'function') {+ const setBlocking = handle.setBlocking;+ handle.setBlocking = function setBlockingRecorded(flag, ...rest) {+ if (flag === true) events.push(`blocking ${name}`);+ return setBlocking.call(this, flag, ...rest);+ };+ }+ const write = stream.write;+ stream.write = function writeRecorded(...args) {+ events.push(`write ${name}`);+ return write.apply(this, args);+ };+ }+ // Added before anything the script adds, so it runs first: a write made by a later 'exit' listener is not the printer's, and is not recorded.+ process.on('exit', (code) => fs.writeFileSync(file, JSON.stringify({ code, events })));+}diff --git a/plugins/pcf/scripts/tests/pcf-exit-writes-inventory.test.js b/plugins/pcf/scripts/tests/pcf-exit-writes-inventory.test.jsnew file mode 100644index 000000000..4ea08dfe1--- /dev/null+++ b/plugins/pcf/scripts/tests/pcf-exit-writes-inventory.test.js@@ -0,0 +1,212 @@+'use strict';+// A SYNTACTIC TRIPWIRE on the exits of pcf's own code — the same reader as model-apps' tests/exit-writes-inventory.test.js, kept here because this+// plugin's suite runs on its own. A script that writes and then ends the process at once must make its writes blocking first+// (lib/output-redaction.js makeWritesBlocking), or a pipe on Linux and macOS takes only what fits at once. This scan of the source fails when+// - an exit — `process.exit(…)`, an injectable `io.exit(…)` / `proc.exit(…)`, an `exit(<status>)`, or a call of a name bound to process.exit — has+// no makeWritesBlocking call before it in a block that also holds it, and is not listed in ALLOWED with the bound that makes it safe without one:+// it writes nothing, or only a constant text, or a value from a closed set;+// - the call that protects an exit comes after a write in its own block (with no `await` between them), or leaves out a stream that is written+// directly between it and the exit.+// It reads the source, not what runs: it shows that a new exit has a call before it, not that the call runs, or runs before every write that+// matters. What a process does is shown by pcf-printers-whole-before-exit.test.js and pcf-result-whole-before-exit.test.js.+//+// Read: every .js/.cjs/.mjs file under scripts/ and hooks/ but tests/, vendor/ and node_modules/, with comments and the contents of strings,+// templates and regular expressions blanked by lib/source-literals.js. A call protects only as a statement of its own — not as the body of an+// unbraced `if`, `else` or loop, an arrow function or an operand — and the innermost `{ … }` around it must also hold the exit; when it is the first+// statement of a `try` block, the block that holds that `try`. Known limits: a write in an enclosing block or in an earlier turn of the event loop is+// not compared with the call; a write through a helper (`emitResult`, a stream kept in a variable) is not seen; protection inside a called+// function is not seen; an exit reached through an alias of another form is not found; and control flow is not followed.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { blankLiterals } = require('../lib/source-literals.js');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const ROOTS = ['scripts', 'hooks'].map((dir) => path.join(PLUGIN_ROOT, dir));+const SKIPPED = new Set(['tests', 'vendor', 'node_modules']);+const EXIT = /\b(?:process|io|proc)\.exit\s*\(|(?<![.\w$])exit\(\s*\d/g;+const GUARD = /\bmakeWritesBlocking\s*\(/g;+// A name bound to process.exit — a reference that is not a call (`const exit = opts.exit || process.exit;`) or `const { exit } = process;`.+const ALIAS = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=[^;]*?\bprocess\.exit\b(?!\s*\()/g;+const DESTRUCTURED = /\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*process\b/g;+// A direct write, and the stream it goes to: a stream's own `write`, or the console — `log`, `info`, `debug`, `dir` and `table` print on stdout,+// `error`, `warn` and `trace` on stderr (https://nodejs.org/api/console.html#class-console).+const WRITE = /\b(process|io|proc)\.(stdout|stderr)\.write\s*\(|(?<![.\w$])console\.(log|info|debug|dir|table|error|warn|trace)\s*\(/g;+const CONSOLE_STREAM = { log: 'stdout', info: 'stdout', debug: 'stdout', dir: 'stdout', table: 'stdout', error: 'stderr', warn: 'stderr', trace: 'stderr' };++// The exits of one source text that no makeWritesBlocking call protects (`unprotected`, 1-based line numbers), and the protected ones whose call+// comes after a write of its block or leaves out a stream written before the exit (`misguarded`, one sentence each).+function readExits(source) {+ const blank = blankLiterals(source);+ const lineOf = (at) => source.slice(0, at).split('\n').length;+ const blocks = [];+ const open = [];+ for (let i = 0; i < blank.length; i += 1) {+ if (blank[i] === '{') open.push(i);+ else if (blank[i] === '}' && open.length) blocks.push([open.pop(), i]);+ }+ const innermost = (at) => blocks.filter(([a, b]) => a < at && at < b).reduce((best, block) => (!best || block[0] > best[0] ? block : best), null) || [-1, blank.length];+ const closing = (at) => {+ for (let i = at, depth = 0; i < blank.length; i += 1) {+ if (blank[i] === '(') depth += 1;+ else if (blank[i] === ')' && (depth -= 1) === 0) return i;+ }+ return blank.length;+ };+ // A statement of its own: what comes before the call (its receiver skipped — `outputRedaction.`, `require('…').`) is the start of the text, `{`,+ // `}` or `;`. After `)` it is the body of an `if (…)` or a loop; after `=>`, `&&`, `?` or `else` it runs only sometimes, or not here.+ const isStatement = (at) => {+ let i = at - 1;+ const skipSpace = () => { while (i >= 0 && /\s/.test(blank[i])) i -= 1; };+ skipSpace();+ while (blank[i] === '.') {+ i -= 1;+ skipSpace();+ if (blank[i] === ')') {+ for (let depth = 0; i >= 0; i -= 1) {+ if (blank[i] === ')') depth += 1;+ else if (blank[i] === '(' && (depth -= 1) === 0) break;+ }+ i -= 1;+ skipSpace();+ }+ while (i >= 0 && /[\w$]/.test(blank[i])) i -= 1;+ skipSpace();+ }+ return i < 0 || '{};'.includes(blank[i]);+ };+ const exits = new Set([...blank.matchAll(EXIT)].map((m) => m.index));+ const aliases = new Set([...blank.matchAll(ALIAS)].map((m) => m[1]));+ for (const m of blank.matchAll(DESTRUCTURED)) {+ for (const part of m[1].split(',')) {+ const [key, name] = part.split(':').map((word) => word.trim());+ if (key === 'exit') aliases.add(name || key);+ }+ }+ for (const name of aliases) for (const m of blank.matchAll(new RegExp(`(?<![.\\w$])${name.replace(/\$/g, '\\$')}\\s*\\(`, 'g'))) exits.add(m.index);+ const guards = [];+ for (const m of blank.matchAll(GUARD)) {+ // The declaration of the function itself (`function makeWritesBlocking(`) is not a call of it.+ if (/function\s+$/.test(blank.slice(Math.max(0, m.index - 16), m.index)) || !isStatement(m.index)) continue;+ const paren = m.index + m[0].length - 1;+ const names = blank.slice(paren + 1, closing(paren)).split(',').map((name) => name.replace(/\s+/g, '')).filter(Boolean);+ let [a, b] = innermost(m.index);+ if (a >= 0 && /\btry\s*$/.test(blank.slice(0, a)) && blank.slice(a + 1, m.index).trim() === '') [a, b] = innermost(a);+ guards.push({ at: m.index, a, b, names });+ }+ const writes = [...blank.matchAll(WRITE)].map((m) => ({ at: m.index, stream: m[1] ? `${m[1]}.${m[2]}` : `process.${CONSOLE_STREAM[m[3]]}` }));+ const unprotected = [];+ const misguarded = [];+ for (const at of [...exits].sort((x, y) => x - y)) {+ const by = guards.filter((guard) => guard.at < at && guard.a < at && at < guard.b);+ if (!by.length) {+ unprotected.push(lineOf(at));+ continue;+ }+ const first = by[0];+ for (const write of writes) {+ if (write.at > first.at && write.at < at && !by.some((guard) => guard.at < write.at && guard.names.includes(write.stream))) {+ misguarded.push(`the exit on line ${lineOf(at)}: ${write.stream} is written on line ${lineOf(write.at)}, and no makeWritesBlocking call before it names it`);+ }+ if (write.at > first.a && write.at < first.at && innermost(write.at)[0] === first.a && !/\bawait\b/.test(blank.slice(write.at, first.at))) {+ misguarded.push(`the exit on line ${lineOf(at)}: ${write.stream} is written on line ${lineOf(write.at)}, before the makeWritesBlocking call of its block (line ${lineOf(first.at)})`);+ }+ }+ }+ return { unprotected, misguarded };+}++const unprotectedExits = (source) => readExits(source).unprotected;++function productionFiles() {+ const files = new Set();+ const walk = (dir) => {+ if (!fs.existsSync(dir)) return;+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!SKIPPED.has(entry.name)) walk(full);+ } else if (/\.(?:c|m)?js$/.test(entry.name)) {+ files.add(full);+ }+ }+ };+ for (const root of ROOTS) walk(root);+ return [...files].sort();+}++const label = (file) => path.relative(PLUGIN_ROOT, file).split(path.sep).join('/');++const NOTHING = 'writes nothing before it ends';+const SANDBOX = 'the branch for a test\'s injected process object (`process !== global.process`): a real run goes through emitResult, which is protected';+const ALLOWED = {+ 'hooks/run-skill-pretool-telemetry.js': [7, `the telemetry hook ${NOTHING} on any path`],+ 'hooks/run-user-prompt-telemetry.js': [5, `the telemetry hook ${NOTHING} on any path`],+ 'hooks/validate-write-safety.js': [4, 'the kill switch and the not-a-write-tool path write nothing; the two debug lines (DEBUG=1 only) are constants'],+ 'scripts/check-version.js': [3, NOTHING],+ 'scripts/lib/telemetry/lib/emit-dispatcher.js': [1, `the detached dispatcher ${NOTHING}`],+ 'scripts/lib/telemetry/lib/telemetry-config.js': [4, 'the shared telemetry library\'s copy (shared/telemetry, copied into five plugins), which no pcf skill runs (the telemetry skill runs scripts/telemetry-config.js, protected); run by hand without --plugin: constant sentences and the plugin\'s own name (about 1.2 KB measured), and the config folder\'s path once or twice; under the 4 KiB any pipe takes at once unless that path is over 1,400 characters'],+ 'scripts/pcf-build.js': [1, SANDBOX],+ 'scripts/pcf-gates.js': [1, SANDBOX],+ 'scripts/resolve-interaction-mode.js': [1, 'main prints {"ok":true,"interactive",…,"reason"} with a reason from a closed set of three (under 120 bytes)'],+ 'scripts/run-tests.js': [2, 'a constant line, or the status of the test run, whose children wrote their own output'],+ 'scripts/write-pcf-plan.js': [2, `${SANDBOX}; or its USAGE constant (122 bytes and its line break) as its first output`],+};+test('the inventory reader: what protects an exit, what does not, and a call that comes after a write or leaves out a stream', () => {+ const source = [+ 'function printer(text) {',+ ' makeWritesBlocking(process.stdout, process.stderr);',+ ' if (text) { process.stdout.write(text); process.exit(0); }',+ ' process.exit(1);',+ '}',+ 'function other() {',+ ' if (a) { makeWritesBlocking(process.stderr); process.stderr.write("x"); process.exit(2); }',+ ' if (b) { process.stderr.write("y"); process.exit(3); }',+ '}',+ '// process.exit(4) in a comment, and "process.exit(5)" in a string',+ 'main().then((code) => process.exit(code));',+ 'const exit = opts.exit || process.exit; exit(6); exit(text ? 0 : 1);',+ 'io.exit(1); proc.exit(1);',+ 'function makeWritesBlocking(...streams) { process.exit(7); }',+ 'function skipped(text) { if (quiet) makeWritesBlocking(process.stdout); process.stdout.write(text); process.exit(0); }',+ 'function operand(text) { const later = () => makeWritesBlocking(process.stdout); process.stdout.write(text); process.exit(0); }',+ 'const { exit: quit } = process; quit(9);',+ 'function fatal(text) { try { makeWritesBlocking(process.stderr); process.stderr.write(text); } catch {} process.exit(1); }',+ 'function notFirst(text) { try { prepare(); makeWritesBlocking(process.stderr); process.stderr.write(text); } catch {} process.exit(1); }',+ 'function member(text) { require("./lib/output-redaction.js").makeWritesBlocking(process.stdout, process.stderr); console.log(text); process.exit(0); }',+ 'function wrongStream(text) { makeWritesBlocking(process.stderr); process.stdout.write(text); process.exit(0); }',+ 'function lateGuard(text) { process.stdout.write(text); makeWritesBlocking(process.stdout); process.exit(0); }',+ 'function viaConsole(text) { makeWritesBlocking(process.stdout); console.error(text); process.exit(1); }',+ 'async function earlierTurn(text) { process.stderr.write("working"); await done(); makeWritesBlocking(process.stdout, process.stderr); console.error(text); process.exit(1); }',+ 'function ended(text) { if (text) { makeWritesBlocking(process.stderr); process.stderr.write(text); process.exit(2); } makeWritesBlocking(process.stderr); process.stderr.write("none"); process.exit(2); }',+ ].join('\n');+ // Not protected: a branch without the call, a callback, an alias (called with a status, and without one), io/proc, an exit in the function itself,+ // a call in an unbraced if, a call in an arrow function, a destructured alias, and a call that is not the first statement of its try.+ assert.deepEqual(unprotectedExits(source), [8, 11, 12, 12, 13, 13, 14, 15, 16, 17, 19]);+ assert.deepEqual(readExits(source).misguarded, [+ 'the exit on line 21: process.stdout is written on line 21, and no makeWritesBlocking call before it names it',+ 'the exit on line 22: process.stdout is written on line 22, before the makeWritesBlocking call of its block (line 22)',+ 'the exit on line 23: process.stderr is written on line 23, and no makeWritesBlocking call before it names it',+ ]);+});++test('every exit of pcf\'s own code is protected, or listed with the bound that makes it safe — and nothing listed is gone; no protecting call comes after a write of its block or leaves out a stream', () => {+ const found = {};+ const misguarded = [];+ let exits = 0;+ for (const file of productionFiles()) {+ const source = fs.readFileSync(file, 'utf8');+ exits += [...blankLiterals(source).matchAll(EXIT)].length;+ const read = readExits(source);+ if (read.unprotected.length) found[label(file)] = read.unprotected;+ misguarded.push(...read.misguarded.map((finding) => `${label(file)}: ${finding}`));+ }+ assert.ok(exits > 50, `the scan read the plugin (${exits} exits)`);+ assert.deepEqual(misguarded, [], 'a makeWritesBlocking call that comes after a write of its block, or leaves out a stream written before the exit it protects');+ const unlisted = Object.keys(found).filter((file) => !ALLOWED[file]).map((file) => `${file}: lines ${found[file].join(', ')}`);+ assert.deepEqual(unlisted, [], 'an exit that is neither protected by makeWritesBlocking nor listed in ALLOWED with its bound');+ const changed = Object.entries(ALLOWED).filter(([file, [count]]) => (found[file] || []).length !== count)+ .map(([file, [count]]) => `${file}: listed ${count}, found ${(found[file] || []).length} (lines ${(found[file] || []).join(', ') || 'none'})`);+ assert.deepEqual(changed, [], 'a listed file whose unprotected exits changed: protect the new one, or update its count and bound');+});diff --git a/plugins/pcf/scripts/tests/pcf-printers-whole-before-exit.test.js b/plugins/pcf/scripts/tests/pcf-printers-whole-before-exit.test.jsnew file mode 100644index 000000000..8f6adee85--- /dev/null+++ b/plugins/pcf/scripts/tests/pcf-printers-whole-before-exit.test.js@@ -0,0 +1,216 @@+'use strict';+// A pcf script that writes and then ends the process at once must make its writes blocking first (lib/output-redaction.js makeWritesBlocking), or a+// pipe on Linux and macOS takes only what fits at once. pcf-result-whole-before-exit.test.js holds emitResult and the result printers of+// pcf-inventory.js, verify-pcf.js and lint-pcf.js; this file holds check-auth.js (this plugin's copy of model-apps' script), every script's usage+// error, and the write-safety hook's message. pcf-exit-writes-inventory.test.js is a syntactic tripwire for a new exit.+//+// Each case runs as a real process, with a text a megabyte long and with a small one, and is checked two ways:+// - THE ORDER (helpers/write-order-preload.js): the process records when it makes stdout or stderr blocking and when it writes to them, and each+// stream it wrote to must have been made blocking before its first write. An order does not depend on the platform, the runtime or how far+// anything reads ahead, so this is the check that fails, on every run, for a printer left without the call.+// - THE TEXT: the whole text arrives, with the exit status it always had — over the kind of pipe Linux and macOS give a script+// (helpers/queued-stdio-preload.js), whose reader holds back (its streams are paused until the process has ended, or has written and then+// written nothing more for a while), and over the process's own stdout and stderr, the reference the queued run must equal. Pausing stops the+// test from taking what arrives, not the runtime from reading ahead below it, so how much a printer without the call loses here depends on the+// runtime (on Windows: 65,536 characters of a megabyte under Node 22, all of it under Node 20). It shows what a reader gets; the order is the proof.+// The texts are made without a command line that long: helpers/huge-failure-preload.js makes the plugin's flag check answer with such a message;+// helpers/fake-auth-check-preload.js refuses check-auth.js's WhoAmI with such a diagnostic. A small text's bytes and exit status must be what they+// always were.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawn } = require('node:child_process');+const { hugeFailureText } = require('./helpers/huge-failure-preload.js');+const { validateFlags } = require('../lib/dataverse-auth.js');++const SCRIPTS = path.join(__dirname, '..');+const HOOKS = path.join(SCRIPTS, '..', 'hooks');+const QUEUED = path.join(__dirname, 'helpers', 'queued-stdio-preload.js');+const ORDER = path.join(__dirname, 'helpers', 'write-order-preload.js');+const HUGE = path.join(__dirname, 'helpers', 'huge-failure-preload.js');+const FAKE_AUTH = path.join(__dirname, 'helpers', 'fake-auth-check-preload.js');+const ENV_URL = 'https://contoso.crm.dynamics.com';+const BIG = 1024 * 1024;+const MODES = ['queued', 'own'];+const QUIET_MS = 300;+const CAP_MS = 10000;++const tempDirs = [];+test.after(() => {+ for (const dir of tempDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+});+function makeTempDir(prefix) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ tempDirs.push(dir);+ return dir;+}++// Where each run's record of the order of its writes goes (helpers/write-order-preload.js): one file a run.+let orderDir = null;+let orderRuns = 0;+const orderFile = () => path.join(orderDir || (orderDir = makeTempDir('pcf-write-order-')), `${orderRuns += 1}.json`);++// Runs `node <args>` and reads what it printed, and the order of its writes (`order`). `queued`: stdout and stderr are descriptors 3 and 4 (the+// preload), held back until the process has ended or has written and then stopped; `own`: the process's own stdout and stderr, read as they come.+// `input` is written to stdin (a hook's payload).+function runScript(args, { mode = 'queued', preloads = [], env = {}, cwd, input } = {}) {+ return new Promise((resolve, reject) => {+ const queued = mode === 'queued';+ const record = orderFile();+ const child = spawn(process.execPath, [...(queued ? ['--require', QUEUED] : []), ...preloads.flatMap((p) => ['--require', p]), '--require', ORDER, ...args], {+ cwd: cwd || makeTempDir('pcf-printers-cwd-'),+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT: '1', ...env, WRITE_ORDER_FILE: record },+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe', ...(queued ? ['pipe', 'pipe'] : [])],+ });+ if (input !== undefined) child.stdin.end(input);+ const readers = queued ? [child.stdio[3], child.stdio[4]] : [child.stdout, child.stderr];+ const read = [[], []];+ const own = [];+ readers.forEach((reader, i) => reader.on('data', (chunk) => read[i].push(chunk)));+ if (queued) for (const reader of [child.stdout, child.stderr]) reader.on('data', (chunk) => own.push(chunk));+ let held = queued;+ let timer = null;+ const release = () => {+ if (!held) return;+ held = false;+ clearInterval(timer);+ for (const reader of readers) reader.resume();+ };+ if (held) {+ for (const reader of readers) reader.pause();+ const started = Date.now();+ let seen = -1;+ let quietSince = started;+ timer = setInterval(() => {+ const taken = readers.reduce((sum, reader) => sum + reader.readableLength, 0);+ if (taken !== seen) {+ seen = taken;+ quietSince = Date.now();+ }+ if ((taken > 0 && Date.now() - quietSince >= QUIET_MS) || Date.now() - started >= CAP_MS) release();+ }, 25);+ }+ child.on('exit', release);+ child.on('error', reject);+ child.on('close', (status, signal) => resolve({+ status,+ signal,+ stdout: Buffer.concat(read[0]).toString('utf8'),+ stderr: Buffer.concat(read[1]).toString('utf8'),+ own: Buffer.concat(own).toString('utf8'),+ order: fs.existsSync(record) ? JSON.parse(fs.readFileSync(record, 'utf8')).events : null,+ }));+ });+}++async function eachAtOnce(items, task, width = 6) {+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(width, items.length) }, async () => {+ while (next < items.length) await task(items[next++]);+ }));+}++function assertSameText(actual, expected, what) {+ assert.equal(typeof actual, 'string', `${what}: nothing was read`);+ if (actual === expected) return;+ const ending = (text) => JSON.stringify(text.slice(-60));+ assert.fail(`${what}: ${actual.length} characters arrived of the ${expected.length} expected; it ends with ${ending(actual)} where the text ends with ${ending(expected)}`);+}++// Each stream the process wrote to was made blocking before its first write — the order the fix is, read from the process itself.+function assertBlockingFirst(ran, what) {+ assert.ok(Array.isArray(ran.order), `${what}: the process left no record of its writes`);+ for (const name of ['stdout', 'stderr']) {+ const firstWrite = ran.order.indexOf(`write ${name}`);+ if (firstWrite === -1) continue;+ const blocking = ran.order.indexOf(`blocking ${name}`);+ assert.ok(blocking !== -1 && blocking < firstWrite, `${what}: ${name} is made blocking before it is written to — ${blocking === -1 ? 'it never was' : 'only after'} (${ran.order.slice(0, 8).join(', ')})`);+ }+}++function assertPrinted(ran, expected, what) {+ assert.equal(ran.status, expected.status, `${what}: the exit status (${ran.own || ''}${ran.status === 0 ? '' : ran.stderr.slice(0, 300)})`);+ assertSameText(ran.stdout, expected.stdout, `${what}: stdout`);+ assertSameText(ran.stderr, expected.stderr, `${what}: stderr`);+ assertBlockingFirst(ran, what);+}++async function assertWholeBothWays(args, { preloads, env, cwd, input, status, stream, text }, what) {+ const [queued, own] = await Promise.all(MODES.map((mode) => runScript(args, { mode, preloads, env, cwd, input })));+ for (const [ran, mode] of [[queued, 'queued'], [own, 'own']]) {+ assert.equal(ran.status, status, `${what}, ${mode}: the exit status (${ran.own}${ran.stderr.slice(0, 300)})`);+ assertBlockingFirst(ran, `${what}, ${mode}`);+ assert.ok(ran[stream].includes(text), `${what}, ${mode}: the whole text is on ${stream} — ${ran[stream].length} characters arrived, and they do not hold the ${text.length}-character text that ends it`);+ assert.ok(ran[stream].endsWith('\n'), `${what}, ${mode}: ${stream} ends with its line break`);+ }+ assertSameText(queued.stdout, own.stdout, `${what}: stdout, queued and own`);+ assertSameText(queued.stderr, own.stderr, `${what}: stderr, queued and own`);+ return { queued, own };+}++// ── check-auth.js ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++const CHECK_AUTH = path.join(SCRIPTS, 'check-auth.js');+const usageBlocker = (flagError) => ({ ok: false, blocker: 'usage', message: `${flagError}. Usage: node check-auth.js --env <url> [--require-pac]`, warnings: [], azUser: null, pacUser: null, envUrl: null, identitiesMatch: false, whoAmI: null });++test('check-auth.js prints a usage blocker that quotes a message of a megabyte whole, and still exits 0 — through both kinds of stream; a mistyped flag exactly as before', async () => {+ const expected = { status: 0, stdout: `${JSON.stringify(usageBlocker(hugeFailureText('flag', BIG)))}\n`, stderr: '' };+ for (const mode of MODES) {+ assertPrinted(await runScript([CHECK_AUTH, '--env', ENV_URL], { mode, preloads: [HUGE], env: { HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: String(BIG) } }), expected, `a megabyte, ${mode}`);+ }+ const argv = ['--env', ENV_URL, '--requir-pac'];+ const small = { status: 0, stdout: `${JSON.stringify(usageBlocker(validateFlags(argv, { known: ['env', 'require-pac'], needValue: ['env'] })))}\n`, stderr: '' };+ for (const mode of MODES) assertPrinted(await runScript([CHECK_AUTH, ...argv], { mode }), small, `--requir-pac, ${mode}`);+});++test('check-auth.js prints a refused WhoAmI whose diagnostic is a megabyte long whole, and still exits 0; a short diagnostic exactly as before', async () => {+ for (const size of [BIG, 12]) {+ const text = hugeFailureText('whoami', size);+ const { queued } = await assertWholeBothWays([CHECK_AUTH, '--env', ENV_URL], { preloads: [FAKE_AUTH], env: { FAKE_WHOAMI_DIAGNOSTIC_SIZE: String(size) }, status: 0, stream: 'stdout', text }, `${size} characters`);+ const result = JSON.parse(queued.stdout);+ assert.equal(result.blocker, 'whoami_error');+ assert.equal(result.whoAmI.message, text, 'the service\'s whole diagnostic, as the result has always carried it');+ assert.equal(queued.stderr, '');+ }+});++// ── Every script's own usage error ────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// Each prints `${USAGE}\n${message}\n` (its usageError), or `✗ ${message}\n${USAGE}\n` (lint-pcf.js, write-pcf-plan.js), or `${message}\n${USAGE}\n`+// (telemetry-config.js) — and exits 1.+const USAGE_SCRIPTS = ['lint-pcf.js', 'pcf-build.js', 'pcf-ci-build.js', 'pcf-doctor.js', 'pcf-gates.js', 'pcf-inventory.js', 'pcf-push.js', 'pcf-scaffold.js',+ 'pcf-upgrade.js', 'telemetry-config.js', 'verify-pcf.js', 'write-pcf-plan.js'];++test('every pcf script prints a usage error that quotes a message of a megabyte whole on stderr, with exit 1 — through both kinds of stream', async () => {+ const text = hugeFailureText('flag', BIG);+ await eachAtOnce(USAGE_SCRIPTS, (script) => assertWholeBothWays([path.join(SCRIPTS, script)], {+ preloads: [HUGE], env: { HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: String(BIG) }, status: 1, stream: 'stderr', text: `${text}\n`,+ }, script).then(({ queued }) => assert.equal(queued.stdout, '', `${script}: nothing on stdout`)));+});++test('every pcf script\'s usage error is what it always was: the message and the usage text on stderr, with exit 1', async () => {+ const text = hugeFailureText('flag', 10);+ await eachAtOnce(USAGE_SCRIPTS, async (script) => {+ const ran = await runScript([path.join(SCRIPTS, script)], { preloads: [HUGE], env: { HUGE_FAILURE: 'flag', HUGE_FAILURE_SIZE: '10' } });+ assert.equal(ran.status, 1, `${script}: ${ran.own}${ran.stderr}`);+ assert.equal(ran.stdout, '', `${script}: nothing on stdout`);+ assert.ok(ran.stderr.includes(`${text}\n`) && /usage/i.test(ran.stderr) && ran.stderr.endsWith('\n'), `${script}: ${JSON.stringify(ran.stderr.slice(0, 300))}`);+ assertBlockingFirst(ran, script);+ });+});++// ── The write-safety hook ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++test('validate-write-safety.js flags a write outside the project whose path is a megabyte long with its whole message, exit 1; a short path as before', async () => {+ for (const size of [BIG, 10]) {+ const dir = makeTempDir('pcf-write-safety-whole-');+ fs.writeFileSync(path.join(dir, 'pcf-plan.md'), '# plan\n');+ const target = path.join(path.parse(dir).root, `outside-${'p'.repeat(size)}.tsx`);+ const input = JSON.stringify({ tool_name: 'Write', tool_input: { file_path: target, content: '' }, cwd: dir });+ const { queued } = await assertWholeBothWays([path.join(HOOKS, 'validate-write-safety.js')], { input, cwd: dir, status: 1, stream: 'stderr', text: `targeted "${target}", which is outside your project folder` }, `${size} characters`);+ assert.match(queued.stderr, /^\[pcf\] Heads up: a pcf Write targeted "/);+ assert.match(queued.stderr, /Silence with PCF_SKIP_WRITE_GUARD=1 or PCF_DISABLE_HOOKS=1\.\n$/);+ }+});diff --git a/plugins/pcf/scripts/tests/pcf-push-token.test.js b/plugins/pcf/scripts/tests/pcf-push-token.test.jsnew file mode 100644index 000000000..5c346ff8b--- /dev/null+++ b/plugins/pcf/scripts/tests/pcf-push-token.test.js@@ -0,0 +1,132 @@+'use strict';+// pcf-push.js writes a receipt, `pcf-receipt.json`, after a push — and what it says about the registration is the service's own words: when the read that confirms the push is refused, the reason is the refusal's text, which a+// service may fill with the access token it was sent (whole, or by a part, folded onto several lines the way a gateway wraps a long header, or spelled with a JSON escape). The token is kept out of everything the process+// writes by lib/output-redaction.js: the two streams (once a token is known) and every file a script writes with a service's words in it. The receipt is such a file, and this holds it — in a REAL process, with the real SDK bundle+// and the production client — together with the list of every other write of file content in this plugin and why none of them can carry a token.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const { TOKEN, SECRETS, leaksIn } = require('./helpers/push-token.js');++const SCRIPTS = path.resolve(__dirname, '..');+const CHILD = path.join(__dirname, 'helpers', 'push-token-child.js');+const MARK = '<token>';++function filesUnder(root, out = new Map()) {+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {+ const full = path.join(root, entry.name);+ if (entry.isDirectory()) filesUnder(full, out);+ else out.set(path.relative(root, full).split(path.sep).join('/'), fs.readFileSync(full, 'utf8'));+ }+ return out;+}++// The push, in a real process, against a service that refuses the confirming read with a diagnostic that says the token as `how` spells it. Returns what reached stdout and stderr, how the process ended, and every file it+// left in the project folder and the SDK's workspace.+function pushWith(how) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pcf-push-token-'));+ try {+ const project = path.join(dir, 'project');+ const run = spawnSync(process.execPath, [CHILD, project, how], {+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT: '1', POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' },+ encoding: 'utf8',+ timeout: 120000,+ });+ return { status: run.status, stdout: run.stdout, stderr: run.stderr, files: filesUnder(project) };+ } finally {+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ }+}++for (const [how, name] of [['folded', 'folded onto several lines'], ['escaped-fold', 'folded with a JSON-escaped line break'], ['plain', 'plainly']]) {+ test(`a push whose confirming read is refused with a diagnostic that repeats the access token ${name} writes a receipt, and a result, without it`, () => {+ const ran = pushWith(how);+ assert.equal(ran.status, 1, `the push is not confirmed, so the script ends with 1: ${ran.stderr.slice(0, 500)}`);+ assert.ok(ran.files.has('pcf-receipt.json'), 'the receipt is written');+ assert.deepEqual(leaksIn(ran.stdout), [], 'stdout holds the token');+ assert.deepEqual(leaksIn(ran.stderr), [], 'stderr holds the token');+ for (const [name, text] of ran.files) assert.deepEqual(leaksIn(text), [], `${name} holds the token, or a part of it, in some spelling`);+ const receipt = JSON.parse(ran.files.get('pcf-receipt.json'));+ // The plugin's own scrubber (`scrubSecrets`) reads a token that is whole and shaped like a JWT, and the guard on what the process writes reads the rest: the token folded, or spelled with an escape.+ assert.match(receipt.registered.reason, /^HTTP 403 from \S+: Header check failed for value (?:<token>|<redacted-jwt>)$/, 'what the service said is still there, with the token taken out');+ assert.equal(receipt.control, 'new_Contoso.Controls.StarRating', 'the rest of the receipt is what it was');+ assert.equal(receipt.version, '1.2.3');+ assert.equal(receipt.registered.ok, false);+ const result = JSON.parse(ran.stdout);+ assert.equal(result.registered.reason, receipt.registered.reason, 'the receipt says what the result says');+ });+}++test('a refusal that does not repeat the token is written to the receipt as the service said it', () => {+ const ran = pushWith('none');+ assert.equal(ran.status, 1);+ const receipt = JSON.parse(ran.files.get('pcf-receipt.json'));+ assert.match(receipt.registered.reason, /^HTTP 403 from \S+: Header check failed for value nothing secret here$/);+ assert.deepEqual(leaksIn(ran.stdout), []);+});++test('the receipt is the one file this plugin writes that carries a service\'s words, and it is written through the guard — every other write of file content is listed, with the reason it cannot carry a token', () => {+ const files = (dir, out = []) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) { if (!['tests', 'vendor', 'node_modules'].includes(entry.name)) files(full, out); } else if (/\.js$/.test(entry.name)) out.push(full);+ }+ return out;+ };+ // A call that writes or copies a file's content.+ const WRITES = /\.(?:writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|writeSync|copyFileSync|copyFile|cpSync)\s*\(/;+ const withoutComments = (text) => text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');+ const found = files(SCRIPTS).filter((file) => WRITES.test(withoutComments(fs.readFileSync(file, 'utf8')))).map((file) => path.relative(SCRIPTS, file).split(path.sep).join('/')).sort();+ const OTHER = {+ 'lib/pcf-scaffold.js': 'writes the files of a new project from templates and the answers a person gave; it calls no service',+ 'lib/pcf-upgrade.js': 'rewrites a project\'s own files (package.json, the manifest, the pcfproj) with versions it computed; it calls no service',+ 'pcf-ci-build.js': 'builds a bundle and sets the version in the project\'s own manifest and solution files; it calls no service',+ 'write-pcf-plan.js': 'writes the plan the agent gave; it calls no service',+ 'lib/telemetry/lib/emit-dispatcher.js': 'telemetry events, in a hook process that obtains no token, limited to the approved fields',+ 'lib/telemetry/lib/local-log.js': 'the local mirror of those events',+ 'lib/telemetry/lib/user-config.js': 'the telemetry choice a person made',+ 'lib/telemetry/region/region-cache.js': 'a cached region name',+ };+ assert.deepEqual(found, ['pcf-push.js', ...Object.keys(OTHER)].sort(), 'a writer was added or removed: say which kind it is');+ // The receipt is cleaned by the one function that cleans what a process writes.+ const push = withoutComments(fs.readFileSync(path.join(SCRIPTS, 'pcf-push.js'), 'utf8'));+ assert.match(push, /redactOutput\(/, 'pcf-push.js cleans the text of its receipt');+ assert.match(push, /require\('\.\/lib\/output-redaction\.js'\)/);+ // The others run in processes that obtain no token: none of them calls anything that does.+ const OBTAINS = /\b(?:getAuthToken|getAuthTokenAsync|getPowerAppsToken|dataverseRequest|preflightAuth|createMakerSdk|createAzHttpClient|makePcfSdk|noteToken)\b/;+ for (const label of Object.keys(OTHER)) assert.doesNotMatch(withoutComments(fs.readFileSync(path.join(SCRIPTS, label), 'utf8')), OBTAINS, `${label} obtains no token`);+});++test('the SDK\'s workspace the push makes is guarded like the receipt — what the SDK writes into it holds no token — and the reads of this plugin write nothing into it but the manifest', async () => {+ const { makePcfSdk, findCustomControl, listCustomControls } = require('../lib/pcf-dataverse.js');+ const { noteToken } = require('../lib/output-redaction.js');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pcf-workspace-token-'));+ try {+ noteToken(TOKEN);+ // Answers that SUCCEED and repeat the token in every place a read can put it.+ const answer = (body) => ({ status: 200, headers: {}, body });+ const http = {+ get: async (url) => {+ const text = String(url);+ if (/EntityDefinitions\(LogicalName='customcontrol'\)/i.test(text)) return answer({ EntitySetName: 'customcontrols', LogicalName: 'customcontrol', note: TOKEN });+ if (/\/customcontrols\?/i.test(text)) return answer({ value: [{ customcontrolid: '11111111-1111-1111-1111-111111111111', name: `Contoso ${TOKEN}`, version: '1.0.0', componentstate: 0, ismanaged: false }] });+ return answer({ note: TOKEN });+ },+ post: async () => answer({}), patch: async () => answer({}), put: async () => answer({}), delete: async () => answer({}),+ };+ // The manifest the SDK writes names the instance it works on: here an address that holds the token, which is the one place a text the process knows can reach the workspace of a read.+ const workspace = path.join(dir, 'workspace');+ const sdk = await makePcfSdk(`https://contoso.crm.dynamics.com/${TOKEN}`, workspace, http);+ assert.equal((await findCustomControl(sdk, 'new_Contoso.Controls.StarRating')).name, `Contoso ${TOKEN}`, 'the data a read returns is the caller\'s, as it came');+ assert.equal((await listCustomControls(sdk)).length, 1);+ const written = filesUnder(workspace);+ assert.deepEqual([...written.keys()], ['manifest.json'], 'a read writes nothing into the workspace but the manifest');+ for (const [name, text] of written) assert.deepEqual(leaksIn(text), [], `${name} holds the token`);+ assert.equal(JSON.parse(written.get('manifest.json')).instanceUrl, `https://contoso.crm.dynamics.com/${MARK}`, 'the marker stands where the token was');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ }+});diff --git a/plugins/pcf/scripts/tests/pcf-result-whole-before-exit.test.js b/plugins/pcf/scripts/tests/pcf-result-whole-before-exit.test.jsnew file mode 100644index 000000000..205b69608--- /dev/null+++ b/plugins/pcf/scripts/tests/pcf-result-whole-before-exit.test.js@@ -0,0 +1,262 @@+'use strict';+// pcf's result printers end the process right after their writes — `emitResult` (lib/dataverse-auth.js), and the printers of pcf-inventory.js, verify-pcf.js and lint-pcf.js — and an agent reads the result through a+// pipe. Node writes to a pipe asynchronously on Linux and macOS, and `process.exit` does not wait for what is still queued (https://nodejs.org/api/process.html#a-note-on-process-io), so a large result reached its reader+// cut short there; Windows makes a pipe on stdout and stderr synchronous, so nothing shows it there. Each printer now makes its writes blocking first (makeWritesBlocking, lib/output-redaction.js).+//+// The tests check it on every platform. THE ORDER: each real process records when it makes stdout or stderr blocking and when it writes to them+// (helpers/write-order-preload.js), and each stream it wrote to must have been made blocking before its first write — which does not depend on the+// platform, the runtime or how fast the reader reads, so it fails on every run for a printer without the call. THE TEXT: the same processes, whose+// stdout and stderr are the kind of stream Linux and macOS give a pipe (helpers/queued-stdio-preload.js: sockets over descriptors 3 and 4, which Node+// leaves asynchronous on Windows too), print a result of megabytes — and the same over the process's own stdout and stderr; how much of it a printer+// without the call loses depends on the runtime and on how fast this process reads, so this half shows what a reader gets, not the fix. In this+// process, stand-ins for stdout and stderr that take what a pipe takes at once and queue the rest show that emitResult has every text taken whole when+// it calls `process.exit`, and never returns — as deterministic as the order. A small result is pinned to the bytes and the exit status it always had.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const { rows, longText, controls } = require('./helpers/big-results.js');++const SCRIPTS = path.join(__dirname, '..');+const QUEUED = path.join(__dirname, 'helpers', 'queued-stdio-preload.js');+const ORDER = path.join(__dirname, 'helpers', 'write-order-preload.js');+const FAKE_ORG = path.join(__dirname, 'helpers', 'fake-big-org-preload.js');+const BUILDERS = path.join(__dirname, 'helpers', 'big-results.js');+const AUTH = path.join(SCRIPTS, 'lib', 'dataverse-auth.js');+const BIG = 30000;+const SMALL = 2;+// `queued`: the kind of pipe Linux and macOS give a script, on every platform. `own`: the process's own stdout and stderr (queued pipes on Linux and macOS, synchronous ones on Windows).+const MODES = ['queued', 'own'];++const tempDirs = [];+test.after(() => {+ for (const dir of tempDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+});+function makeTempDir(prefix) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ tempDirs.push(dir);+ return dir;+}++// Where each run's record of the order of its writes goes (helpers/write-order-preload.js): one file a run.+let orderDir = null;+let orderRuns = 0;+const orderFile = () => path.join(orderDir || (orderDir = makeTempDir('pcf-write-order-')), `${orderRuns += 1}.json`);++function run(args, mode, env = {}) {+ const queued = mode === 'queued';+ const record = orderFile();+ const result = spawnSync(process.execPath, [...(queued ? ['--require', QUEUED] : []), '--require', ORDER, ...args], {+ cwd: makeTempDir('pcf-whole-before-exit-'),+ stdio: ['ignore', 'pipe', 'pipe', ...(queued ? ['pipe', 'pipe'] : [])],+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT: '1', ...env, WRITE_ORDER_FILE: record },+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ timeout: 120000,+ });+ assert.equal(result.error, undefined, `the process could not be run: ${result.error}`);+ const order = fs.existsSync(record) ? JSON.parse(fs.readFileSync(record, 'utf8')).events : null;+ if (!queued) return { status: result.status, stdout: result.stdout, stderr: result.stderr, order };+ // With the preload everything the script prints goes to descriptors 3 and 4; what reached 1 and 2 is Node's own (a failure to start), shown if the test fails.+ return { status: result.status, stdout: result.output[3], stderr: result.output[4], own: `${result.stdout}${result.stderr}`, order };+}++// Each stream the process wrote to was made blocking before its first write — the order the fix is, read from the process itself.+function assertBlockingFirst(ran, what) {+ assert.ok(Array.isArray(ran.order), `${what}: the process left no record of its writes`);+ for (const name of ['stdout', 'stderr']) {+ const firstWrite = ran.order.indexOf(`write ${name}`);+ if (firstWrite === -1) continue;+ const blocking = ran.order.indexOf(`blocking ${name}`);+ assert.ok(blocking !== -1 && blocking < firstWrite, `${what}: ${name} is made blocking before it is written to — ${blocking === -1 ? 'it never was' : 'only after'} (${ran.order.slice(0, 8).join(', ')})`);+ }+}++// Compares a long text by its length and its two ends first, so that a text cut short fails with a message a person can read.+function assertSameText(actual, expected, what) {+ assert.equal(typeof actual, 'string', `${what}: nothing was read`);+ if (actual === expected) return;+ const ending = (text) => JSON.stringify(text.slice(-60));+ assert.fail(`${what}: ${actual.length} characters arrived of the ${expected.length} written; it ends with ${ending(actual)} where the text ends with ${ending(expected)}`);+}++function assertPrinted(ran, expected, what) {+ assert.equal(ran.status, expected.status, `${what}: the exit status (${ran.own || ''})`);+ assertBlockingFirst(ran, what);+ assertSameText(ran.stdout, expected.stdout, `${what}: stdout`);+ assertSameText(ran.stderr, expected.stderr, `${what}: stderr`);+}++// ── emitResult ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// Each branch of pcf's emitResult: the call, and the bytes and status it always printed (an Error is also a `{ ok:false, error }` line on stdout — pcf's own contract).+const EMITS = {+ ok: { call: (n) => `emitResult(true, rows(${n}))`, expected: (n) => ({ status: 0, stdout: `${JSON.stringify(rows(n))}\n`, stderr: '' }) },+ error: { call: (n) => `emitResult(false, new Error(longText(${n})))`, expected: (n) => ({ status: 1, stdout: `${JSON.stringify({ ok: false, error: longText(n) })}\n`, stderr: `${longText(n)}\n` }) },+ 'structured-error': {+ call: (n) => `emitResult(false, { ok: false, error: longText(${n}), rows: rows(${n}) })`,+ expected: (n) => ({ status: 1, stdout: `${JSON.stringify({ ok: false, error: longText(n), rows: rows(n) })}\n`, stderr: `${longText(n)}\n` }),+ },+ 'structured-errors': {+ call: (n) => `emitResult(false, { ok: false, errors: rows(${n}) })`,+ expected: (n) => ({ status: 1, stdout: `${JSON.stringify({ ok: false, errors: rows(n) })}\n`, stderr: `Operation completed with ${n} error(s); see stdout JSON\n` }),+ },+ 'structured-unexplained': {+ call: (n) => `emitResult(false, { ok: false, rows: rows(${n}) })`,+ expected: (n) => ({ status: 1, stdout: `${JSON.stringify({ ok: false, rows: rows(n) })}\n`, stderr: 'Operation failed with an unstructured error; see stdout JSON\n' }),+ },+ text: { call: (n) => `emitResult(false, longText(${n}))`, expected: (n) => ({ status: 1, stdout: '', stderr: `${longText(n)}\n` }) },+};++const runEmit = (branch, n, mode) => run(['-e', `const { emitResult } = require(${JSON.stringify(AUTH)}); const { rows, longText } = require(${JSON.stringify(BUILDERS)}); ${EMITS[branch].call(n)};`], mode);++for (const branch of Object.keys(EMITS)) {+ test(`pcf emitResult (${branch}) writes a result of megabytes whole before the process ends — through a pipe that queues what it cannot take at once, and through the process's own stdout and stderr`, () => {+ for (const mode of MODES) assertPrinted(runEmit(branch, BIG, mode), EMITS[branch].expected(BIG), `${branch}, ${mode}`);+ });+}++test('pcf emitResult prints a small result exactly as it always did, with the same exit status, in every branch and through both kinds of stream', () => {+ for (const branch of Object.keys(EMITS)) {+ for (const mode of MODES) assertPrinted(runEmit(branch, SMALL, mode), EMITS[branch].expected(SMALL), `${branch}, ${mode}`);+ }+});++// A stand-in for a pipe whose reader is reading but has not caught up: a write puts at most `capacity` characters in the pipe at once and queues the rest for a later turn of the event loop — unless the handle was made+// blocking, when the write returns with all of it taken. A write made while something is queued waits behind it, as a real stream's does.+function queuingPipe(capacity = 64 * 1024) {+ const pipe = { written: '', taken: '', queued: '', blocking: false };+ pipe.stream = {+ _handle: { setBlocking(flag) { pipe.blocking = flag === true; return 0; } },+ write(chunk) {+ const text = String(chunk);+ pipe.written += text;+ if (pipe.queued) {+ pipe.queued += text;+ } else {+ const now = pipe.blocking ? text : text.slice(0, capacity);+ pipe.taken += now;+ pipe.queued = text.slice(now.length);+ if (pipe.queued) setImmediate(() => { pipe.taken += pipe.queued; pipe.queued = ''; });+ }+ return !pipe.queued;+ },+ };+ return pipe;+}++// Runs `fn` with the stand-ins as this process's stdout and stderr and a `process.exit` that records what the reader had been given when it was called, then throws — nothing runs after the real one either.+function endedWith(fn) {+ const out = queuingPipe();+ const err = queuingPipe();+ const saved = { stdout: Object.getOwnPropertyDescriptor(process, 'stdout'), stderr: Object.getOwnPropertyDescriptor(process, 'stderr'), exit: process.exit };+ const END = new Error('process.exit');+ const ended = { code: undefined, returned: false, takenAtExit: undefined };+ Object.defineProperty(process, 'stdout', { configurable: true, enumerable: true, get: () => out.stream });+ Object.defineProperty(process, 'stderr', { configurable: true, enumerable: true, get: () => err.stream });+ process.exit = (code) => {+ ended.code = code;+ ended.takenAtExit = { stdout: out.taken, stderr: err.taken };+ throw END;+ };+ try {+ fn();+ ended.returned = true;+ } catch (error) {+ if (error !== END) throw error;+ } finally {+ Object.defineProperty(process, 'stdout', saved.stdout);+ Object.defineProperty(process, 'stderr', saved.stderr);+ process.exit = saved.exit;+ }+ return { ...ended, written: { stdout: out.written, stderr: err.written } };+}++test('pcf emitResult has every text it wrote taken whole by the pipe when it calls process.exit — a pipe that takes 64 KiB at once and queues the rest — and never returns to its caller', () => {+ const { emitResult } = require('../lib/dataverse-auth.js');+ const calls = {+ ok: () => emitResult(true, rows(BIG)),+ error: () => emitResult(false, new Error(longText(BIG))),+ 'structured-error': () => emitResult(false, { ok: false, error: longText(BIG), rows: rows(BIG) }),+ text: () => emitResult(false, longText(BIG)),+ };+ for (const [name, call] of Object.entries(calls)) {+ const ended = endedWith(call);+ assert.equal(ended.returned, false, `${name}: emitResult never returns — the exit follows its writes at once`);+ assert.equal(ended.code, name === 'ok' ? 0 : 1, `${name}: the exit status`);+ assert.ok(ended.written.stdout.length + ended.written.stderr.length > 2 * 1024 * 1024, `${name}: a text of megabytes was written`);+ for (const stream of ['stdout', 'stderr']) {+ assert.equal(ended.takenAtExit[stream].length, ended.written[stream].length, `${name}: the pipe had taken all of ${stream} when process.exit was called`);+ }+ }+});++// ── The scripts with printers of their own ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++const ENV_URL = 'https://contoso.crm.dynamics.com';+const inventoryRow = ({ name, version, isManaged, componentState }) => ({ name, version, isManaged, componentState });++test('pcf-inventory.js prints a listing of megabytes whole before it exits, and a failure that long whole on both streams — through both kinds of stream; a small listing exactly as before', () => {+ for (const mode of MODES) {+ for (const n of [BIG, SMALL]) {+ const what = `${n} controls, ${mode}`;+ const workspace = path.join(makeTempDir('pcf-inventory-workspace-'), 'ws');+ const args = ['--require', FAKE_ORG, path.join(SCRIPTS, 'pcf-inventory.js'), '--env', ENV_URL, '--include-managed', '--workspace', workspace];+ assertPrinted(run(args, mode, { FAKE_BIG_ORG_CONTROLS: String(n) }), { status: 0, stdout: `${JSON.stringify({ ok: true, controls: controls(n).map(inventoryRow) })}\n`, stderr: '' }, what);+ assertPrinted(run(args, mode, { FAKE_BIG_ORG_FAILURE: String(n) }), {+ status: 1,+ stdout: `${JSON.stringify({ ok: false, controls: [], error: longText(n) })}\n`,+ stderr: `${longText(n)}\n`,+ }, `${what}, failed`);+ }+ }+});++test('verify-pcf.js prints a failure of megabytes whole on both streams before it exits — through both kinds of stream; a small one exactly as before', () => {+ for (const mode of MODES) {+ for (const n of [BIG, SMALL]) {+ const workspace = path.join(makeTempDir('pcf-verify-workspace-'), 'ws');+ const args = ['--require', FAKE_ORG, path.join(SCRIPTS, 'verify-pcf.js'), '--env', ENV_URL, '--control', 'new_Contoso.Controls.StarRating',+ '--table', 'account', '--form', 'Information', '--column', 'name', '--workspace', workspace];+ assertPrinted(run(args, mode, { FAKE_BIG_ORG_FAILURE: String(n) }), {+ status: 1,+ stdout: `${JSON.stringify({ ok: false, error: longText(n), control: { registered: { ok: false, version: null, expected: null, componentState: null } }, bindings: [], runtime: 'not-checked' })}\n`,+ stderr: `${longText(n)}\n`,+ }, `${n} lines, ${mode}`);+ }+ }+});++test('lint-pcf.js prints findings of megabytes whole before it exits — through both kinds of stream — and a manifest with no finding as before', () => {+ const dir = makeTempDir('pcf-lint-whole-');+ const manifest = (version) => `<?xml version="1.0"?><manifest><control namespace="Contoso.Controls" constructor="Big" version="${version}" display-name-key="Big" description-key="Big"><resources><code path="index.ts" /></resources></control></manifest>`;+ // A version of three megabytes: the finding that names it is a text that long.+ const version = '9'.repeat(3 * 1024 * 1024);+ const big = path.join(dir, 'big', 'ControlManifest.Input.xml');+ const clean = path.join(dir, 'clean', 'ControlManifest.Input.xml');+ fs.mkdirSync(path.dirname(big));+ fs.mkdirSync(path.dirname(clean));+ fs.writeFileSync(big, manifest(version));+ fs.writeFileSync(clean, manifest('1.0.0'));+ const printed = {};+ for (const mode of MODES) {+ const ran = run([path.join(SCRIPTS, 'lint-pcf.js'), '--manifest', big], mode);+ assert.equal(ran.status, 1, `${mode}: findings exit 1 (${ran.own || ''})`);+ assertBlockingFirst(ran, `${mode}: the findings`);+ assert.ok(ran.stdout.endsWith('}\n') && ran.stdout.indexOf('\n') === ran.stdout.length - 1, `${mode}: one JSON line, ended by a line break — ${ran.stdout.length} characters arrived`);+ const result = JSON.parse(ran.stdout);+ assert.equal(result.ok, false);+ const finding = result.results[0].errors.find((item) => item.code === 'PCF_VERSION_FORMAT');+ assert.ok(finding && finding.message.includes(`'${version}'`), `${mode}: the finding names the whole version`);+ assert.equal(ran.stderr, 'PCF manifest lint failed; see stdout JSON\n', `${mode}: the note on stderr`);+ printed[mode] = ran.stdout;+ const fine = run([path.join(SCRIPTS, 'lint-pcf.js'), '--manifest', clean], mode);+ assert.equal(fine.status, 0, `${mode}: a manifest with no error exits 0 (${fine.stderr})`);+ assertBlockingFirst(fine, `${mode}: no finding`);+ assert.deepEqual(JSON.parse(fine.stdout), { ok: true, results: [{ manifest: clean, errors: [], warnings: JSON.parse(fine.stdout).results[0].warnings }] }, `${mode}: the same shape`);+ assert.equal(fine.stderr, '', `${mode}: nothing on stderr`);+ }+ assert.equal(printed.queued, printed.own, 'the same text through both kinds of stream');+});diff --git a/plugins/pcf/scripts/vendor/PROVENANCE.json b/plugins/pcf/scripts/vendor/PROVENANCE.jsonindex 707ba670b..8f172d545 100644--- a/plugins/pcf/scripts/vendor/PROVENANCE.json+++ b/plugins/pcf/scripts/vendor/PROVENANCE.json@@ -1,13 +1,13 @@{- "commit": "ccf2c1a11a829fe261199936493aa12f3e2bd0ed",+ "commit": "d603c7996f7918da669b3ef16c6fa63f5b9fb7a0","dirtySdkPackage": 0,- "libBuiltAt": "2026-10-19T15:37:01.994Z",- "newestSrcAt": "2026-10-18T02:54:15.290Z",+ "libBuiltAt": "2026-10-20T01:32:45.044Z",+ "newestSrcAt": "2026-10-20T01:31:52.361Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v20.20.2",- "builtAt": "2026-10-19T15:38:54.180Z",- "bundleSha256": "b8497fbc98f732df23b83d4002818612a9f41c1b94bff7bbeefc5cc60e910f36",- "bundleBytes": 1057824+ "builtAt": "2026-10-20T01:34:40.388Z",+ "bundleSha256": "16246ee08fe653de994989f08fbf4a8e243f4d3cbe961a7c89c40be37bef1a88",+ "bundleBytes": 1020302}diff --git a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjsindex f359733cc..c8ac6679b 100644--- a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs@@ -25,33 +25,33 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-var eq=Object.create;var qc=Object.defineProperty;var tq=Object.getOwnPropertyDescriptor;var rq=Object.getOwnPropertyNames;var nq=Object.getPrototypeOf,iq=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},nn=(e,t)=>{for(var r in t)qc(e,r,{get:t[r],enumerable:!0})},Bc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rq(t))!iq.call(e,i)&&i!==r&&qc(e,i,{get:()=>t[i],enumerable:!(n=tq(t,i))||n.enumerable});return e},so=(e,t,r)=>(Bc(e,t,"default"),r&&Bc(r,t,"default")),Ce=(e,t,r)=>(r=e!=null?eq(nq(e)):{},Bc(t||!e||!e.__esModule?qc(r,"default",{value:e,enumerable:!0}):r,e)),zr=e=>Bc(qc({},"__esModule",{value:!0}),e);var lo=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var qw;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(qw||(T.OwnershipTypes=qw={}));var Vw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Vw||(T.PrincipalType=Vw={}));var Gw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Gw||(T.ActivityTypeMask=Gw={}));var Ww;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Ww||(T.TableTypes=Ww={}));var zw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(zw||(T.TableTypeCode=zw={}));var jw;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(jw||(T.FormType=jw={}));var Hw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Hw||(T.FormPresentation=Hw={}));var Kw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(Kw||(T.ActivationState=Kw={}));var Jw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(Jw||(T.AttributeType=Jw={}));var Yw;(function(e){e[e.Public=0]="Public",e[e.AdvancedFind=1]="AdvancedFind",e[e.Associated=2]="Associated",e[e.QuickFind=4]="QuickFind",e[e.Lookup=64]="Lookup"})(Yw||(T.ViewType=Yw={}));var Qw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(Qw||(T.ChartsType=Qw={}));var Xw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(Xw||(T.ChartType=Xw={}));var Zw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(Zw||(T.ComponentState=Zw={}));var eC;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(eC||(T.PluginIsolationMode=eC={}));var tC;(function(e){e[e.BasicAuth=0]="BasicAuth"})(tC||(T.AuthType=tC={}));var rC;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(rC||(T.PluginSourceType=rC={}));var nC;(function(e){e.Boolean="Boolean",e.Customer="Customer",e.Date="Date",e.DateTime="DateTime",e.DateTimeNoTimeZone="DateTimeNoTimeZone",e.Decimal="Decimal",e.Double="Double",e.Integer="Integer",e.Lookup="Lookup",e.Memo="Memo",e.Money="Money",e.Owner="Owner",e.PartyList="PartyList",e.Picklist="Picklist",e.State="State",e.Status="Status",e.String="String",e.Uniqueidentifier="Uniqueidentifier",e.CalendarRules="CalendarRules",e.Virtual="Virtual",e.BigInt="BigInt",e.ManagedProperty="ManagedProperty",e.EntityName="EntityName"})(nC||(T.AttributeTypeCode=nC={}));var iC;(function(e){e.DateTimeType="DateTimeType",e.ImageType="ImageType",e.IntegerType="IntegerType",e.FileType="FileType",e.BooleanType="BooleanType",e.CustomerType="CustomerType",e.MemoType="MemoType",e.MultiSelectPicklistType="MultiSelectPicklistType",e.MoneyType="MoneyType",e.DecimalType="DecimalType",e.DoubleType="DoubleType",e.LookupType="LookupType",e.BigIntType="BigIntType",e.UniqueidentifierType="UniqueidentifierType",e.StringType="StringType",e.OwnerType="OwnerType",e.PicklistType="PicklistType",e.StateType="StateType",e.StatusType="StatusType",e.EntityNameType="EntityNameType"})(iC||(T.AttributeTypeName=iC={}));var oC;(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(oC||(T.AttributeFormatCode=oC={}));var aC;(function(e){e.Text="Text",e.TextArea="TextArea",e.Email="Email",e.Url="Url",e.Phone="Phone",e.Json="Json",e.RichText="RichText",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(aC||(T.AttributeFormatName=aC={}));var sC;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(sC||(T.AttributeTypeCodeNum=sC={}));var lC;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(lC||(T.OptionSetType=lC={}));var uC;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(uC||(T.StateCode=uC={}));var cC;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(cC||(T.StatusCode=cC={}));var dC;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(dC||(T.StateCodeEnabledDisabled=dC={}));var fC;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(fC||(T.StatusCodeEnabledDisabled=fC={}));var pC;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(pC||(T.WorkflowTypeCode=pC={}));var mC;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(mC||(T.WorkflowScope=mC={}));var hC;(function(e){e[e.Workflow=0]="Workflow",e[e.Dialog=1]="Dialog",e[e.BusinessRule=2]="BusinessRule",e[e.Action=3]="Action",e[e.BusinessProcessFlow=4]="BusinessProcessFlow",e[e.Flow=5]="Flow",e[e.UIFlow=6]="UIFlow"})(hC||(T.WorkflowCategory=hC={}));var gC;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(gC||(T.BusinessProcessType=gC={}));var yC;(function(e){e[e.CanvasApp=0]="CanvasApp",e[e.ComponentLibrary=1]="ComponentLibrary",e[e.CustomCanvasPage=2]="CustomCanvasPage",e[e.UnifiedApp=3]="UnifiedApp",e[e.CodeApp=4]="CodeApp",e[e.MobileApp=5]="MobileApp"})(yC||(T.AppSubType=yC={}));var bC;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(bC||(T.RelationshipType=bC={}));var vC;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(vC||(T.RelationshipTypeExt=vC={}));var wC;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(wC||(T.CascadeType=wC={}));var CC;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(CC||(T.RelationshipSecurityTypes=CC={}));var EC;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(EC||(T.ViewStatusCode=EC={}));var AC;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(AC||(T.ViewStateCode=AC={}));var SC;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(SC||(T.EntityKeyIndexStatus=SC={}));var NC;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.Tour=10061]="Tour"})(NC||(T.SolutionComponentTypeCode=NC={}));var _C;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(_C||(T.RootComponentBehavior=_C={}));var Vc;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(Vc||(T.SolutionComponentTypeCodeExt=Vc={}));var Gc;(function(e){e[e.Entity=9801]="Entity",e[e.Attribute=9802]="Attribute",e[e.OptionSet=9804]="OptionSet",e[e.EntityRelationship=9805]="EntityRelationship",e[e.EntityKey=9812]="EntityKey",e[e.Role=1036]="Role",e[e.DisplayString=4102]="DisplayString",e[e.SavedQuery=1039]="SavedQuery",e[e.Workflow=4703]="Workflow",e[e.Report=9100]="Report",e[e.Template=2010]="Template",e[e.ContractTemplate=2011]="ContractTemplate",e[e.KbArticleTemplate=1016]="KbArticleTemplate",e[e.MailMergeTemplate=9106]="MailMergeTemplate",e[e.SavedQueryVisualization=1111]="SavedQueryVisualization",e[e.SystemForm=1030]="SystemForm",e[e.WebResource=9333]="WebResource",e[e.SiteMap=4709]="SiteMap",e[e.ConnectionRole=3231]="ConnectionRole",e[e.HierarchyRule=8840]="HierarchyRule",e[e.CustomControl=9753]="CustomControl",e[e.FieldSecurityProfile=1200]="FieldSecurityProfile",e[e.AppModule=9006]="AppModule",e[e.PluginAssembly=4605]="PluginAssembly",e[e.SdkMessageProcessingStep=4608]="SdkMessageProcessingStep",e[e.ServiceEndpoint=4618]="ServiceEndpoint",e[e.RoutingRule=8181]="RoutingRule",e[e.SLA=9750]="SLA",e[e.ConvertRule=9300]="ConvertRule",e[e.MobileOfflineProfile=9866]="MobileOfflineProfile",e[e.EntityDataSource=85]="EntityDataSource",e[e.SdkMessage=4606]="SdkMessage",e[e.RibbonCustomization=1120]="RibbonCustomization",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.MaskingRule=373]="MaskingRule",e[e.AttributeMaskingRule=374]="AttributeMaskingRule",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Plan=10283]="Plan",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.TeamTemplate=511]="TeamTemplate",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=1030]="Dashboard",e[e.InteractionCentricDashboard=1032]="InteractionCentricDashboard",e[e.PowerBIDashboard=1034]="PowerBIDashboard",e[e.Dialog=1030]="Dialog",e[e.WebResourceImage=9333]="WebResourceImage",e[e.WebResourceSilverlight=9333]="WebResourceSilverlight",e[e.WebResourceCode=9333]="WebResourceCode",e[e.WebResourceData=9333]="WebResourceData",e[e.BusinessRule=4703]="BusinessRule",e[e.ActionDefinition=4703]="ActionDefinition",e[e.ActionTemplate=4703]="ActionTemplate",e[e.DialogDefinition=4703]="DialogDefinition",e[e.DialogTemplate=4703]="DialogTemplate",e[e.WorkflowDefinition=4703]="WorkflowDefinition",e[e.WorkflowTemplate=4703]="WorkflowTemplate",e[e.ProcessFlow=4703]="ProcessFlow",e[e.Flow=4703]="Flow",e[e.UIFlow=4703]="UIFlow",e[e.ProcessNoFlow=4703]="ProcessNoFlow",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=4703]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.AllDashboards=1030]="AllDashboards",e[e.FormsOnly=1030]="FormsOnly",e[e.ComponentLibrary=300]="ComponentLibrary",e[e.CanvasAppsOnly=300]="CanvasAppsOnly",e[e.CustomCanvasPage=300]="CustomCanvasPage",e[e.CodeApp=300]="CodeApp",e[e.MobileApp=300]="MobileApp",e[e.Chatbot=10030]="Chatbot",e[e.Card=10276]="Card"})(Gc||(T.EntityTypeCode=Gc={}));var TC;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(TC||(T.SolutionComponentVirtualAttributeSubtype=TC={}));function oq(e){let t=Vc[e];return Gc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=oq;function aq(e){let t=Gc[e];return Vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=aq;var DC;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(DC||(T.ImeMode=DC={}));var IC;(function(e){e[e.Simple=0]="Simple",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup",e[e.Formula=3]="Formula",e[e.Prompt=4]="Prompt"})(IC||(T.SourceType=IC={}));var OC;(function(e){e.Email="Email",e.Phone="Phone",e.PhoneticGuide="PhoneticGuide",e.Text="Text",e.TextArea="TextArea",e.TickerSymbol="TickerSymbol",e.Url="Url",e.VersionNumber="VersionNumber"})(OC||(T.StringFormatName=OC={}));var PC;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(PC||(T.PrecisionSource=PC={}));var RC;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(RC||(T.DateTimeBehavior=RC={}));var LC;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(LC||(T.DateTimeFormat=LC={}));var kC;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(kC||(T.IntegerFormat=kC={}));var $C;(function(e){e[e.HTML=1]="HTML",e[e.CSS=2]="CSS",e[e.JScript=3]="JScript",e[e.XML=4]="XML",e[e.PNG=5]="PNG",e[e.JPG=6]="JPG",e[e.GIF=7]="GIF",e[e.Silverlight=8]="Silverlight",e[e.XSL=9]="XSL",e[e.ICO=10]="ICO",e[e.SVG=11]="SVG",e[e.RESX=12]="RESX"})($C||(T.WebResourceTypeCode=$C={}));var xC;(function(e){e[e.Initial=5]="Initial",e[e.PreValidation=10]="PreValidation",e[e.InternalPreOperationBeforeExternal=15]="InternalPreOperationBeforeExternal",e[e.PreOperation=20]="PreOperation",e[e.InternalPreOperationAfterExternal=25]="InternalPreOperationAfterExternal",e[e.MainOperation=30]="MainOperation",e[e.InternalPostOperationBeforeExternal=35]="InternalPostOperationBeforeExternal",e[e.PostOperation=40]="PostOperation",e[e.InternalPostOperationAfterExternal=45]="InternalPostOperationAfterExternal",e[e.PostOperationDeprecated=50]="PostOperationDeprecated",e[e.FinalPostOperation=55]="FinalPostOperation"})(xC||(T.SdkMessageProcessingStage=xC={}));var FC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(FC||(T.SupportedDeployment=FC={}));var MC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(MC||(T.SdkMessageProcessingMode=MC={}));var UC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(UC||(T.ReportTypeCode=UC={}));var BC;(function(e){e[e.Business=1]="Business",e[e.Family=2]="Family",e[e.Social=3]="Social",e[e.Sales=4]="Sales",e[e.Other=5]="Other",e[e.Stakeholder=1e3]="Stakeholder",e[e.SalesTeam=1001]="SalesTeam",e[e.Service=1002]="Service"})(BC||(T.ConnectionRoleCategory=BC={}));var qC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(qC||(T.ServiceNamespaceFormat=qC={}));var VC;(function(e){e[e.OneWay=1]="OneWay",e[e.Queue=2]="Queue",e[e.Rest=3]="Rest",e[e.TwoWay=4]="TwoWay",e[e.Topic=5]="Topic",e[e.PersistentQueue=6]="PersistentQueue",e[e.EventHub=7]="EventHub",e[e.WebHook=8]="WebHook"})(VC||(T.ServiceEndpointContract=VC={}));var GC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(GC||(T.ServiceEndpointConnectionMode=GC={}));var WC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(WC||(T.DeleteDependencyErrorCode=WC={}));var zC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(zC||(T.DefaultRoleTemplates=zC={}));var jC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(jC||(T.RoleInheritance=jC={}));var HC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(HC||(T.ConnectorTypeEnum=HC={}));var KC;(function(e){e[e.String=1e8]="String",e[e.Number=100000001]="Number",e[e.Boolean=100000002]="Boolean",e[e.JSON=100000003]="JSON",e[e.ConnectionReference=100000004]="ConnectionReference",e[e.Secret=100000005]="Secret"})(KC||(T.EnvironmentVariableDefinitionTypeEnum=KC={}));var JC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(JC||(T.TeamTypeEnum=JC={}));var YC;(function(e){e.Bots="bots"})(YC||(T.KnownCustomSolutionComponentEntitySetName=YC={}));var QC;(function(e){e[e.MainApplicationView=0]="MainApplicationView",e[e.AdvancedSearch=1]="AdvancedSearch",e[e.SubGrid=2]="SubGrid",e[e.QuickFindSearch=4]="QuickFindSearch",e[e.Reporting=8]="Reporting",e[e.OfflineFilters=16]="OfflineFilters",e[e.MASearch=32]="MASearch",e[e.LookupView=64]="LookupView",e[e.SMAppointmentBookView=128]="SMAppointmentBookView",e[e.OutlookFilters=256]="OutlookFilters",e[e.AddressBookFilters=512]="AddressBookFilters",e[e.SavedQueryTypeOther=2048]="SavedQueryTypeOther",e[e.InteractiveWorkflowView=4096]="InteractiveWorkflowView",e[e.OfflineTemplate=8192]="OfflineTemplate",e[e.OutlookTemplate=131072]="OutlookTemplate",e[e.CustomDefinedView=16384]="CustomDefinedView"})(QC||(T.QueryType=QC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readPcfRegistrationProgress=X.withPcfRegistrationProgress=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var _t=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=_t;var XC=Symbol.for("cds-maker-sdk.partialWriteTokens");function sq(e,t){return typeof e=="object"&&e!==null&&(e[XC]=t),e}X.withPartialTokens=sq;function lq(e){return Wc(e,XC)}X.readPartialTokens=lq;function Wc(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var ZC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function uq(e,t){return typeof e=="object"&&e!==null&&(e[ZC]=t),e}X.withPartialEnrichment=uq;function cq(e){return Wc(e,ZC)}X.readPartialEnrichment=cq;var qm=Symbol.for("cds-maker-sdk.cleanupWarnings");function dq(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[qm];r[qm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=dq;function fq(e){let t=Wc(e,qm);return t?[...t]:void 0}X.readCleanupWarnings=fq;var eE=Symbol.for("cds-maker-sdk.pcfRegistrationProgress");function tE(e){return{...e,written:[...e.written],unconfirmed:[...e.unconfirmed],published:[...e.published],publishedUnknown:[...e.publishedUnknown],temporaries:[...e.temporaries]}}function pq(e,t){return typeof e=="object"&&e!==null&&(e[eE]=tE(t)),e}X.withPcfRegistrationProgress=pq;function mq(e){let t=Wc(e,eE);return t?tE(t):void 0}X.readPcfRegistrationProgress=mq;var Vm=class extends _t{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=Vm;var Gm=class extends _t{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=Gm;var Wm=class extends _t{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:+var AU=Object.create;var bc=Object.defineProperty;var SU=Object.getOwnPropertyDescriptor;var NU=Object.getOwnPropertyNames;var _U=Object.getPrototypeOf,TU=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Hr=(e,t)=>{for(var r in t)bc(e,r,{get:t[r],enumerable:!0})},yc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of NU(t))!TU.call(e,i)&&i!==r&&bc(e,i,{get:()=>t[i],enumerable:!(n=SU(t,i))||n.enumerable});return e},Ji=(e,t,r)=>(yc(e,t,"default"),r&&yc(r,t,"default")),Ee=(e,t,r)=>(r=e!=null?AU(_U(e)):{},yc(t||!e||!e.__esModule?bc(r,"default",{value:e,enumerable:!0}):r,e)),Fr=e=>yc(bc({},"__esModule",{value:!0}),e);var Yi=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 Yv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(Yv||(T.OwnershipTypes=Yv={}));var Qv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Qv||(T.PrincipalType=Qv={}));var Xv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Xv||(T.ActivityTypeMask=Xv={}));var Zv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Zv||(T.TableTypes=Zv={}));var ew;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(ew||(T.TableTypeCode=ew={}));var tw;(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"})(tw||(T.FormType=tw={}));var rw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(rw||(T.FormPresentation=rw={}));var nw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(nw||(T.ActivationState=nw={}));var iw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(iw||(T.AttributeType=iw={}));var ow;(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"})(ow||(T.ViewType=ow={}));var aw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(aw||(T.ChartsType=aw={}));var sw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(sw||(T.ChartType=sw={}));var lw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(lw||(T.ComponentState=lw={}));var uw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(uw||(T.PluginIsolationMode=uw={}));var cw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(cw||(T.AuthType=cw={}));var dw;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(dw||(T.PluginSourceType=dw={}));var fw;(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"})(fw||(T.AttributeTypeCode=fw={}));var pw;(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"})(pw||(T.AttributeTypeName=pw={}));var mw;(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"})(mw||(T.AttributeFormatCode=mw={}));var hw;(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"})(hw||(T.AttributeFormatName=hw={}));var gw;(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"})(gw||(T.AttributeTypeCodeNum=gw={}));var yw;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(yw||(T.OptionSetType=yw={}));var bw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(bw||(T.StateCode=bw={}));var vw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(vw||(T.StatusCode=vw={}));var ww;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(ww||(T.StateCodeEnabledDisabled=ww={}));var Cw;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Cw||(T.StatusCodeEnabledDisabled=Cw={}));var Ew;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Ew||(T.WorkflowTypeCode=Ew={}));var Aw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Aw||(T.WorkflowScope=Aw={}));var Sw;(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"})(Sw||(T.WorkflowCategory=Sw={}));var Nw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Nw||(T.BusinessProcessType=Nw={}));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 Tw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Tw||(T.RelationshipType=Tw={}));var Dw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Dw||(T.RelationshipTypeExt=Dw={}));var Iw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Iw||(T.CascadeType=Iw={}));var Ow;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Ow||(T.RelationshipSecurityTypes=Ow={}));var Pw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Pw||(T.ViewStatusCode=Pw={}));var Rw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Rw||(T.ViewStateCode=Rw={}));var Lw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Lw||(T.EntityKeyIndexStatus=Lw={}));var kw;(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"})(kw||(T.SolutionComponentTypeCode=kw={}));var $w;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})($w||(T.RootComponentBehavior=$w={}));var vc;(function(e){e[e.Entity=1]="Entity",e[e.Attribute=2]="Attribute",e[e.OptionSet=9]="OptionSet",e[e.EntityRelationship=10]="EntityRelationship",e[e.EntityKey=14]="EntityKey",e[e.Role=20]="Role",e[e.DisplayString=22]="DisplayString",e[e.SavedQuery=26]="SavedQuery",e[e.Workflow=29]="Workflow",e[e.Report=31]="Report",e[e.Template=36]="Template",e[e.ContractTemplate=37]="ContractTemplate",e[e.KbArticleTemplate=38]="KbArticleTemplate",e[e.MailMergeTemplate=39]="MailMergeTemplate",e[e.RibbonCustomization=50]="RibbonCustomization",e[e.SavedQueryVisualization=59]="SavedQueryVisualization",e[e.SystemForm=60]="SystemForm",e[e.WebResource=61]="WebResource",e[e.SiteMap=62]="SiteMap",e[e.ConnectionRole=63]="ConnectionRole",e[e.HierarchyRule=65]="HierarchyRule",e[e.CustomControl=66]="CustomControl",e[e.FieldSecurityProfile=70]="FieldSecurityProfile",e[e.AppModule=80]="AppModule",e[e.PluginAssembly=91]="PluginAssembly",e[e.SdkMessageProcessingStep=92]="SdkMessageProcessingStep",e[e.ServiceEndpoint=95]="ServiceEndpoint",e[e.RoutingRule=150]="RoutingRule",e[e.SLA=152]="SLA",e[e.ConvertRule=154]="ConvertRule",e[e.MobileOfflineProfile=161]="MobileOfflineProfile",e[e.EntityDataProvider=181]="EntityDataProvider",e[e.EntityDataSource=183]="EntityDataSource",e[e.SdkMessage=201]="SdkMessage",e[e.CanvasApp=300]="CanvasApp",e[e.Connector=372]="Connector",e[e.EnvironmentVariableDefinition=380]="EnvironmentVariableDefinition",e[e.EnvironmentVariableValue=381]="EnvironmentVariableValue",e[e.AIModel=401]="AIModel",e[e.Dataflow=418]="Dataflow",e[e.DataflowEntities=419]="DataflowEntities",e[e.DualWriteEntityMap=500]="DualWriteEntityMap",e[e.DataIntegrationConnection=501]="DataIntegrationConnection",e[e.ExportToDataLakeConfig=510]="ExportToDataLakeConfig",e[e.DataWorkspace=10282]="DataWorkspace",e[e.Dashboard=100001]="Dashboard",e[e.InteractionCentricDashboard=100002]="InteractionCentricDashboard",e[e.Dialog=100003]="Dialog",e[e.PowerBIDashboard=100004]="PowerBIDashboard",e[e.BusinessRule=100021]="BusinessRule",e[e.ProcessFlow=100024]="ProcessFlow",e[e.Flow=100025]="Flow",e[e.UIFlow=100026]="UIFlow",e[e.ProcessNoFlow=100031]="ProcessNoFlow",e[e.AllDashboards=100032]="AllDashboards",e[e.FormsOnly=100033]="FormsOnly",e[e.ComponentLibrary=100034]="ComponentLibrary",e[e.CanvasAppsOnly=100035]="CanvasAppsOnly",e[e.CustomCanvasPage=100038]="CustomCanvasPage",e[e.CodeApp=100039]="CodeApp",e[e.MobileApp=100046]="MobileApp",e[e.ProcessNoFlowNoUIFlowNoBusinessRule=100036]="ProcessNoFlowNoUIFlowNoBusinessRule",e[e.ActionDefinition=100040]="ActionDefinition",e[e.ActionTemplate=100041]="ActionTemplate",e[e.DialogDefinition=100042]="DialogDefinition",e[e.DialogTemplate=100043]="DialogTemplate",e[e.WorkflowDefinition=100044]="WorkflowDefinition",e[e.WorkflowTemplate=100045]="WorkflowTemplate"})(vc||(T.SolutionComponentTypeCodeExt=vc={}));var wc;(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"})(wc||(T.EntityTypeCode=wc={}));var xw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(xw||(T.SolutionComponentVirtualAttributeSubtype=xw={}));function DU(e){let t=vc[e];return wc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=DU;function IU(e){let t=wc[e];return vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=IU;var Fw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Fw||(T.ImeMode=Fw={}));var Mw;(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"})(Mw||(T.SourceType=Mw={}));var Uw;(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"})(Uw||(T.StringFormatName=Uw={}));var Bw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Bw||(T.PrecisionSource=Bw={}));var qw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(qw||(T.DateTimeBehavior=qw={}));var Vw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Vw||(T.DateTimeFormat=Vw={}));var Gw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Gw||(T.IntegerFormat=Gw={}));var Ww;(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"})(Ww||(T.WebResourceTypeCode=Ww={}));var zw;(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"})(zw||(T.SdkMessageProcessingStage=zw={}));var jw;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(jw||(T.SupportedDeployment=jw={}));var Hw;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Hw||(T.SdkMessageProcessingMode=Hw={}));var Kw;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(Kw||(T.ReportTypeCode=Kw={}));var Jw;(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"})(Jw||(T.ConnectionRoleCategory=Jw={}));var Yw;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Yw||(T.ServiceNamespaceFormat=Yw={}));var Qw;(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"})(Qw||(T.ServiceEndpointContract=Qw={}));var Xw;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(Xw||(T.ServiceEndpointConnectionMode=Xw={}));var Zw;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(Zw||(T.DeleteDependencyErrorCode=Zw={}));var eC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(eC||(T.DefaultRoleTemplates=eC={}));var tC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(tC||(T.RoleInheritance=tC={}));var rC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(rC||(T.ConnectorTypeEnum=rC={}));var nC;(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"})(nC||(T.EnvironmentVariableDefinitionTypeEnum=nC={}));var iC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(iC||(T.TeamTypeEnum=iC={}));var oC;(function(e){e.Bots="bots"})(oC||(T.KnownCustomSolutionComponentEntitySetName=oC={}));var aC;(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"})(aC||(T.QueryType=aC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var wt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=wt;var sC=Symbol.for("cds-maker-sdk.partialWriteTokens");function OU(e,t){return typeof e=="object"&&e!==null&&(e[sC]=t),e}X.withPartialTokens=OU;function PU(e){return wm(e,sC)}X.readPartialTokens=PU;function wm(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 lC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function RU(e,t){return typeof e=="object"&&e!==null&&(e[lC]=t),e}X.withPartialEnrichment=RU;function LU(e){return wm(e,lC)}X.readPartialEnrichment=LU;var im=Symbol.for("cds-maker-sdk.cleanupWarnings");function kU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[im];r[im]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=kU;function $U(e){let t=wm(e,im);return t?[...t]:void 0}X.readCleanupWarnings=$U;var om=class extends wt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=om;var am=class extends wt{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=am;var sm=class extends wt{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=Wm;var zm=class extends _t{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=zm;var jm=class extends _t{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=jm;var Hm=class extends _t{constructor(t,r,n,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${r}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${n??"(none)"}, server=${i??"(none)"}). Overwriting now would discard your edits and replace them with another writer's changes. Push or discard your edits first, or pass { overwrite: true } to deliberately reset the local copy to the server version.`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i}};X.LocalEditsWouldBeLostError=Hm;var Km=class extends _t{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=Km;var Jm=class extends _t{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=Jm;function hq(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=hq;var Ym=class extends _t{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Ym;var Qm=class extends _t{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=Qm;var Xm=class extends _t{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Xm;var Zm=class extends _t{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Zm;var eh=class extends _t{constructor(t,r,n){super("AMBIGUOUS_ARTIFACT",`Found ${n} ${t} rows matching '${r}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=r,this.matchCount=n}};X.AmbiguousArtifactError=eh;var th=class extends _t{constructor(t,r){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${r}'.`),this.target=t,this.root=r}};X.PathTraversalError=th;var rh=class extends _t{constructor(t,r){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${r}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=r}};X.IncompatibleWorkspaceError=rh});var oe=v(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.odataQuery=at.normalizeGuid=at.createSafeXmlElement=at.assertNoControlChars=at.assertODataName=at.assertXmlName=at.xmlText=at.odataPathLiteral=at.odataLiteral=void 0;var zc=Q();function rE(e){return String(e??"").replace(/'/g,"''")}at.odataLiteral=rE;function gq(e){return encodeURIComponent(rE(e))}at.odataPathLiteral=gq;function yq(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}at.xmlText=yq;function nE(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new zc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}at.assertXmlName=nE;function bq(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new zc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}at.assertODataName=bq;function vq(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new zc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}at.assertNoControlChars=vq;function wq(e,t,r){return e.createElement(nE(t,r))}at.createSafeXmlElement=wq;var Cq=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function Eq(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!Cq.test(n))throw new zc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}at.normalizeGuid=Eq;function Aq(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}at.odataQuery=Aq});var fe=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Ka=Q(),Ja=oe();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function Sq(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=Sq;function iE(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=iE;function Nq(e,t,r){if(!iE(e))throw new Ka.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"no concurrency token is held for it"}, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}j.requireEtag=Nq;function oE(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}j.readEtag=oE;async function _q(e,t,r,n){let i=`/${t}(${n})${(0,Ja.odataQuery)([["$select",r]])}`;return oE(ih(await e.get(i),e.apiUrl(i)))}j.readRowEtag=_q;function nh(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ja.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ja.normalizeGuid)(a[1],t)}return null}j.readCreatedId=nh;function Tq(e,t,r){return r?{...e,[t]:(0,Ja.normalizeGuid)(r,t)}:e}j.withClientMintedId=Tq;function Dq(e,t,r){let n=nh(e,t);if(!n)throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=Dq;function Iq(e,t,r,n){let i=nh(e,t);if(i)return i;if(n)return(0,Ja.normalizeGuid)(n,t);throw new Ka.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=Iq;function ih(e,t){if(e.status===412)throw new Ka.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Ka.ConnectionError(t,e.status,$q(e.body),e.body);return e}j.ensureSuccess=ih;function aE(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=aE;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function Oq(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=Oq;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function Pq(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=Pq;var Rq=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function sE(e){return Rq.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=sE;function lE(e){return e.status!==400||e.body===void 0||e.body===null?!1:sE(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=lE;async function oh(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=oh;function Lq(e){return oh(aE,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=Lq;function kq(e){return oh(lE,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=kq;function $q(e){if(typeof e=="string"&&e.length>0)return e;if(e!==null&&typeof e=="object"){let t=e;if(t.error&&typeof t.error.message=="string")return t.error.message;if(typeof t.Message=="string")return t.Message;if(typeof t.message=="string")return t.message}return"request failed"}async function xq(e,t,r,n){let i=(0,Ja.normalizeGuid)(r,"id"),o=`/${t}(${i})`;ih(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=xq;function Fq(e){return e instanceof Ka.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=Fq;function Mq(){return new Date().toISOString()}j.nowIso=Mq});var Tt=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.describeMalformedValue=Ya.collectPages=void 0;var uE=fe(),ah=Q();async function Uq(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,uE.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${sh(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new ah.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${sh(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new ah.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,uE.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}Ya.collectPages=Uq;function sh(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Ya.describeMalformedValue=sh});var lh=v(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.assertWorkflowKind=Ho.WORKFLOW_KIND_MISMATCH_CODE=void 0;var jo=lo(),Bq=Q(),cE=fe(),qq=oe();Ho.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var dE={[jo.WorkflowCategory.Workflow]:"classic workflow",[jo.WorkflowCategory.Dialog]:"dialog",[jo.WorkflowCategory.BusinessRule]:"business rule",[jo.WorkflowCategory.Action]:"custom action",[jo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[jo.WorkflowCategory.Flow]:"cloud flow",[jo.WorkflowCategory.UIFlow]:"desktop flow"};async function Vq(e,t,r){var n,i;let o=`/workflows(${t})${(0,qq.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,cE.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=dE[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new Bq.SdkError(Ho.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${dE[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,cE.readEtag)(a)}Ho.assertWorkflowKind=Vq});var ch=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.deleteWorkflowResending=on.isWorkflowDeleteUnsettled=on.failedAfterResend=on.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var $l=Q(),_i=fe(),pE=oe();on.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var mE=new WeakSet;function uh(e){return typeof e=="object"&&e!==null&&mE.add(e),e}function Gq(e){return typeof e=="object"&&e!==null&&mE.has(e)}on.failedAfterResend=Gq;function Wq(e){return e instanceof $l.SdkError&&e.code===on.WORKFLOW_DELETE_UNSETTLED_CODE}on.isWorkflowDeleteUnsettled=Wq;function zq(e,t){try{(0,_i.ensureSuccess)(e,t)}catch(r){return r}}function jq(e){return(0,_i.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${_i.TRANSACTION_NOT_STARTED_CODE})`}async function fE(e,t){try{return(await e.get(`/workflows(${t})${(0,pE.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function Hq(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,pE.normalizeGuid)(t,"id");if(a&&!r)throw new $l.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,_i.isTransactionNotStarted)(p)||o&&(0,_i.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,_i.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?_i.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof $l.ConnectionError&&p.statusCode===0&&r&&await fE(e,s))return;throw d>1?uh(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=jq(f),h=new $l.SdkError(on.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw uh((0,$l.attachCause)(h,zq(f,u)))}if(!(r&&_i.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await fE(e,s)))try{(0,_i.ensureSuccess)(m,u)}catch(p){throw d>1?uh(p):p}}}on.deleteWorkflowResending=Hq});var dh=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.businessRuleApi=Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Hn.WFOM_API_UNAVAILABLE_CODE=void 0;var jn=lo(),Kq=Tt(),Jq=lh(),Yq=ch(),Kt=fe(),Ti=oe(),Hc=Q();Hn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function hE(e,t,r,n){let i=`/workflows(${Zq})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Kt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Hc.SdkError(Hn.WFOM_API_UNAVAILABLE_CODE,`Business-rule authoring (preview) is not enabled on this environment yet: it does not expose 'Microsoft.Dynamics.CRM.${t}'. The bound members are still rolling out, so re-check once the release flag reaches this environment. Nothing was written. The SDK does NOT fall back to generating workflow XAML: that covered only 4 of the 7 action types and would silently save a rule different from the one you wrote.`)}}async function Qq(e,t){let r=`/workflows(${t})${(0,Ti.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let n=await e.get(r);if(n.status<200||n.status>=300)return null;let i=n.body;return{etag:(0,Kt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function Xq(e,t,r){let n=await Qq(e,t);if(n===null||n.etag===null)throw new Hc.SdkError(Kt.VERSION_CONFLICT_CODE,`Refusing to update business rule '${t}': its current version could not be read, so the write could not be verified as conditional. The supported update api does not enforce If-Match, so proceeding would risk silently overwriting a concurrent edit. Re-fetch the rule and try again.`);if(n.etag!==r)throw new Hc.SdkError(Kt.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${r}, server ${n.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:n.statecode,statuscode:n.statuscode}}var Zq="00000000-0000-0000-0000-000000000000",jc={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},e3="workflowid,name,description,primaryentity,statecode,category,type",t3="category eq 2 and type eq 1";async function gE(e,t,r){var n;if(r==="Draft")return null;let i=(0,Ti.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?jn.StateCode.Activated:jn.StateCode.Draft,statuscode:o?jn.StatusCode.Activated:jn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Kt.ensureSuccess)(await e.patch(s,a,{headers:jc}),e.apiUrl(s));return(n=(0,Kt.readEtag)(l))!==null&&n!==void 0?n:await xl(e,i)}async function xl(e,t){let r=`/workflows(${t})${(0,Ti.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Kt.readEtag)(n):null}catch{return null}}async function r3(e,t,r){let n=await xl(e,t),i=await r(),o=(0,Kt.readEtag)(i);if(o)return{response:i,etag:o};let a=await xl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Hn.businessRuleApi={async get(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await r3(e,r,async()=>(0,Kt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[t3];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Ti.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Ti.odataQuery)([["$select",e3],["$filter",r.join(" and ")]])}`;return(await(0,Kq.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,Ti.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await hE(e,"CreateProcessWithWfomJson",n,jc),a=(0,Kt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await gE(e,a,n.status)}catch(l){try{await(0,Kt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Kt.readEtag)(o))!==null&&r!==void 0?r:await xl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,Ti.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...jc,"If-Match":(0,Kt.requireEtag)(n,"business rule",s)},c=await Xq(e,s,u["If-Match"]),d=c.statecode===jn.StateCode.Activated;d&&(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Draft,statuscode:jn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await hE(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Kt.ensureSuccess)(await e.patch(l,{statecode:jn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:jn.StatusCode.Activated},{headers:jc}),e.apiUrl(l))}catch(h){throw new Hc.SdkError(Hn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await gE(e,s,a.status);return{id:s,etag:(o=m??(0,Kt.readEtag)(f))!==null&&o!==void 0?o:await xl(e,s)}},async delete(e,t){let r=(0,Ti.normalizeGuid)(t,"id"),n=await(0,Jq.assertWorkflowKind)(e,r,jn.WorkflowCategory.BusinessRule);return(0,Yq.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var jr=v(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.publishBoundEntity=st.boundEntityPublishScope=st.publishGenPageById=st.publishDashboardById=st.publishWebResourceById=st.publishEntity=st.publishAppModule=st.publishAllXml=st.publishXml=void 0;var Kc=fe(),Fl=oe(),yE="/PublishXml";async function Qa(e,t){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(yE,{ParameterXml:t})),e.apiUrl(yE))}st.publishXml=Qa;var bE="/PublishAllXml";async function n3(e){(0,Kc.ensureSuccess)(await(0,Kc.resendDeadlockVictim)(()=>e.post(bE,{})),e.apiUrl(bE))}st.publishAllXml=n3;function i3(e,t){return Qa(e,`<importexportxml><appmodules><appmodule>${(0,Fl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}st.publishAppModule=i3;function vE(e,t){return Qa(e,`<importexportxml><entities><entity>${(0,Fl.xmlText)(t)}</entity></entities></importexportxml>`)}st.publishEntity=vE;function o3(e,t){return Qa(e,`<importexportxml><webresources><webresource>${(0,Fl.xmlText)(t)}</webresource></webresources></importexportxml>`)}st.publishWebResourceById=o3;function a3(e,t){return Qa(e,`<importexportxml><dashboards><dashboard>${(0,Fl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}st.publishDashboardById=a3;function s3(e,t){return Qa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Fl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}st.publishGenPageById=s3;function l3(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}st.boundEntityPublishScope=l3;function u3(e,t){let r=t?.entityLogicalName;return r?vE(e,r):Promise.resolve()}st.publishBoundEntity=u3});var Xa=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.JsonPointer=void 0;var Hr=Q(),Jc=class e{static isReservedToken(t){return e.RESERVED_TOKENS.has(t)}static decodeToken(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}static encodeToken(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}static parse(t){if(t==="")return[];if(t[0]!=="/")throw new Hr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Hr.JsonPointerError(t,`invalid '~' escape in token '${r}' (expected ~0 or ~1)`);return e.decodeToken(r)})}static compile(t){return t.length===0?"":"/"+t.map(r=>e.encodeToken(r)).join("/")}static resolve(t,r){let n=e.parse(r),i=t;for(let o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Hr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Hr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Hr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Hr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Hr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Hr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Hr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Hr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Hr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Hr.JsonPointerError(r,`insert index ${s} is out of range`);a.splice(s,0,n)}static parent(t){let r=e.parse(t);return r.pop(),e.compile(r)}static lastToken(t){let r=e.parse(t);return r.length===0?"":r[r.length-1]}static append(t,r){return`${t}/${e.encodeToken(String(r))}`}static resolveParent(t,r,n){let i=r[r.length-1],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Hr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Yc.JsonPointer=Jc;Jc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var CE=v(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.findElements=void 0;var wE=Xa();function c3(e,t){let r=[];return fh(e,"",t,r),r}Qc.findElements=c3;function fh(e,t,r,n){if(!(e===null||typeof e!="object"))if(r(e,t)&&n.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{fh(i,wE.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))fh(e[i],wE.JsonPointer.append(t,i),r,n)}});var ph=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assertMutationResult=Kn.assertExistsResult=Kn.assertReadResult=Kn.assertStorageContract=void 0;var d3=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],f3=["ensureContainer","exists"];function p3(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of d3)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of f3){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Kn.assertStorageContract=p3;function m3(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Kn.assertReadResult=m3;function h3(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Kn.assertExistsResult=h3;function g3(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Kn.assertMutationResult=g3});var mh=v(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.retryTransientIoAsync=Za.retryTransientIo=void 0;var y3=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),b3=5,EE=10;function v3(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!AE(r,t))throw r;C3(EE*t)}}Za.retryTransientIo=v3;async function w3(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!AE(r,t))throw r;await new Promise(n=>setTimeout(n,EE*t))}}Za.retryTransientIoAsync=w3;function AE(e,t){let r=e.code;return t<b3&&!!r&&y3.has(r)}function C3(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var DE=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.canonicalArtifactId=Kr.WorkspaceManager=Kr.WORKSPACE_SCHEMA_VERSION=Kr.retryTransientIo=void 0;var Jt=ph(),Jn=Q(),E3=mh();Object.defineProperty(Kr,"retryTransientIo",{enumerable:!0,get:function(){return E3.retryTransientIo}});function SE(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Kr.WORKSPACE_SCHEMA_VERSION=1;var uo={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},A3="manifest.json",es=".metadata",hh="entities";function NE(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function gh(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Kr.WORKSPACE_SCHEMA_VERSION)throw new Jn.IncompatibleWorkspaceError(e.schemaVersion,Kr.WORKSPACE_SCHEMA_VERSION)}function _E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var yh=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[uo[t],`${Ml(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[es,uo[t],`${Ml(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[es,hh,`${t.toLowerCase()}.json`]}fsStore(){let t=SE(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=SE(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([uo[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Jn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[A3]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Jn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[es,hh]];for(let i of Object.keys(uo))r.push([uo[i]],[es,uo[i]]);let n=await Promise.allSettled(r.map(i=>NE(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Jt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Jt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!_E(t))throw new Jn.WorkspaceOrgMismatchError("",this.instanceUrl);gh(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Xc(r);if(!n||n!==Xc(this.instanceUrl))throw new Jn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!_E(t.value))throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;gh(r);let n=Object.keys(uo).map(o=>[uo[o]]);n.push([es]);let i=await Promise.allSettled(n.map(o=>NE(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Jt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Jt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=TE(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Ml(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Jt.assertMutationResult)(await this.storage.deleteByPrefix([es,hh]),"deleteByPrefix");return}(0,Jt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Jn.WorkspaceNotInitializedError(this.workspaceLabel);return gh(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Kr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Xc(String(t.instanceUrl))!==Xc(r.instanceUrl))throw new Jn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Ml(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Jt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Jt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Jt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Jt.assertMutationResult)(await this.storage.writeTextAtomic(t,TE(r)),"writeTextAtomic")}};Kr.WorkspaceManager=yh;function TE(e){return`${JSON.stringify(e,null,2)}-`}function Ml(e){let r=/^\{?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}Kr.canonicalArtifactId=Ml});var bh=v(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.deepEqual=ts.deepDiff=void 0;var S3=Xa();function N3(e,t){let r=[];return OE(e,t,"",r,0),r}ts.deepDiff=N3;var Zc=Symbol("missing"),ed=512;function OE(e,t,r,n,i){if(e===t)return;if(i>ed)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${ed}`);let o=td(e),a=td(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=_3(e,t);for(let l of s){let u=IE(e,l),c=IE(t,l),d=S3.JsonPointer.append(r,l);u===Zc?n.push({pointer:d,type:"added",newValue:c}):c===Zc?n.push({pointer:d,type:"removed",oldValue:u}):OE(u,c,d,n,i+1)}return}PE(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function td(e){return e!==null&&typeof e=="object"}function _3(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function IE(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Zc}return t in e?e[t]:Zc}function PE(e,t){return RE(e,t,0)}ts.deepEqual=PE;function RE(e,t,r){if(e===t)return!0;if(r>ed)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${ed}`);if(!td(e)||!td(t)||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(o=>o in t&&RE(e[o],t[o],r+1))}});var kE=v(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.VersionManager=rs.PROJECTION_VERSION=void 0;var LE=bh(),T3=fe();rs.PROJECTION_VERSION=8;var vh=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,LE.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,LE.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,T3.isVersionToken)(i.etag)?!0:i.etag!==n}};rs.VersionManager=vh});var xE=v((wh,$E)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof wh=="object"?$E.exports=t():e.compareVersions=t()})(wh,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var qE=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.EnvironmentFlowHostingType=Je.EnvironmentDisableReasonCode=Je.EnvironmentMigrationConstants=Je.EnvironmentProvisioningStates=Je.EnvironmentLocations=Je.EnvironmentCreationTypeConstants=Je.EnvironmentType=Je.EnvironmentSkuConstants=Je.environmentPermissions=Je.DatabaseType=void 0;var FE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(FE||(Je.DatabaseType=FE={}));Je.environmentPermissions={CreatePowerApp:"CreatePowerApp",ReadEnvironment:"ReadEnvironment",GenerateResourceStorage:"GenerateResourceStorage",CreateGateway:"CreateGateway",CreateFlow:"CreateFlow",CreateCustomApi:"CreateCustomApi",AdminReadEnvironment:"AdminReadEnvironment",UpdateEnvironment:"UpdateEnvironment",DeleteEnvironment:"DeleteEnvironment",ExportEnvironmentPackage:"ExportEnvironmentPackage",SetDLPPolicy:"SetDLPPolicy",ListAnyPowerApp:"ListAnyPowerApp",ListAnyFlow:"ListAnyFlow",DeleteAnyPowerApp:"DeleteAnyPowerApp",DeleteAnyFlow:"DeleteAnyFlow",AddEnvironmentRoleAssignment:"AddEnvironmentRoleAssignment",ReadEnvironmentRoleInformation:"ReadEnvironmentRoleInformation",RemoveEnvironmentRoleAssignment:"RemoveEnvironmentRoleAssignment",ModifyDatabaseRoleAssignments:"ModifyDatabaseRoleAssignments",CreateDatabase:"CreateDatabase",ListDatabaseEntities:"ListDatabaseEntities",CreateDatabaseEntities:"CreateDatabaseEntities",UpdateDatabaseEntities:"UpdateDatabaseEntities",DeleteDatabaseEntities:"DeleteDatabaseEntities"};Je.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var ME;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(ME||(Je.EnvironmentType=ME={}));Je.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Je.EnvironmentLocations={global:"global",unitedStates:"unitedstates",southamerica:"southamerica",europe:"europe",canada:"canada",preview:"unitedstatesfirstrelease",asia:"asia",japan:"japan",australia:"australia",india:"india",unitedkingdom:"unitedkingdom",france:"france",germany:"germany",brazil:"brazil",usgov:"usgov",usgovhigh:"usgovhigh",uae:"unitedarabemirates",switzerland:"switzerland",mooncake:"china",korea:"korea",norway:"norway",southafrica:"southafrica",dod:"usdod",singapore:"singapore",sweden:"sweden",italy:"italy",poland:"poland"};Je.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Je.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var UE;(function(e){e.NotSpecified="NotSpecified",e.NoValidLicense="NoValidLicense",e.SuspendedLicense="SuspendedLicense",e.TrialExpiration="TrialExpiration",e.UserRequested="UserRequested",e.InstanceStateUpdate="InstanceStateUpdated",e.InactivityThreshold="InactivityThreshold",e.OperationsInitiated="OperationsInitiated",e.EnvironmentLifecycleOperation="EnvironmentLifecycleOperation",e.TenantPolicyEvaluation="TenantPolicyEvaluation"})(UE||(Je.EnvironmentDisableReasonCode=UE={}));var BE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(BE||(Je.EnvironmentFlowHostingType=BE={}))});var JE=v(_=>{"use strict";var D3=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var I3=D3(xE()),Oe=qE(),Ul=Eh();function O3(e){let t=Ii(e);return t&&t.version}_.getCrmVersion=O3;function Ii(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=Ii;function Di(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=Di;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Ko(e){return!!Ii(e)&&VE(e)}_.environmentHasCds2Database=Ko;function P3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=P3;function R3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=R3;function L3(e){if(e&&Ko(e)){let t=co(e);(0,Ul.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=L3;function k3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=k3;function $3(e){return e&&Ko(e)?co(e):""}_.getAllThemesUrl=$3;function VE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=VE;function x3(e){if(e&&Ko(e)){let t=co(e);return(0,Ul.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=x3;function F3(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=F3;function co(e){let t=Ii(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=co;function M3(e){let t=Ii(e);return t?t.uniqueName:""}_.getCrmInstanceName=M3;function U3(e){return Ii(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=U3;function B3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=B3;function q3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=q3;function V3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=V3;function Bl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Bl;function G3(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=G3;var W3=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=W3;function z3(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=z3;function j3(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=j3;function H3(e){return e&&e.properties&&Di(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=H3;function K3(e){return!!(e&&e.properties&&e.properties.provisioningState&&KE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=K3;function J3(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=J3;function Y3(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=Y3;function Q3(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Q3;function X3(e){return!!e&&!!e.properties&&!!e.properties.linkedEnvironmentMetadata&&e.properties.linkedEnvironmentMetadata.platformSku==="Lite"&&!!e.properties.states&&!!e.properties.states.management&&e.properties.states.management.id==="Running"&&!!e.properties.ongoingOperation&&!!e.properties.ongoingOperation.type&&e.properties.ongoingOperation.type.id==="Promote"}_.isLiteEnvironmentUpgrading=X3;function Z3(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Z3;function e4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=e4;function t4(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=t4;function r4(e){return e&&e.name||""}_.getEnvironmentName=r4;function n4(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=n4;var GE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function i4(e){return jE(e,GE)}_.doesCds2EnvironmentSupportApiVersion9_1=i4;function o4(e){return Ch(e,GE)}_.doesCds2VersionSupportApiVersion9_1=o4;function WE(e){let t=Ii(e);if(t)return t.securityGroupId}function zE(e){return e&&e.properties&&e.properties.connectedGroups}function a4(e,t){let r=zE(e);return!!r&&!!r.find(n=>n.id===t)||WE(e)===t}_.hasSecurityGroupId=a4;function s4(e){let t=zE(e);return t&&t.length>0&&t[0].id?t[0].id:WE(e)}_.getSecurityOrConnectedGroupId=s4;function jE(e,t){let r=e.version;return r?Ch(r,t):!1}_.isCds2EnvironmentVersionAtLeast=jE;function Ch(e,t){return t?e?(0,I3.default)(e,t)>=0:!1:!0}_.checkVersions=Ch;function l4(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=l4;function u4(e){let t=Ii(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=u4;function HE(e){let t=Ii(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=HE;function c4(e){let t=HE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=c4;function d4(e){let t=co(e);if(t==="")return"";let r=t.split("/");if(r.length!==4)return"";let n=r[2].split(".");return n[0]="globaldisco",r[2]=n.join("."),r.join("/")+"api/discovery/v2.0/Instances"}_.getEnvironmentDiscoveryUrl=d4;var f4=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=f4;var p4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=p4;var m4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=m4;var h4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=h4;var g4=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=g4;var y4=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Di((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=y4;var b4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=b4;function KE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=KE;var v4=e=>{var t;return Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=v4;var w4=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Bl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=w4;var C4=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Bl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=C4;var E4=e=>{var t,r;return!Di((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&Di((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=E4});var Eh=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var YE=JE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Vl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Vl||(Vl={}));function A4(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=A4;function S4(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=S4;function N4(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=N4;function _4(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=_4;function T4(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=T4;function D4(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=D4;function Ah(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function I4(e){return Ah(e,Vl.AllSolutions)}A.getCrmAllSolutionsUrl=I4;function O4(e){return Ah(e,Vl.AllPublishers)}A.getCrmAllPublishersUrl=O4;function P4(e){return Ah(e,Vl.DevResources)}A.getCrmDevResourcesUrl=P4;function R4(e,t=YE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=R4;function L4(e){return`${e}apps`}A.getCrmMyAppsUrl=L4;function k4(e){return QE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=k4;function $4(e){return`${QE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=$4;function QE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function x4(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=x4;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function F4(e,t,r=YE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=F4;function M4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=M4;function U4(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=U4;function B4(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=B4;function q4(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=q4;function V4(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=V4;function G4(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=G4;function W4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=W4;function z4(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=z4;function j4(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=j4;function H4(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=H4;function K4(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=K4;function J4(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=J4;function Y4(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=Y4;function Q4(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=Q4;function X4(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=X4;function Z4(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=Z4;function eV(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=eV;function tV(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=tV;function rV(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=rV;function nV(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=nV;function iV(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=iV;function oV(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=oV;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function aV(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=aV;function sV(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=sV;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function lV(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=lV;function uV(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=uV;function cV(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=cV;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function dV(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns+`)),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=sm;var lm=class extends wt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=lm;var um=class extends wt{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=um;var cm=class extends wt{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=cm;var dm=class extends wt{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=dm;var fm=class extends wt{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=fm;function xU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=xU;var pm=class extends wt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=pm;var mm=class extends wt{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=mm;var hm=class extends wt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=hm;var gm=class extends wt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=gm;var ym=class extends wt{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=ym;var bm=class extends wt{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=bm;var vm=class extends wt{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=vm});var se=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.odataQuery=rt.normalizeGuid=rt.createSafeXmlElement=rt.assertNoControlChars=rt.assertODataName=rt.assertXmlName=rt.xmlText=rt.odataPathLiteral=rt.odataLiteral=void 0;var Cc=Q();function uC(e){return String(e??"").replace(/'/g,"''")}rt.odataLiteral=uC;function FU(e){return encodeURIComponent(uC(e))}rt.odataPathLiteral=FU;function MU(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}rt.xmlText=MU;function cC(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 Cc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}rt.assertXmlName=cC;function UU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Cc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}rt.assertODataName=UU;function BU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Cc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}rt.assertNoControlChars=BU;function qU(e,t,r){return e.createElement(cC(t,r))}rt.createSafeXmlElement=qU;var VU=/^[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 GU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!VU.test(n))throw new Cc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}rt.normalizeGuid=GU;function WU(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}rt.odataQuery=WU});var ye=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Pa=Q(),Ra=se();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function zU(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=zU;function dC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=dC;function jU(e,t,r){if(!dC(e))throw new Pa.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"no concurrency token is held for it"}, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}j.requireEtag=jU;function fC(e){var t;let r=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(r))if(i.toLowerCase()==="etag")return r[i];let n=e.body;return n&&typeof n["@odata.etag"]=="string"?n["@odata.etag"]:null}j.readEtag=fC;async function HU(e,t,r,n){let i=`/${t}(${n})${(0,Ra.odataQuery)([["$select",r]])}`;return fC(Em(await e.get(i),e.apiUrl(i)))}j.readRowEtag=HU;function Cm(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ra.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ra.normalizeGuid)(a[1],t)}return null}j.readCreatedId=Cm;function KU(e,t,r){return r?{...e,[t]:(0,Ra.normalizeGuid)(r,t)}:e}j.withClientMintedId=KU;function JU(e,t,r){let n=Cm(e,t);if(!n)throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=JU;function YU(e,t,r,n){let i=Cm(e,t);if(i)return i;if(n)return(0,Ra.normalizeGuid)(n,t);throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=YU;function Em(e,t){if(e.status===412)throw new Pa.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Pa.ConnectionError(t,e.status,rB(e.body),e.body);return e}j.ensureSuccess=Em;function pC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=pC;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function QU(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=QU;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function XU(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=XU;var ZU=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function mC(e){return ZU.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=mC;function hC(e){return e.status!==400||e.body===void 0||e.body===null?!1:mC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=hC;async function Am(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=Am;function eB(e){return Am(pC,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=eB;function tB(e){return Am(hC,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=tB;function rB(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 nB(e,t,r,n){let i=(0,Ra.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Em(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=nB;function iB(e){return e instanceof Pa.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=iB;function oB(){return new Date().toISOString()}j.nowIso=oB});var Lt=v(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.describeMalformedValue=La.collectPages=void 0;var gC=ye(),Sm=Q();async function aB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,gC.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Nm(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 Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${Nm(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Sm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,gC.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}La.collectPages=aB;function Nm(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}La.describeMalformedValue=Nm});var _m=v(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.assertWorkflowKind=Lo.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Ro=Yi(),sB=Q(),yC=ye(),lB=se();Lo.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var bC={[Ro.WorkflowCategory.Workflow]:"classic workflow",[Ro.WorkflowCategory.Dialog]:"dialog",[Ro.WorkflowCategory.BusinessRule]:"business rule",[Ro.WorkflowCategory.Action]:"custom action",[Ro.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Ro.WorkflowCategory.Flow]:"cloud flow",[Ro.WorkflowCategory.UIFlow]:"desktop flow"};async function uB(e,t,r){var n,i;let o=`/workflows(${t})${(0,lB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,yC.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=bC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new sB.SdkError(Lo.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${bC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,yC.readEtag)(a)}Lo.assertWorkflowKind=uB});var Dm=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.deleteWorkflowResending=Kr.isWorkflowDeleteUnsettled=Kr.failedAfterResend=Kr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var ml=Q(),mi=ye(),wC=se();Kr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var CC=new WeakSet;function Tm(e){return typeof e=="object"&&e!==null&&CC.add(e),e}function cB(e){return typeof e=="object"&&e!==null&&CC.has(e)}Kr.failedAfterResend=cB;function dB(e){return e instanceof ml.SdkError&&e.code===Kr.WORKFLOW_DELETE_UNSETTLED_CODE}Kr.isWorkflowDeleteUnsettled=dB;function fB(e,t){try{(0,mi.ensureSuccess)(e,t)}catch(r){return r}}function pB(e){return(0,mi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${mi.TRANSACTION_NOT_STARTED_CODE})`}async function vC(e,t){try{return(await e.get(`/workflows(${t})${(0,wC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function mB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,wC.normalizeGuid)(t,"id");if(a&&!r)throw new ml.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,mi.isTransactionNotStarted)(p)||o&&(0,mi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,mi.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?mi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof ml.ConnectionError&&p.statusCode===0&&r&&await vC(e,s))return;throw d>1?Tm(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=pB(f),h=new ml.SdkError(Kr.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 Tm((0,ml.attachCause)(h,fB(f,u)))}if(!(r&&mi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await vC(e,s)))try{(0,mi.ensureSuccess)(m,u)}catch(p){throw d>1?Tm(p):p}}}Kr.deleteWorkflowResending=mB});var Im=v(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.businessRuleApi=Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Un.WFOM_API_UNAVAILABLE_CODE=void 0;var Mn=Yi(),hB=Lt(),gB=_m(),yB=Dm(),Vt=ye(),hi=se(),Ac=Q();Un.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function EC(e,t,r,n){let i=`/workflows(${wB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Vt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Ac.SdkError(Un.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 bB(e,t){let r=`/workflows(${t})${(0,hi.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,Vt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function vB(e,t,r){let n=await bB(e,t);if(n===null||n.etag===null)throw new Ac.SdkError(Vt.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 Ac.SdkError(Vt.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 wB="00000000-0000-0000-0000-000000000000",Ec={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},CB="workflowid,name,description,primaryentity,statecode,category,type",EB="category eq 2 and type eq 1";async function AC(e,t,r){var n;if(r==="Draft")return null;let i=(0,hi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Mn.StateCode.Activated:Mn.StateCode.Draft,statuscode:o?Mn.StatusCode.Activated:Mn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Vt.ensureSuccess)(await e.patch(s,a,{headers:Ec}),e.apiUrl(s));return(n=(0,Vt.readEtag)(l))!==null&&n!==void 0?n:await hl(e,i)}async function hl(e,t){let r=`/workflows(${t})${(0,hi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Vt.readEtag)(n):null}catch{return null}}async function AB(e,t,r){let n=await hl(e,t),i=await r(),o=(0,Vt.readEtag)(i);if(o)return{response:i,etag:o};let a=await hl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Un.businessRuleApi={async get(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await AB(e,r,async()=>(0,Vt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[EB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,hi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,hi.odataQuery)([["$select",CB],["$filter",r.join(" and ")]])}`;return(await(0,hB.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,hi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await EC(e,"CreateProcessWithWfomJson",n,Ec),a=(0,Vt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await AC(e,a,n.status)}catch(l){try{await(0,Vt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Vt.readEtag)(o))!==null&&r!==void 0?r:await hl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,hi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ec,"If-Match":(0,Vt.requireEtag)(n,"business rule",s)},c=await vB(e,s,u["If-Match"]),d=c.statecode===Mn.StateCode.Activated;d&&(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Draft,statuscode:Mn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await EC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Mn.StatusCode.Activated},{headers:Ec}),e.apiUrl(l))}catch(h){throw new Ac.SdkError(Un.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 AC(e,s,a.status);return{id:s,etag:(o=m??(0,Vt.readEtag)(f))!==null&&o!==void 0?o:await hl(e,s)}},async delete(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=await(0,gB.assertWorkflowKind)(e,r,Mn.WorkflowCategory.BusinessRule);return(0,yB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Jr=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.publishBoundEntity=Ct.boundEntityPublishScope=Ct.publishGenPageById=Ct.publishDashboardById=Ct.publishWebResourceById=Ct.publishEntity=Ct.publishAppModule=Ct.publishXml=void 0;var SC=ye(),gl=se(),NC="/PublishXml";async function ka(e,t){(0,SC.ensureSuccess)(await(0,SC.resendDeadlockVictim)(()=>e.post(NC,{ParameterXml:t})),e.apiUrl(NC))}Ct.publishXml=ka;function SB(e,t){return ka(e,`<importexportxml><appmodules><appmodule>${(0,gl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ct.publishAppModule=SB;function _C(e,t){return ka(e,`<importexportxml><entities><entity>${(0,gl.xmlText)(t)}</entity></entities></importexportxml>`)}Ct.publishEntity=_C;function NB(e,t){return ka(e,`<importexportxml><webresources><webresource>${(0,gl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ct.publishWebResourceById=NB;function _B(e,t){return ka(e,`<importexportxml><dashboards><dashboard>${(0,gl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ct.publishDashboardById=_B;function TB(e,t){return ka(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,gl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ct.publishGenPageById=TB;function DB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ct.boundEntityPublishScope=DB;function IB(e,t){let r=t?.entityLogicalName;return r?_C(e,r):Promise.resolve()}Ct.publishBoundEntity=IB});var $a=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.JsonPointer=void 0;var Mr=Q(),Sc=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 Mr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Mr.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 Mr.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 Mr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Mr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Mr.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 Mr.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 Mr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Mr.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 Mr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Mr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Mr.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 Mr.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)}};Nc.JsonPointer=Sc;Sc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var DC=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.findElements=void 0;var TC=$a();function OB(e,t){let r=[];return Om(e,"",t,r),r}_c.findElements=OB;function Om(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)=>{Om(i,TC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Om(e[i],TC.JsonPointer.append(t,i),r,n)}});var Pm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.assertMutationResult=Bn.assertExistsResult=Bn.assertReadResult=Bn.assertStorageContract=void 0;var PB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],RB=["ensureContainer","exists"];function LB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of PB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of RB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Bn.assertStorageContract=LB;function kB(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.`)}Bn.assertReadResult=kB;function $B(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.`)}Bn.assertExistsResult=$B;function xB(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.`)}Bn.assertMutationResult=xB});var Rm=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.retryTransientIoAsync=xa.retryTransientIo=void 0;var FB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),MB=5,IC=10;function UB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!OC(r,t))throw r;qB(IC*t)}}xa.retryTransientIo=UB;async function BB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!OC(r,t))throw r;await new Promise(n=>setTimeout(n,IC*t))}}xa.retryTransientIoAsync=BB;function OC(e,t){let r=e.code;return t<MB&&!!r&&FB.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 $C=v(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.canonicalArtifactId=Ur.WorkspaceManager=Ur.WORKSPACE_SCHEMA_VERSION=Ur.retryTransientIo=void 0;var Gt=Pm(),qn=Q(),VB=Rm();Object.defineProperty(Ur,"retryTransientIo",{enumerable:!0,get:function(){return VB.retryTransientIo}});function PC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Ur.WORKSPACE_SCHEMA_VERSION=1;var Qi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},GB="manifest.json",Fa=".metadata",Lm="entities";function RC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function km(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Ur.WORKSPACE_SCHEMA_VERSION)throw new qn.IncompatibleWorkspaceError(e.schemaVersion,Ur.WORKSPACE_SCHEMA_VERSION)}function LC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var $m=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),[Qi[t],`${yl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Fa,Qi[t],`${yl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Fa,Lm,`${t.toLowerCase()}.json`]}fsStore(){let t=PC(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=PC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Qi[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 qn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[GB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new qn.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,Gt.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=[[Fa,Lm]];for(let i of Object.keys(Qi))r.push([Qi[i]],[Fa,Qi[i]]);let n=await Promise.allSettled(r.map(i=>RC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Gt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Gt.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 qn.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 qn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!LC(t))throw new qn.WorkspaceOrgMismatchError("",this.instanceUrl);km(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Tc(r);if(!n||n!==Tc(this.instanceUrl))throw new qn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!LC(t.value))throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;km(r);let n=Object.keys(Qi).map(o=>[Qi[o]]);n.push([Fa]);let i=await Promise.allSettled(n.map(o=>RC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Gt.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,Gt.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=kC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Gt.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,Gt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=yl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Gt.assertMutationResult)(await this.storage.deleteByPrefix([Fa,Lm]),"deleteByPrefix");return}(0,Gt.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 qn.WorkspaceNotInitializedError(this.workspaceLabel);return km(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Ur.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Tc(String(t.instanceUrl))!==Tc(r.instanceUrl))throw new qn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=yl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Gt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Gt.assertMutationResult)(await this.storage.writeTextAtomic(t,kC(r)),"writeTextAtomic")}};Ur.WorkspaceManager=$m;function kC(e){return`${JSON.stringify(e,null,2)}+`}function yl(e){let r=/^\{?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\}?$/.exec(e);return r?r[1].toLowerCase():e.toLowerCase()}Ur.canonicalArtifactId=yl});var xm=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.deepEqual=Ma.deepDiff=void 0;var WB=$a();function zB(e,t){let r=[];return FC(e,t,"",r,0),r}Ma.deepDiff=zB;var Dc=Symbol("missing"),Ic=512;function FC(e,t,r,n,i){if(e===t)return;if(i>Ic)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Ic}`);let o=Oc(e),a=Oc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=jB(e,t);for(let l of s){let u=xC(e,l),c=xC(t,l),d=WB.JsonPointer.append(r,l);u===Dc?n.push({pointer:d,type:"added",newValue:c}):c===Dc?n.push({pointer:d,type:"removed",oldValue:u}):FC(u,c,d,n,i+1)}return}MC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Oc(e){return e!==null&&typeof e=="object"}function jB(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 xC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Dc}return t in e?e[t]:Dc}function MC(e,t){return UC(e,t,0)}Ma.deepEqual=MC;function UC(e,t,r){if(e===t)return!0;if(r>Ic)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Ic}`);if(!Oc(e)||!Oc(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&&UC(e[o],t[o],r+1))}});var qC=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.VersionManager=Ua.PROJECTION_VERSION=void 0;var BC=xm(),HB=ye();Ua.PROJECTION_VERSION=8;var Fm=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,BC.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,BC.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,HB.isVersionToken)(i.etag)?!0:i.etag!==n}};Ua.VersionManager=Fm});var GC=v((Mm,VC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Mm=="object"?VC.exports=t():e.compareVersions=t()})(Mm,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 KC=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.EnvironmentFlowHostingType=Ke.EnvironmentDisableReasonCode=Ke.EnvironmentMigrationConstants=Ke.EnvironmentProvisioningStates=Ke.EnvironmentLocations=Ke.EnvironmentCreationTypeConstants=Ke.EnvironmentType=Ke.EnvironmentSkuConstants=Ke.environmentPermissions=Ke.DatabaseType=void 0;var WC;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(WC||(Ke.DatabaseType=WC={}));Ke.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"};Ke.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var zC;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(zC||(Ke.EnvironmentType=zC={}));Ke.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ke.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"};Ke.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ke.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var jC;(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"})(jC||(Ke.EnvironmentDisableReasonCode=jC={}));var HC;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(HC||(Ke.EnvironmentFlowHostingType=HC={}))});var rE=v(_=>{"use strict";var KB=_&&_.__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 JB=KB(GC()),Oe=KC(),bl=Bm();function YB(e){let t=yi(e);return t&&t.version}_.getCrmVersion=YB;function yi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=yi;function gi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=gi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function ko(e){return!!yi(e)&&JC(e)}_.environmentHasCds2Database=ko;function QB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=QB;function XB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=XB;function ZB(e){if(e&&ko(e)){let t=Xi(e);(0,bl.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=ZB;function eq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=eq;function tq(e){return e&&ko(e)?Xi(e):""}_.getAllThemesUrl=tq;function JC(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=JC;function rq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=rq;function nq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=nq;function Xi(e){let t=yi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Xi;function iq(e){let t=yi(e);return t?t.uniqueName:""}_.getCrmInstanceName=iq;function oq(e){return yi(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=oq;function aq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=aq;function sq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=sq;function lq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=lq;function vl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=vl;function uq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=uq;var cq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=cq;function dq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=dq;function fq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=fq;function pq(e){return e&&e.properties&&gi(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=pq;function mq(e){return!!(e&&e.properties&&e.properties.provisioningState&&tE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=mq;function hq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=hq;function gq(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=gq;function yq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=yq;function bq(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=bq;function vq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=vq;function wq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=wq;function Cq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Cq;function Eq(e){return e&&e.name||""}_.getEnvironmentName=Eq;function Aq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=Aq;var YC="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Sq(e){return ZC(e,YC)}_.doesCds2EnvironmentSupportApiVersion9_1=Sq;function Nq(e){return Um(e,YC)}_.doesCds2VersionSupportApiVersion9_1=Nq;function QC(e){let t=yi(e);if(t)return t.securityGroupId}function XC(e){return e&&e.properties&&e.properties.connectedGroups}function _q(e,t){let r=XC(e);return!!r&&!!r.find(n=>n.id===t)||QC(e)===t}_.hasSecurityGroupId=_q;function Tq(e){let t=XC(e);return t&&t.length>0&&t[0].id?t[0].id:QC(e)}_.getSecurityOrConnectedGroupId=Tq;function ZC(e,t){let r=e.version;return r?Um(r,t):!1}_.isCds2EnvironmentVersionAtLeast=ZC;function Um(e,t){return t?e?(0,JB.default)(e,t)>=0:!1:!0}_.checkVersions=Um;function Dq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Dq;function Iq(e){let t=yi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Iq;function eE(e){let t=yi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=eE;function Oq(e){let t=eE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Oq;function Pq(e){let t=Xi(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=Pq;var Rq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Rq;var Lq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Lq;var kq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=kq;var $q=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=$q;var xq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=xq;var Fq=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return gi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Fq;var Mq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Mq;function tE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=tE;var Uq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Uq;var Bq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Bq;var qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=qq;var Vq=e=>{var t,r;return!gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&gi((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Vq});var Bm=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 nE=rE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Cl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Cl||(Cl={}));function Gq(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=Gq;function Wq(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=Wq;function zq(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=zq;function jq(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=jq;function Hq(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=Hq;function Kq(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=Kq;function qm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function Jq(e){return qm(e,Cl.AllSolutions)}A.getCrmAllSolutionsUrl=Jq;function Yq(e){return qm(e,Cl.AllPublishers)}A.getCrmAllPublishersUrl=Yq;function Qq(e){return qm(e,Cl.DevResources)}A.getCrmDevResourcesUrl=Qq;function Xq(e,t=nE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=Xq;function Zq(e){return`${e}apps`}A.getCrmMyAppsUrl=Zq;function e3(e){return iE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=e3;function t3(e){return`${iE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=t3;function iE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function r3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=r3;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 n3(e,t,r=nE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=n3;function i3(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=i3;function o3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=o3;function a3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=a3;function s3(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=s3;function l3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=l3;function u3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=u3;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.getProcessDesignerUrl=c3;function d3(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=d3;function f3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=f3;function p3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=p3;function m3(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=m3;function h3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=h3;function g3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=g3;function y3(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=y3;function b3(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=b3;function v3(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=v3;function w3(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=w3;function C3(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=C3;function E3(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=E3;function A3(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=A3;function S3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=S3;function N3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=N3;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 _3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=_3;function T3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=T3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function D3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=D3;function I3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=I3;function O3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=O3;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 P3(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=dV;function fV(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=fV;function pV(e){return`/api/data/v9.0/deploymentenvironments+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=P3;function R3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=R3;function L3(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=pV;function mV(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=L3;function k3(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=mV;function hV(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=hV;function gV(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=gV;function yV(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=yV;function bV(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=bV;function vV(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=vV;function wV(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=wV;function CV(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=k3;function $3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=$3;function x3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=x3;function F3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=F3;function M3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=M3;function U3(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=U3;function B3(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=B3;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?$filter=(${t})- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=CV;function EV(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=EV;function AV(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=q3;function V3(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=AV;var SV=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=G3;var W3=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=SV;function NV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=NV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function _V(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=_V;A.OrgSettingOverrideName="organizationsettings";function TV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=TV;A.AppSettingOverrideName="appsettings";function DV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=DV;var ql;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(ql||(A.RetrievePlatform=ql={}));function IV(e,t,r,n=ql.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==ql.All&&o.push(`RetrievePlatformSettings=${n===ql.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=IV;function OV(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=OV;function PV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=PV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function RV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=RV;function XE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=XE;function LV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||XE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=LV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var tA=v(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.DataverseClient=void 0;var kV=Eh(),Jo=Q(),ZE=fe(),$V=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function xV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return $V.has(s)}function FV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function eA(e,t){var r;if(!xV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Sh=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${kV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Jo.SdkError?n:new Jo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=eA(t,r);return(0,ZE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=eA(FV(t),r);return(0,ZE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Jo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Jo.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new Jo.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};rd.DataverseClient=Sh});var iA=v(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.findColumns=cr.findTables=cr.readCheckColumns=cr.readColumnHints=cr.fetchEntityMetadataFromApi=cr.COLUMN_DETAIL_VERSION=void 0;var od=fe(),Ar=oe();function an(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}cr.COLUMN_DETAIL_VERSION=2;function Nh(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Yo(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let r={};for(let n of t)typeof n?.LanguageCode=="number"&&typeof n.Label=="string"&&(r[n.LanguageCode]=n.Label);return Object.keys(r).length?r:void 0}async function nd(e,t){return(await ad(e,t)).rows}async function ad(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Jr(e){return`/EntityDefinitions(LogicalName='${(0,Ar.odataPathLiteral)(e)}')`}async function MV(e,t,r){let n=await nd(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function UV(e){return`${Jr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function BV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:an(a.Label),...Yo(a.Label)?{localizedLabel:Yo(a.Label)}:{}}}))}}function _h(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:an(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function qV(e,t,r){var n;let i=c=>ad(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Nh(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(_h)));let u=await i(`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Nh(d.TrueOption.Label)&&Nh(d.FalseOption.Label),s.set(c.LogicalName,[_h(d.FalseOption),_h(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function VV(e,t,r){let{rows:n,ok:i}=await ad(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,Ar.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function id(e,t){return e<t?-1:e>t?1:0}var rA={OneToMany:0,ManyToOne:1,ManyToMany:2};function GV(e,t){return rA[e.type]-rA[t.type]||id(e.schemaName,t.schemaName)||id(e.relatedEntity,t.relatedEntity)||id(e.relatedAttribute,t.relatedAttribute)}async function WV(e,t){var r,n,i,o;let a=[],s=await nd(e,`${Jr(t)}/OneToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(r=c.ReferencingEntity)!==null&&r!==void 0?r:"",relatedAttribute:(n=c.ReferencingAttribute)!==null&&n!==void 0?n:""});let l=await nd(e,`${Jr(t)}/ManyToOneRelationships${(0,Ar.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await nd(e,`${Jr(t)}/ManyToManyRelationships${(0,Ar.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(GV)}async function zV(e,t){var r,n,i,o,a;let s=`${Jr(t)}`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,od.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,C;return{logicalName:g.LogicalName,displayName:an(g.DisplayName),...Yo(g.DisplayName)?{localizedDisplayName:Yo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(C=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...an(g.Description)?{description:an(g.Description)}:{}}}).sort((g,b)=>id(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=ad(e,UV(t)),[,,m,p,h]=await Promise.all([MV(e,t,d),BV(f,d),qV(e,t,f),VV(e,t,d),WV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:an(u.DisplayName),...Yo(u.DisplayName)?{localizedDisplayName:Yo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...an(u.Description)?{description:an(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:cr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}cr.fetchEntityMetadataFromApi=zV;var nA=40;async function Th(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=nA){let u=a.slice(l,l+nA).map(f=>`LogicalName eq '${(0,Ar.odataLiteral)(f)}'`).join(" or "),c=t+(0,Ar.odataQuery)([["$select",r],["$filter",u]]),d=(0,od.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function jV(e,t,r){return(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Yo(i.DisplayName);return{logicalName:i.LogicalName,displayName:an(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}cr.readColumnHints=jV;async function HV(e,t,r){let i=(await Th(e,`${Jr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:an(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Th(e,`${Jr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}cr.readCheckColumns=HV;async function KV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,od.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],l=(t??"").toLowerCase(),u=s.filter(c=>!r?.customOnly||c.IsCustomEntity).map(c=>{var d,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:an(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}cr.findTables=KV;async function JV(e,t,r,n){var i,o;let a=`${Jr(t)}/Attributes`+(0,Ar.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,od.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:an(d.DisplayName),attributeType:(m=d.AttributeType)!==null&&m!==void 0?m:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}cr.findColumns=JV});var Oh=v(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.renderTypeRegistrations=Sr.buildGenPageLegacyEnums=Sr.renderGenPageAuthoringTypes=Sr.buildGenPageRuntimeTypes=Sr.toDesignerEntity=Sr.TABLE_LOGICAL_NAME=void 0;Sr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function Dh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var YV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function sd(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function sA(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=sd(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function oA(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function lA(e){return!YV.has(e.logicalName)&&(!e.attributeOf||sd(e)==="image")&&e.isValidForRead!==!1}var aA=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function uA(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(oA),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(oA);return[...n,...i]}function Ih(e){var t;let r=[],n=new Set,i=uA(e);for(let o of i){let a=sd(o),s=a==="image";lA(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:sA(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}Sr.toDesignerEntity=Ih;function cA(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Ih(n);return pA(r,t)}Sr.buildGenPageRuntimeTypes=cA;var dA=`export interface TableRegistrations extends BaseTableRegistrations {-`,fA=`export interface EnumRegistrations extends BaseEnumRegistrations {-`;function QV(e,t){return e.length>0?cA(e,t).text:hA(`${dA}}-`,`${fA}}-`,"","")}Sr.renderGenPageAuthoringTypes=QV;function XV(e){let t=new Set;for(let n of e)for(let i of Ih(n).Attributes)aA.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of uA(n)){let o=`${n.logicalName}_${i.logicalName}`,a=sA(i);if(lA(i)||!aA.has(sd(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:mA(o,a,!1,s),model:s})}return r}Sr.buildGenPageLegacyEnums=XV;function pA(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=dA,u=fA,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${Dh(f.Description)}+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=W3;function z3(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=z3;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function j3(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=j3;A.OrgSettingOverrideName="organizationsettings";function H3(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=H3;A.AppSettingOverrideName="appsettings";function K3(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=K3;var wl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(wl||(A.RetrievePlatform=wl={}));function J3(e,t,r,n=wl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==wl.All&&o.push(`RetrievePlatformSettings=${n===wl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=J3;function Y3(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=Y3;function Q3(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=Q3;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function X3(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=X3;function oE({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=oE;function Z3({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||oE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=Z3;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var lE=v(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.DataverseClient=void 0;var eV=Bm(),$o=Q(),aE=ye(),tV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function rV(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 tV.has(s)}function nV(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 sE(e,t){var r;if(!rV(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 Vm=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${eV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof $o.SdkError?n:new $o.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=sE(t,r);return(0,aE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=sE(nV(t),r);return(0,aE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new $o.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new $o.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new $o.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,r,this.withSolution(n)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,r,n){if(!this.httpClient.patchRaw)throw new $o.InvalidArgumentError("The injected HttpClient does not implement patchRaw(), required to upload file content (a Dataverse File column cannot be written through a JSON body)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patchRaw(i,r,this.withSolution(n)))}put(t,r,n){if(!this.httpClient.put)throw new $o.InvalidArgumentError("The injected HttpClient does not implement put(), required for metadata replace operations (e.g. updateColumn)");let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.put(i,r,this.withSolution(n)))}delete(t,r){let n=this.apiUrl(t);return this.send(n,()=>this.httpClient.delete(n,this.withSolution(r)))}};Pc.DataverseClient=Vm});var dE=v(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.findColumns=rr.findTables=rr.readCheckColumns=rr.readColumnHints=rr.fetchEntityMetadataFromApi=rr.COLUMN_DETAIL_VERSION=void 0;var kc=ye(),hr=se();function Yr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}rr.COLUMN_DETAIL_VERSION=2;function Gm(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 xo(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 Rc(e,t){return(await $c(e,t)).rows}async function $c(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 Br(e){return`/EntityDefinitions(LogicalName='${(0,hr.odataPathLiteral)(e)}')`}async function iV(e,t,r){let n=await Rc(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,hr.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 oV(e){return`${Br(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function aV(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:Yr(a.Label),...xo(a.Label)?{localizedLabel:xo(a.Label)}:{}}}))}}function Wm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Yr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function sV(e,t,r){var n;let i=c=>$c(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,hr.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=>Gm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Wm)));let u=await i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Gm(d.TrueOption.Label)&&Gm(d.FalseOption.Label),s.set(c.LogicalName,[Wm(d.FalseOption),Wm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function lV(e,t,r){let{rows:n,ok:i}=await $c(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,hr.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 Lc(e,t){return e<t?-1:e>t?1:0}var uE={OneToMany:0,ManyToOne:1,ManyToMany:2};function uV(e,t){return uE[e.type]-uE[t.type]||Lc(e.schemaName,t.schemaName)||Lc(e.relatedEntity,t.relatedEntity)||Lc(e.relatedAttribute,t.relatedAttribute)}async function cV(e,t){var r,n,i,o;let a=[],s=await Rc(e,`${Br(t)}/OneToManyRelationships${(0,hr.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 Rc(e,`${Br(t)}/ManyToOneRelationships${(0,hr.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 Rc(e,`${Br(t)}/ManyToManyRelationships${(0,hr.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(uV)}async function dV(e,t){var r,n,i,o,a;let s=`${Br(t)}`+(0,hr.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,kc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,E;return{logicalName:g.LogicalName,displayName:Yr(g.DisplayName),...xo(g.DisplayName)?{localizedDisplayName:xo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&E!==void 0?E:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Yr(g.Description)?{description:Yr(g.Description)}:{}}}).sort((g,b)=>Lc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=$c(e,oV(t)),[,,m,p,h]=await Promise.all([iV(e,t,d),aV(f,d),sV(e,t,f),lV(e,t,d),cV(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:Yr(u.DisplayName),...xo(u.DisplayName)?{localizedDisplayName:xo(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,...Yr(u.Description)?{description:Yr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:rr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}rr.fetchEntityMetadataFromApi=dV;var cE=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+=cE){let u=a.slice(l,l+cE).map(f=>`LogicalName eq '${(0,hr.odataLiteral)(f)}'`).join(" or "),c=t+(0,hr.odataQuery)([["$select",r],["$filter",u]]),d=(0,kc.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 fV(e,t,r){return(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=xo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Yr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}rr.readColumnHints=fV;async function pV(e,t,r){let i=(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Yr(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,`${Br(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}rr.readCheckColumns=pV;async function mV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,hr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,kc.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:Yr(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}rr.findTables=mV;async function hV(e,t,r,n){var i,o;let a=`${Br(t)}/Attributes`+(0,hr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,kc.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:Yr(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}rr.findColumns=hV});var Km=v(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.renderTypeRegistrations=gr.buildGenPageLegacyEnums=gr.renderGenPageAuthoringTypes=gr.buildGenPageRuntimeTypes=gr.toDesignerEntity=gr.TABLE_LOGICAL_NAME=void 0;gr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function jm(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var gV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function xc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function mE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=xc(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 fE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function hE(e){return!gV.has(e.logicalName)&&(!e.attributeOf||xc(e)==="image")&&e.isValidForRead!==!1}var pE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function gE(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(fE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(fE);return[...n,...i]}function Hm(e){var t;let r=[],n=new Set,i=gE(e);for(let o of i){let a=xc(o),s=a==="image";hE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:mE(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))}}gr.toDesignerEntity=Hm;function yE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Hm(n);return wE(r,t)}gr.buildGenPageRuntimeTypes=yE;var bE=`export interface TableRegistrations extends BaseTableRegistrations {+`,vE=`export interface EnumRegistrations extends BaseEnumRegistrations {+`;function yV(e,t){return e.length>0?yE(e,t).text:EE(`${bE}}+`,`${vE}}+`,"","")}gr.renderGenPageAuthoringTypes=yV;function bV(e){let t=new Set;for(let n of e)for(let i of Hm(n).Attributes)pE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of gE(n)){let o=`${n.logicalName}_${i.logicalName}`,a=mE(i);if(hE(i)||!pE.has(xc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:CE(o,a,!1,s),model:s})}return r}gr.buildGenPageLegacyEnums=bV;function wE(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=bE,u=vE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${jm(f.Description)}`),c+=`export type ${f.LogicalName} = TableRow<{// Primary Key Columnreadonly ${f.PrimaryIdAttribute}: string,@@ -62,19 +62,19 @@ var eq=Object.create;var qc=Object.defineProperty;var tq=Object.getOwnPropertyDe`;break;case"customer":case"lookup":{let g=(r=m.Targets)!==null&&r!==void 0?r:m.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}p=` // Foreign Key Column${m.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${m.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;p+=`${b},`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${m.LogicalName}`;p+=`: ${g},-`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=mA(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},+`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=CE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.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+=` // ${Dh(m.Description)}+`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${jm(m.Description)}`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+``),c+=` ${p}`)}c+=`}>`}return l+=`}`,u+=`}-`,{text:hA(l,u,c,d),enums:i}}Sr.renderTypeRegistrations=pA;function mA(e,t,r,n){var i;let o=`const enum ${e} {-`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${Dh(a.color)}+`,{text:EE(l,u,c,d),enums:i}}gr.renderTypeRegistrations=wE;function CE(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: ${jm(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 hA(e,t,r,n){return`+`}function EE(e,t,r,n){return`// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------${e}${t}@@ -345,23 +345,23 @@ export interface GeneratedComponentProps {dataApi: UxAgentDataApi;pageInput?: PageInput;}-`}});var bA=v(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});ld.generateGenPageRuntimeTypes=void 0;var yA=Oh(),Qo=Q(),gA=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Xo="generateGenPageRuntimeTypes";async function ZV(e,t,r){let n=eG(t),i=tG(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Qo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Xo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,yA.renderGenPageAuthoringTypes)(o,i)}ld.generateGenPageRuntimeTypes=ZV;function eG(e){if(!Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!yA.TABLE_LOGICAL_NAME.test(r))throw new Qo.InvalidArgumentError(`${Xo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Qo.InvalidArgumentError(`${Xo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function tG(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Qo.InvalidArgumentError(`${Xo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Qo.InvalidArgumentError(`${Xo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!gA.has(r))throw new Qo.InvalidArgumentError(`${Xo}: detail must be one of ${[...gA].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var SA=v(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.getEnvironmentLanguages=Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var rG=Q(),CA=fe();Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var vA="/organizations?$select=languagecode",nG="/RetrieveProvisionedLanguages()",iG="/RetrieveAvailableLanguages()";function EA(e,t){return new rG.SdkError(Zo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function AA(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function wA(e,t,r,n){let i=(0,CA.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(AA))throw EA(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function oG(e){var t;let r=(0,CA.ensureSuccess)(await e.get(vA),e.apiUrl(vA)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!AA(i))throw EA("the organization read","did not answer one row with a language code");let o=await wA(e,nG,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await wA(e,iG,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Zo.getEnvironmentLanguages=oG});var Wl=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.projectConnectorOperationSchema=lt.projectConnectorOperations=lt.validateConnectorSwagger=lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=lt.CONNECTOR_OPERATION_NOT_FOUND_CODE=lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var Gl=Q();lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";lt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var NA=64,_A=128,TA=2e5,DA=4e6,aG=new Set(["get","put","post","delete","patch","head","options"]),sG=new Set(["query","header","path","formData","body"]);function sn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dt(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function et(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new Gl.SdkError(lt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function fo(e,t){return new Gl.SdkError(lt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function lG(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!Tn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Lh(e,t,r){if(!t.startsWith("#/"))throw fo(r,`has a $ref that is not a local '#/\u2026' pointer (${et(t)})`);if(t.includes("%"))throw fo(r,`has a $ref with a percent-encoded character (${et(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${et(t)}): a '~' not followed by 0 or 1`);let n=lG(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${et(t)})`);return n.value}function ud(e,t){if(Tn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Dt(e.$ref)}, not a string`);return e.$ref}}function uG(e,t,r){if(!sn(t))throw ke(r,`is ${Dt(t)}, not a parameter object`);let n=t,i=ud(t,r);if(i!==void 0){let s=Lh(e,i,r);if(!sn(s))throw ke(r,`has a $ref (${et(i)}) that resolves to ${Dt(s)}, not a parameter object`);if(ud(s,`${r} \u2192 ${et(i)}`)!==void 0)throw fo(r,`has a $ref (${et(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!sG.has(o))throw ke(r,`has an in that is ${typeof o=="string"?et(o):Dt(o)}, not one of query, header, path, formData or body`);if(Tn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Dt(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(Tn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Dt(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Ph(e){return`${e.in}:${e.name}`}function OA(e,t,r){if(!Tn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Dt(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=uG(e,o,s),u=Ph(l);if(i.has(u))throw ke(s,`repeats the parameter ${et(l.name)} in ${et(l.in)}, which must be unique in its list`);return i.add(u),l})}function PA(e,t,r){let n=t.responses;if(!Tn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!sn(o))throw ke(i,`is ${Dt(o)}, not a response object`);let a=o,s=ud(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${et(s)}) that does not name a response ('#/responses/<name>')`);let l=Lh(e,s,i);if(!sn(l))throw ke(i,`has a $ref (${et(s)}) that resolves to ${Dt(l)}, not a response object`);if(ud(l,`${i} \u2192 ${et(s)}`)!==void 0)throw fo(i,`has a $ref (${et(s)}) to a response that is itself a $ref`);a=l}if(Tn(a,"content"))throw fo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(Tn(a,"schema")){if(!sn(a.schema))throw ke(i,`has a schema that is ${Dt(a.schema)}, not an object`);return a.schema}}function IA(e,t,r){if(!Tn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Dt(n)}, not a string`);return n}function cG(e,t,r,n,i){if(!sn(t))throw ke(r,`is ${Dt(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Dt(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${et(o)}, which must be unique in the document`);n.add(o);let a=IA(t,"summary",r),s=IA(t,"description",r),l=OA(e,t,r);if(!sn(t.responses))throw ke(r,`has no responses object (${Dt(t.responses)})`);return PA(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function kh(e){if(!sn(e))throw ke("the document",`is ${Dt(e)}, not an object`);if(Tn(e,"openapi"))throw fo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!Tn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw fo("the document",`declares swagger ${et(String(e.swagger))}, not 2.0`);let t=e.paths;if(!sn(t))throw ke("the document",`has paths that are ${Dt(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${et(i)}]`;if(!sn(o))throw ke(a,`is ${Dt(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(aG.has(l.toLowerCase()))r.push(cG(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of OA(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw fo(a,`has a ${et(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function dG(e){kh(e)}lt.validateConnectorSwagger=dG;var Rh=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new Gl.SdkError(lt.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>TA)throw this.tooLarge(`more than ${TA} nodes`)}text(t){if(this.characters+=t,this.characters>DA)throw this.tooLarge(`more than ${DA} characters of strings and keys`)}checkDepth(t){if(t>_A)throw this.tooLarge(`nesting deeper than ${_A} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(sn(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=NA)throw this.tooLarge(`a $ref chain of more than ${NA} references`);let n=Lh(this.root,t,this.where);if(!sn(n))throw ke(this.where,`has a schema $ref (${et(t)}) that resolves to ${Dt(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function fG(e){let{operations:t}=kh(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}lt.projectConnectorOperations=fG;function pG(e,t){if(typeof t!="string"||t==="")throw new Gl.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=kh(e),i=n.find(u=>u.id===t);if(!i)throw new Gl.SdkError(lt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${et(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Ph)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Ph(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=PA(r,i.node,i.where),l=s===void 0?{}:new Rh(r,`${i.where} (${et(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}lt.projectConnectorOperationSchema=pG});var ea=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zl=Q(),mG=fe(),hG=Wl();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=Nr;function ns(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=ns;function is(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=is;function LA(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=LA;function gG(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=gG;var yG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,bG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function vG(e){let t=LA(e),r=t?t.host.toLowerCase():"";if(bG.test(r))return"Test";let n=yG.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=vG;function Yn(e,t){return new zl.SdkError(hG.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Yn;function wG(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=wG;function CG(e){if(typeof e=="string"&&e.length>0)return is(e,500);if(Nr(e)){let t=Nr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return is(r,500)}return"request failed"}J.messageOf=CG;function kA(e){return Nr(e)&&Nr(e.error)?e.error.code:void 0}J.errorCodeOf=kA;function EG(e){if(Nr(e)&&Nr(e.error)&&Nr(e.error.innererror))return e.error.innererror.code}function AG(e,t,r){let n=[],i=kA(t);typeof i=="string"&&i.length>0&&n.push(is(i,80));let o=EG(t);typeof o=="string"&&o.length>0&&n.push(is(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,zl.attachCause)(new zl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=AG;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var SG=/^[A-Za-z0-9_.-]{1,128}$/,NG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function _G(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(SG.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${is(e,80)}'`:ns(e)}.`)}J.connectorShortName=_G;function TG(e,t,r){let n=`Connection row ${t}`;if(!Nr(e))throw Yn(n,`it is ${ns(e)}, not an object`);let i=e.properties;if(!Nr(i))throw Yn(n,`its properties are ${ns(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Yn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Yn(n,"its apiId names no single connector");if(NG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Yn(n,"it has no name");let l=i.environment,u=Nr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Yn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Yn(n,`its displayName is ${ns(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Yn(n,`its statuses are ${ns(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=Nr(f)?f.status:void 0;if(typeof m!="string")throw Yn(n,"one of its statuses has no string status");return m})}}J.readConnection=TG;var RA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function DG(e){let t=(0,mG.ensureSuccess)(await e.get(RA),e.apiUrl(RA)).body,r=Nr(t)?t.Detail:void 0,n=Nr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new zl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=DG});var qA=v(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.ConnectivityApi=_r.CONNECTIVITY_UNAUTHORIZED_CODE=_r.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=_r.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=_r.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=_r.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Yt=Q(),IG=fe(),dd=Wl(),Hl=ea(),Kl=ea();Object.defineProperty(_r,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(_r,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Kl.CONNECTIVITY_UNAUTHORIZED_CODE}});var $A="2016-11-01",OG="2021-04-01",PG="https://api.bap.microsoft.com",RG="https://test.api.bap.microsoft.com",LG=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,kG=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,xA="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",Oi="/providers/Microsoft.PowerApps/apis/",$G=/^[A-Za-z0-9_.-]{1,128}$/,xG=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),FG="ServiceDecommissioned";function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function po(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Qn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function jl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function FA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function MG(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function ln(e,t){return new Yt.SdkError(dd.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function cd(e){return new Yt.SdkError(Hl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function MA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function UA(e){if(typeof e=="string"&&e.length>0)return Qn(e,500);if(gt(e)){let t=gt(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Qn(r,500)}return"request failed"}function UG(e){return gt(e)&>(e.error)?e.error.code:void 0}function BA(e){if(typeof e=="string"){let r=e.slice(0,Oi.length).toLowerCase()===Oi.toLowerCase()?e.slice(Oi.length):e;if($G.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Yt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${Oi}shared_office365users'); got ${typeof e=="string"?`'${Qn(e,80)}'`:po(e)}.`)}function BG(e,t,r){let n=`Connection row ${t}`;if(!gt(e))throw ln(n,`it is ${po(e)}, not an object`);let i=e.properties;if(!gt(i))throw ln(n,`its properties are ${po(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,Oi.length).toLowerCase()!==Oi.toLowerCase())throw ln(n,`its apiId is not '${Oi}<connector>'`);let a=o.slice(Oi.length);if(a===""||a.includes("/"))throw ln(n,"its apiId names no single connector");if(xG.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw ln(n,"it has no name");let l=i.environment,u=gt(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw ln(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw ln(n,`its displayName is ${po(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw ln(n,`its statuses are ${po(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=gt(f)?f.status:void 0;if(typeof m!="string")throw ln(n,"one of its statuses has no string status");return m})}}var $h=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${$A}&$filter=${MA(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw ln(u,`its value is ${po(d)}, not an array`);for(let m of d){let p=BG(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw ln(u,`its nextLink is ${f===""?"an empty string":po(f)}, not a non-empty string`);if(i.has(f))throw new Yt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Qn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=BA(t);return(0,dd.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=BA(t);if(typeof r!="string"||r==="")throw new Yt.InvalidArgumentError("operationId must be a non-empty string.");return(0,dd.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Yt.SdkError(Hl.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${OG}`,o=(await this.send(t,i,!1)).body,a=gt(o)?o.properties:void 0,s=gt(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw cd(`BAP's environment row is not the one named '${Qn(n,80)}' (its name)`);let l=gt(a)&>(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?jl(l):void 0,c=jl(this.instanceUrl);if(!u||!c||!FA(u,c))throw cd("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=gt(a)?a.runtimeEndpoints:void 0,f=gt(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?jl(f):void 0;if(!m||m.protocol!=="https:"||!MG(m.host.toLowerCase()))throw cd("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=jl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=LG.exec(r);if(n&&n[1]!=="9")return PG;if(kG.test(r))return RG;throw new Yt.SdkError(Hl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Qn(t.host,80)}'`:`'${Qn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,IG.ensureSuccess)(await this.org.get(xA),this.org.apiUrl(xA)).body,r=gt(t)?t.Detail:void 0,n=gt(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw cd("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${Oi}${i}?api-version=${$A}&$filter=${MA(n.id)}`,a=(await this.send(t,o,!0)).body,s=gt(a)?a.properties:void 0,l=gt(s)?s.swagger:void 0;if(!gt(l))throw ln(`The connector '${Qn(r,80)}'`,`its properties.swagger is ${po(l)}, not an object`);return(0,dd.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=jl(t);if(!n)throw new Yt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Qn(t)}'`);if(!FA(n,r))throw new Yt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Qn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Yt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Yt.SdkError?o:new Yt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Yt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Yt.ConnectionError(t,r,UA(n),n);return i&&r===410&&UG(n)===FG?(0,Yt.attachCause)(new Yt.SdkError(Hl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${UA(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,Hl.connectivityUnauthorized)(r,n,a):a}};_r.ConnectivityApi=$h});var Bh=v(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.projectConnectorTableSchema=Be.projectConnectorTables=Be.tableSchemaSuffix=Be.tablesSuffix=Be.encodeTable=Be.encodeDataset=Be.checkTabularConnection=Be.runtimeAuthority=Be.tabularRevision=Be.checkTableSchemaArguments=Be.checkListTablesArguments=void 0;var ta=Q(),M=ea(),qG=/^[A-Za-z0-9_.-]{1,128}$/,ra=/^\.{1,2}$/,VG="shared_sharepointonline",GG=/^[0-9]{1,9}$/,WG=/^[A-Za-z0-9._~-]+$/,zG=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,jG=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,HG=/^[A-Za-z0-9._~!'()*-]$/,KG=/^[0-9A-Fa-f]{2}$/;function Pi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Jl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function xh(e,t){return new ta.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function fd(e,t){return new ta.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function JG(e){if(typeof e=="string"&&qG.test(e)&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Jl(e)}.`)}function YG(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||ra.test(r))===void 0)return e;throw new ta.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Jl(e)}.`)}}function QG(e){if(typeof e=="string"&&e!==""&&!ra.test(e))return e;throw new ta.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Jl(e)}.`)}function GA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:JG(t),dataset:YG(r)}}Be.checkListTablesArguments=GA;function XG(e,t,r,n){return{...GA(e,t,r),table:QG(n)}}Be.checkTableSchemaArguments=XG;function ZG(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!Pi(n,"interfaces"))throw xh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!Pi(i,"CDPTabular1"))throw xh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!GG.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=e8(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw xh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Be.tabularRevision=ZG;function e8(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>WG.test(i)&&!ra.test(i))?t:void 0}function t8(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw fd(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:zG.exec(l);if(!c||ra.test(c[1]))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:jG.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>ra.test(c)))throw fd(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Be.runtimeAuthority=t8;function r8(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Jl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Jl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Be.checkTabularConnection=r8;function VA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function n8(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!KG.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!HG.test(e[t]))return!1;return!0}function WA(e,t){let r,n,i;try{r=VA(e),n=VA(r),i=decodeURIComponent(n)}catch{throw new ta.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!n8(n)||ra.test(n)||i!==r)throw new ta.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function Uh(e){return e.split(",").map((t,r)=>WA(t,`dataset part ${r}`)).join(",")}Be.encodeDataset=Uh;function zA(e){return WA(e,"table")}Be.encodeTable=zA;function i8(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===VG?"allTables":"tables";return`/datasets/${Uh(t)}/${r}`}Be.tablesSuffix=i8;function o8(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${Uh(e)}`}/tables/${zA(t)}`}Be.tableSchemaSuffix=o8;function os(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function a8(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(os(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=os(e,"value"),i=n.found?n:os(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>s8(n,i))}}Be.projectConnectorTables=a8;function s8(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=os(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=os(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=os(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function Fh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function Mh(e,t,r){if(!Pi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function l8(e,t){var r,n;if(Pi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=Mh(e,"type",t),o=Mh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!Pi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(Pi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=Mh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function u8(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Fh(e,"items","items"),i=Fh(e,"schema","schema"),o=i?Fh(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&Pi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&Pi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:l8(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Be.projectConnectorTableSchema=u8});var jA=v(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.PowerPlatformApiDiscovery=void 0;var qh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};pd.PowerPlatformApiDiscovery=qh});var HA=v(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});md.PowerPlatformApiDiscovery=void 0;var c8=jA();Object.defineProperty(md,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return c8.PowerPlatformApiDiscovery}})});var QA=v(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.platformTokenAudience=mo.platformEnvironment=mo.platformClusterOf=void 0;var KA=HA(),JA=Q(),YA=ea(),d8=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,f8=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,p8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,m8=/^default-/i;function Vh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function h8(e){try{return new URL(e).host.toLowerCase()}catch{return}}function g8(e){let t=h8(e);if(t){if(f8.test(t))return{cloud:"Test",category:"test"};let r=d8.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new JA.SdkError(YA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${Vh(t)}'`:`'${Vh(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}mo.platformClusterOf=g8;function y8(e,t){let r=m8.test(e)?e.slice(8):e;if(!p8.test(r))throw new JA.SdkError(YA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${Vh(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new KA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}mo.platformEnvironment=y8;function b8(e){return new KA.PowerPlatformApiDiscovery(e).getTokenAudience()}mo.platformTokenAudience=b8});var ZA=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.PlatformConnectivityApi=as.assertTabularCloud=void 0;var Dn=Q(),Gh=Wl(),pe=ea(),XA=QA(),Ri=Bh(),Wh="1";function zh(e){let t=(0,pe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Dn.SdkError(pe.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}as.assertTabularCloud=zh;var jh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${Wh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,pe.unreadable)(s,`its value is ${(0,pe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,pe.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,pe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,pe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Dn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,pe.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,pe.connectorShortName)(t);return(0,Gh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,pe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Dn.InvalidArgumentError("operationId must be a non-empty string.");return(0,Gh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){zh(this.instanceUrl);let i=(0,Ri.checkListTablesArguments)(t,r,n),o=(0,Ri.tablesSuffix)(i.short,i.dataset);return(0,Ri.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){zh(this.instanceUrl);let o=(0,Ri.checkTableSchemaArguments)(t,r,n,i),a=(0,Ri.tableSchemaSuffix)(o.dataset,o.table);return(0,Ri.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ri.tabularRevision)(o,t.short),s=(0,Ri.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,pe.environmentFilter)(i.name)}&api-version=${Wh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ri.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new Dn.SdkError(pe.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,XA.platformClusterOf)(this.instanceUrl),n=await(0,pe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,XA.platformEnvironment)(n,r),a=(0,pe.parseUrl)(i);if(!a)throw(0,pe.unreadable)("The Power Platform API origin",`'${(0,pe.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,pe.environmentFilter)(r.name)}&api-version=${Wh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,pe.isObject)(i)?i.name:void 0;if(!(0,pe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,pe.bounded)(o,80)}'`:(0,pe.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,pe.isObject)(n)?n.swagger:void 0;if(!(0,pe.isObject)(i))throw(0,pe.unreadable)(`The connector '${(0,pe.bounded)(t,80)}'`,`its properties.swagger is ${(0,pe.kindOf)(i)}, not an object`);return(0,Gh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,pe.parseUrl)(t);if(!n)throw new Dn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,pe.bounded)(t)}'`);if(!(0,pe.sameOrigin)(n,r))throw new Dn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,pe.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof Dn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Dn.SdkError?s:new Dn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Dn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new Dn.ConnectionError(t,r,(0,pe.messageOf)(n),n);return i.includes(r)?(0,pe.connectivityUnauthorized)(r,n,a):a}};as.PlatformConnectivityApi=jh});var tS=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.ConnectivityRouter=void 0;var Hh=Q(),v8=qA(),hd=ea(),eS=Bh(),Kh=ZA(),Jh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,Kh.assertTabularCloud)(this.instanceUrl),(0,eS.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new Kh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,hd.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new Hh.SdkError(hd.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new v8.ConnectivityApi(this.org,this.instanceUrl,r);throw new Hh.SdkError(hd.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};gd.ConnectivityRouter=Jh});var ss=v(Li=>{"use strict";function w8(e,t,r){if(r===void 0&&(r=Array.prototype),e&&typeof r.find=="function")return r.find.call(e,t);for(var n=0;n<e.length;n++)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];if(t.call(void 0,i,n,e))return i}}function Qh(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function C8(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}var rS=Qh({HTML:"text/html",isHTML:function(e){return e===rS.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nS=Qh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nS.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),yd=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,Yh=new RegExp("[\\-\\.0-9"+yd.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),E8=new RegExp("^"+yd.source+Yh.source+"*(?::"+yd.source+Yh.source+"*)?$");Li.assign=C8;Li.find=w8;Li.freeze=Qh;Li.MIME_TYPE=rS;Li.NAMESPACE=nS;Li.nameStartChar=yd;Li.nameChar=Yh;Li.tagNamePattern=E8});var ug=v(Fi=>{var Xh=ss(),Xn=Xh.find,Ql=Xh.NAMESPACE,ls=Xh.tagNamePattern;function A8(e){return e!==""}function S8(e){return e?e.split(/[\t\n\f\r ]+/).filter(A8):[]}function N8(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function iS(e){if(!e)return[];var t=S8(e);return Object.keys(t.reduce(N8,{}))}function _8(e){return function(t){return e&&e.indexOf(t)!==-1}}function Zl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Dr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Zl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Ir={},un=Ir.ELEMENT_NODE=1,us=Ir.ATTRIBUTE_NODE=2,Yl=Ir.TEXT_NODE=3,fS=Ir.CDATA_SECTION_NODE=4,pS=Ir.ENTITY_REFERENCE_NODE=5,T8=Ir.ENTITY_NODE=6,Zh=Ir.PROCESSING_INSTRUCTION_NODE=7,eg=Ir.COMMENT_NODE=8,mS=Ir.DOCUMENT_NODE=9,hS=Ir.DOCUMENT_TYPE_NODE=10,ki=Ir.DOCUMENT_FRAGMENT_NODE=11,D8=Ir.NOTATION_NODE=12,Qt={},Ot={},vce=Qt.INDEX_SIZE_ERR=(Ot[1]="Index size error",1),wce=Qt.DOMSTRING_SIZE_ERR=(Ot[2]="DOMString size error",2),Tr=Qt.HIERARCHY_REQUEST_ERR=(Ot[3]="Hierarchy request error",3),Cce=Qt.WRONG_DOCUMENT_ERR=(Ot[4]="Wrong document",4),oS=Qt.INVALID_CHARACTER_ERR=(Ot[5]="Invalid character",5),Ece=Qt.NO_DATA_ALLOWED_ERR=(Ot[6]="No data allowed",6),Ace=Qt.NO_MODIFICATION_ALLOWED_ERR=(Ot[7]="No modification allowed",7),gS=Qt.NOT_FOUND_ERR=(Ot[8]="Not found",8),Sce=Qt.NOT_SUPPORTED_ERR=(Ot[9]="Not supported",9),aS=Qt.INUSE_ATTRIBUTE_ERR=(Ot[10]="Attribute in use",10),In=Qt.INVALID_STATE_ERR=(Ot[11]="Invalid state",11),Nce=Qt.SYNTAX_ERR=(Ot[12]="Syntax error",12),_ce=Qt.INVALID_MODIFICATION_ERR=(Ot[13]="Invalid modification",13),Tce=Qt.NAMESPACE_ERR=(Ot[14]="Invalid namespace",14),Dce=Qt.INVALID_ACCESS_ERR=(Ot[15]="Invalid access",15);function me(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ot[e]),this.message=Ot[e],Error.captureStackTrace&&Error.captureStackTrace(this,me);return r.code=e,t&&(this.message=this.message+": "+t),r}me.prototype=Error.prototype;Zl(Qt,me);function $i(){}$i.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,r){for(var n=!!r&&!!r.requireWellFormed,i=[],o=0;o<this.length;o++)lg(this[o],i,e,t,null,n);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function cs(e,t){this._node=e,this._refresh=t,tg(this)}function tg(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(IS(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];Zl(r,e),e._inc=t}}cs.prototype.item=function(e){return tg(this),this[e]||null};Dr(cs,$i);function vd(){this._nameIndex=Object.create(null)}function yS(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function I8(e,t){e._nameIndex[t.nodeName]=t}function bS(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function sS(e,t,r,n){if(n?(t[yS(t,n)]=r,bS(t,n)):t[t.length++]=r,I8(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&CS(i,e,n),O8(i,e,r))}}function lS(e,t,r){var n=yS(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,bS(t,r),e){var o=e.ownerDocument;o&&(CS(o,e,r),r.ownerElement=null)}}else throw new me(gS,new Error(e.tagName+"@"+r))}vd.prototype={length:0,item:$i.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var r=this[t];if(r.nodeName==e)return r}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new me(aS);var r=this._nameIndex[e.nodeName];return sS(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new me(aS);return r=this.getNamedItemNS(e.namespaceURI,e.localName),sS(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return lS(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return lS(this._ownerElement,this,r),r},getNamedItemNS:function(e,t){for(var r=this.length;r--;){var n=this[r];if(n.localName==t&&n.namespaceURI==e)return n}return null}};function vS(){}vS.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new eu;if(n.implementation=this,n.childNodes=new $i,n.doctype=r||null,r&&n.appendChild(r),t){var i=n.createElementNS(e,t);n.appendChild(i)}return n},createDocumentType:function(e,t,r){var n=new Sd;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Cd(this,e,t)},replaceChild:function(e,t){Cd(this,e,t,AS),t&&this.removeChild(t)},removeChild:function(e){return ES(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return DS(this.ownerDocument||this,this,e)},normalize:function(){It(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Yl&&t.nodeType===Yl){for(var n=[],i=r;i!==null&&i.nodeType===Yl;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Ad(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==us?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var r=t._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];t=t.nodeType==us?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function wS(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Zl(Ir,De);Zl(Ir,De.prototype);function wd(e,t){return It(e,null,{enter:function(r){return t(r)?It.STOP:!0}})===It.STOP}function It(e,t,r){for(var n=[{node:e,context:t,phase:It.ENTER}];n.length>0;){var i=n.pop();if(i.phase===It.ENTER){var o=r.enter(i.node,i.context);if(o===It.STOP)return It.STOP;if(n.push({node:i.node,context:o,phase:It.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:It.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}It.STOP=Symbol("walkDOM.STOP");It.ENTER=0;It.EXIT=1;function eu(){this.ownerDocument=this}function O8(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ql.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function CS(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ql.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Ad(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function ES(e,t){var r=t.previousSibling,n=t.nextSibling;return r?r.nextSibling=n:e.firstChild=n,n?n.previousSibling=r:e.lastChild=r,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,Ad(e.ownerDocument,e),t}function P8(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function R8(e){return e&&(Zn(e)||rg(e)||xi(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function xi(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function Zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function rg(e){return e&&e.nodeType===De.TEXT_NODE}function uS(e,t){var r=e.childNodes||[];if(Xn(r,Zn)||xi(t))return!1;var n=Xn(r,xi);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function cS(e,t){var r=e.childNodes||[];function n(o){return Zn(o)&&o!==t}if(Xn(r,n))return!1;var i=Xn(r,xi);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function L8(e,t,r){if(!P8(e))throw new me(Tr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new me(gS,"child not in parent");if(!R8(t)||xi(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new me(Tr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function k8(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!uS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!uS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){if(Xn(n,xi))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element");if(!r&&a)throw new me(Tr,"Doctype can not be appended since element is present")}}function AS(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Zn);if(o.length>1||Xn(i,rg))throw new me(Tr,"More than one element or text in fragment");if(o.length===1&&!cS(e,r))throw new me(Tr,"Element in fragment can not be inserted before doctype")}if(Zn(t)&&!cS(e,r))throw new me(Tr,"Only one element can be added and only after doctype");if(xi(t)){let l=function(u){return xi(u)&&u!==r};var s=l;if(Xn(n,l))throw new me(Tr,"Only one doctype is allowed");var a=Xn(n,Zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new me(Tr,"Doctype can only be inserted before an element")}}function Cd(e,t,r,n){L8(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||k8)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===ki){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Xl(o,l)}while(o!==a&&(o=o.nextSibling));return Ad(e.ownerDocument||e,e),t.nodeType==ki&&(t.firstChild=t.lastChild=null),t}function Xl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===un&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)Xl(i,t),i=i.nextSibling}}function $8(e,t){t.parentNode&&t.parentNode.removeChild(t),t.parentNode=e,t.previousSibling=e.lastChild,t.nextSibling=null,t.previousSibling?t.previousSibling.nextSibling=t:e.firstChild=t,e.lastChild=t,Ad(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Xl(t,r),t}eu.prototype={nodeName:"#document",nodeType:mS,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==ki){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Cd(this,e,t),Xl(e,this),this.documentElement===null&&e.nodeType===un&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),ES(this,e)},replaceChild:function(e,t){Cd(this,e,t,AS),Xl(e,this),t&&this.removeChild(t),Zn(e)&&(this.documentElement=e)},importNode:function(e,t){return x8(this,e,t)},getElementById:function(e){var t=null;return wd(this.documentElement,function(r){if(r.nodeType==un&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=iS(e);return new cs(this,function(r){var n=[];return t.length>0&&wd(r.documentElement,function(i){if(i!==r&&i.nodeType===un){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=iS(o);a=t.every(_8(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new na;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new $i;var r=t.attributes=new vd;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Nd;return e.ownerDocument=this,e.childNodes=new $i,e},createTextNode:function(e){var t=new ng;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new ig;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new me(oS,'data contains "]]>"');var t=new og;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new sg;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Ed;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!ls.test(e))throw new me(oS,'not a valid xml name "'+e+'"');var t=new ag;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new na,n=t.split(":"),i=r.attributes=new vd;return r.childNodes=new $i,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=e,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,i._ownerElement=r,r},createAttributeNS:function(e,t){var r=new Ed,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,n.length==2?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}};Dr(eu,De);function na(){this._nsMap={}}na.prototype={nodeType:un,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var r=this.ownerDocument.createAttribute(e);r.value=r.nodeValue=""+t,this.setAttributeNode(r)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===ki?this.insertBefore(e,null):$8(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);r&&this.removeAttributeNode(r)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);return r&&r.value||""},setAttributeNS:function(e,t,r){var n=this.ownerDocument.createAttributeNS(e,t);n.value=n.nodeValue=""+r,this.setAttributeNode(n)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new cs(this,function(t){var r=[];return wd(t,function(n){n!==t&&n.nodeType==un&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new cs(this,function(r){var n=[];return wd(r,function(i){i!==r&&i.nodeType===un&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};eu.prototype.getElementsByTagName=na.prototype.getElementsByTagName;eu.prototype.getElementsByTagNameNS=na.prototype.getElementsByTagNameNS;Dr(na,De);function Ed(){}Ed.prototype.nodeType=us;Dr(Ed,De);function tu(){}tu.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(Ot[Tr])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){var n=this.data.substring(0,e),i=this.data.substring(e+t);r=n+r+i,this.nodeValue=this.data=r,this.length=r.length}};Dr(tu,De);function ng(){}ng.prototype={nodeName:"#text",nodeType:Yl,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};Dr(ng,tu);function ig(){}ig.prototype={nodeName:"#comment",nodeType:eg};Dr(ig,tu);function og(){}og.prototype={nodeName:"#cdata-section",nodeType:fS};Dr(og,tu);function Sd(){}Sd.prototype.nodeType=hS;Dr(Sd,De);function SS(){}SS.prototype.nodeType=D8;Dr(SS,De);function NS(){}NS.prototype.nodeType=T8;Dr(NS,De);function ag(){}ag.prototype.nodeType=pS;Dr(ag,De);function Nd(){}Nd.prototype.nodeName="#document-fragment";Nd.prototype.nodeType=ki;Dr(Nd,De);function sg(){}sg.prototype.nodeType=Zh;Dr(sg,De);function _S(){}_S.prototype.serializeToString=function(e,t,r,n){return TS.call(e,t,r,n)};De.prototype.toString=TS;function TS(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return lg(this,i,e,t,l,n),i.join("")}function dS(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ql.XML||i===Ql.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function bd(e,t,r,n){if(n&&!ls.test(t))throw new me(In,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,wS),'"')}function lg(e,t,r,n,i,o){i||(i=[]),It(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case un:var c=a.attributes,d=c.length,f=a.tagName;u=Ql.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!ls.test(m))throw new me(In,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),C=0;C<d;C++){var S=c.item(C);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var C=0;C<d;C++){var S=c.item(C);if(dS(S,u,w)){var O=S.prefix||"",L=S.namespaceURI;bd(t,O?"xmlns:"+O:"xmlns",L,o),w.push({prefix:O,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):bd(t,I.name,I.value,o))}if(f===m&&dS(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;bd(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;P;)P.data?t.push(P.data):lg(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case mS:case ki:return{ns:l.slice(),isHTML:u,tag:null};case us:return bd(t,a.name,a.value,o),null;case Yl:return t.push(a.data.replace(/[<&>]/g,wS)),null;case fS:if(o&&a.data.indexOf("]]>")!==-1)throw new me(In,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case eg:if(o&&a.data.indexOf("-->")!==-1)throw new me(In,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case hS:if(o){if(!ls.test(a.name))throw new me(In,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new me(In,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new me(In,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new me(In,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Le=a.internalSubset;Le&&t.push(" [",Le,"]"),t.push(">")}return null;case Zh:if(o){if(!ls.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new me(In,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new me(In,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case pS:if(o&&!ls.test(a.nodeName))throw new me(In,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function x8(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===us||r;return s?a:null}}),n}function DS(e,t,r){var n;return It(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new $i),a.ownerDocument=e;var u=r;switch(a.nodeType){case un:var c=i.attributes,d=a.attributes=new vd,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(DS(e,c.item(m),!0));break;case us:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function IS(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(cs.prototype,"length",{get:function(){return tg(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===un||this.nodeType===ki){var e=[];return It(this,null,{enter:function(t){if(t.nodeType===un||t.nodeType===ki)return!0;if(t.nodeType===Zh||t.nodeType===eg)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case un:case ki:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),IS=function(e,t,r){e["$$"+t]=r})}catch{}Fi.DocumentType=Sd;Fi.DOMException=me;Fi.DOMImplementation=vS;Fi.Element=na;Fi.Node=De;Fi.NodeList=$i;Fi.walkDOM=It;Fi.XMLSerializer=_S});var PS=v(ru=>{"use strict";var OS=ss().freeze;ru.XML_ENTITIES=OS({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ru.HTML_ENTITIES=OS({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`-`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});ru.entityMap=ru.HTML_ENTITIES});var xS=v(dg=>{var ou=ss().NAMESPACE,cg=ss().tagNamePattern,ds=0,ho=1,fs=2,nu=3,ps=4,ms=5,iu=6,_d=7;function hs(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,hs)}hs.prototype=new Error;hs.prototype.name=hs.name;function kS(){}kS.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),q8(t,t={}),F8(e,t,r,n,this.errorHandler),n.endDocument()}};function F8(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var Ke=55296+(de>>10),ur=56320+(de&1023);return String.fromCharCode(Ke,ur)}else return String.fromCharCode(de)}function a(de){var Ke=de.slice(1,-1);return Object.hasOwnProperty.call(r,Ke)?r[Ke]:Ke.charAt(0)==="#"?o(parseInt(Ke.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var Ke=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(Ke,0,de-h),h=de}}function l(de,Ke){for(;de>=c&&(Ke=d.exec(e));)u=Ke.index,c=u+Ke[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),C=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),K=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),K=g+1+C.length):/[ \t\n\r]/.test(C)&&cg.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,L=S.tagName==C,I=L||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,C),O)for(var D in O)Object.prototype.hasOwnProperty.call(O,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=G8(e,g,n);break;case"!":f&&l(g),K=V8(e,g,n,i);break;default:f&&l(g);var P=new $S,x=m[m.length-1].currentNSMap,K=M8(e,g,P,x,a,i),Le=P.length;if(!P.closed&&B8(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Le){for(var lr=RS(f,{}),Ge=0;Ge<Le;Ge++){var Ut=P[Ge];l(Ut.offset),Ut.locator=RS(f,{})}n.locator=lr,LS(P,n,x)&&m.push(P),n.locator=f}else LS(P,n,x)&&m.push(P);ou.isHTML(P.uri)&&!P.closed?K=U8(e,K,P.tagName,a,n):K++}}catch(de){if(de instanceof hs)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function RS(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function M8(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=ds;;){var d=e.charAt(u);if(c===ds&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ho)s=e.slice(t,u),c=nu;else if(c===fs)c=nu;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===nu||c===ho)if(c===ho&&(o.warning('attribute value must after "="'),s=e.slice(t,u)),t=u+1,u=e.indexOf(d,t),u>0)l=e.slice(t,u),a(s,l,t-1),c=ms;else throw new Error("attribute value no end '"+d+"' match");else if(c==ps)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=ms;else throw new Error('attribute value must after "="');break;case"/":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:c=_d,r.closed=!0;case ps:case ho:break;case fs:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==ds&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case ds:r.setTagName(e.slice(t,u));case ms:case iu:case _d:break;case ps:case ho:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case fs:c===fs&&(l=s),c==ps?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!ou.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case nu:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case ds:r.setTagName(e.slice(t,u)),c=iu;break;case ho:s=e.slice(t,u),c=fs;break;case ps:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case ms:c=iu;break}else switch(c){case fs:var f=r.tagName;(!ou.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ho;break;case ms:o.warning('attribute space is required"'+s+'"!!');case iu:c=ho,t=u;break;case nu:c=ps,t=u;break;case _d:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function LS(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=ou.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=ou.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var m=e.uri=r[l||""];if(t.startElement(m,u,n,e),e.closed){if(t.endElement(m,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function U8(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function B8(e,t,r,n){var i=n[r];return i==null&&(i=e.lastIndexOf("</"+r+">"),i<t&&(i=e.lastIndexOf("</"+r)),n[r]=i),i<t}function q8(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function V8(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=W8(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function G8(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function $S(){this.attributeNames={}}$S.prototype={setTagName:function(e){if(!cg.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!cg.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}};function W8(e,t){var r,n=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);r=i.exec(e);)if(n.push(r),r[1])return n}dg.XMLReader=kS;dg.ParseError=hs});var GS=v(Dd=>{var z8=ss(),j8=ug(),FS=PS(),BS=xS(),H8=j8.DOMImplementation,MS=z8.NAMESPACE,K8=BS.ParseError,J8=BS.XMLReader;function qS(e){return e.replace(/\r[\n\u0085]/g,`+`}});var NE=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.generateGenPageRuntimeTypes=void 0;var SE=Km(),Fo=Q(),AE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Mo="generateGenPageRuntimeTypes";async function vV(e,t,r){let n=wV(t),i=CV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Fo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Mo}: 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,SE.renderGenPageAuthoringTypes)(o,i)}Fc.generateGenPageRuntimeTypes=vV;function wV(e){if(!Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!SE.TABLE_LOGICAL_NAME.test(r))throw new Fo.InvalidArgumentError(`${Mo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Fo.InvalidArgumentError(`${Mo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function CV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Fo.InvalidArgumentError(`${Mo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!AE.has(r))throw new Fo.InvalidArgumentError(`${Mo}: detail must be one of ${[...AE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var PE=v(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.getEnvironmentLanguages=Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var EV=Q(),DE=ye();Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var _E="/organizations?$select=languagecode",AV="/RetrieveProvisionedLanguages()",SV="/RetrieveAvailableLanguages()";function IE(e,t){return new EV.SdkError(Uo.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 OE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function TE(e,t,r,n){let i=(0,DE.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(OE))throw IE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function NV(e){var t;let r=(0,DE.ensureSuccess)(await e.get(_E),e.apiUrl(_E)).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(!OE(i))throw IE("the organization read","did not answer one row with a language code");let o=await TE(e,AV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await TE(e,SV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Uo.getEnvironmentLanguages=NV});var Al=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.projectConnectorOperationSchema=nt.projectConnectorOperations=nt.validateConnectorSwagger=nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=nt.CONNECTOR_OPERATION_NOT_FOUND_CODE=nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var El=Q();nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";nt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var RE=64,LE=128,kE=2e5,$E=4e6,_V=new Set(["get","put","post","delete","patch","head","options"]),TV=new Set(["query","header","path","formData","body"]);function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Et(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Xe(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new El.SdkError(nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function Zi(e,t){return new El.SdkError(nt.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 DV(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||!vn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Qm(e,t,r){if(!t.startsWith("#/"))throw Zi(r,`has a $ref that is not a local '#/\u2026' pointer (${Xe(t)})`);if(t.includes("%"))throw Zi(r,`has a $ref with a percent-encoded character (${Xe(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${Xe(t)}): a '~' not followed by 0 or 1`);let n=DV(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${Xe(t)})`);return n.value}function Mc(e,t){if(vn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Et(e.$ref)}, not a string`);return e.$ref}}function IV(e,t,r){if(!Qr(t))throw ke(r,`is ${Et(t)}, not a parameter object`);let n=t,i=Mc(t,r);if(i!==void 0){let s=Qm(e,i,r);if(!Qr(s))throw ke(r,`has a $ref (${Xe(i)}) that resolves to ${Et(s)}, not a parameter object`);if(Mc(s,`${r} \u2192 ${Xe(i)}`)!==void 0)throw Zi(r,`has a $ref (${Xe(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!TV.has(o))throw ke(r,`has an in that is ${typeof o=="string"?Xe(o):Et(o)}, not one of query, header, path, formData or body`);if(vn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Et(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(vn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Et(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Jm(e){return`${e.in}:${e.name}`}function FE(e,t,r){if(!vn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Et(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=IV(e,o,s),u=Jm(l);if(i.has(u))throw ke(s,`repeats the parameter ${Xe(l.name)} in ${Xe(l.in)}, which must be unique in its list`);return i.add(u),l})}function ME(e,t,r){let n=t.responses;if(!vn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Qr(o))throw ke(i,`is ${Et(o)}, not a response object`);let a=o,s=Mc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${Xe(s)}) that does not name a response ('#/responses/<name>')`);let l=Qm(e,s,i);if(!Qr(l))throw ke(i,`has a $ref (${Xe(s)}) that resolves to ${Et(l)}, not a response object`);if(Mc(l,`${i} \u2192 ${Xe(s)}`)!==void 0)throw Zi(i,`has a $ref (${Xe(s)}) to a response that is itself a $ref`);a=l}if(vn(a,"content"))throw Zi(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(vn(a,"schema")){if(!Qr(a.schema))throw ke(i,`has a schema that is ${Et(a.schema)}, not an object`);return a.schema}}function xE(e,t,r){if(!vn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Et(n)}, not a string`);return n}function OV(e,t,r,n,i){if(!Qr(t))throw ke(r,`is ${Et(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Et(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${Xe(o)}, which must be unique in the document`);n.add(o);let a=xE(t,"summary",r),s=xE(t,"description",r),l=FE(e,t,r);if(!Qr(t.responses))throw ke(r,`has no responses object (${Et(t.responses)})`);return ME(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function Xm(e){if(!Qr(e))throw ke("the document",`is ${Et(e)}, not an object`);if(vn(e,"openapi"))throw Zi("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!vn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw Zi("the document",`declares swagger ${Xe(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Qr(t))throw ke("the document",`has paths that are ${Et(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Xe(i)}]`;if(!Qr(o))throw ke(a,`is ${Et(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(_V.has(l.toLowerCase()))r.push(OV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of FE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw Zi(a,`has a ${Xe(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function PV(e){Xm(e)}nt.validateConnectorSwagger=PV;var Ym=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new El.SdkError(nt.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>kE)throw this.tooLarge(`more than ${kE} nodes`)}text(t){if(this.characters+=t,this.characters>$E)throw this.tooLarge(`more than ${$E} characters of strings and keys`)}checkDepth(t){if(t>LE)throw this.tooLarge(`nesting deeper than ${LE} 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(Qr(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>=RE)throw this.tooLarge(`a $ref chain of more than ${RE} references`);let n=Qm(this.root,t,this.where);if(!Qr(n))throw ke(this.where,`has a schema $ref (${Xe(t)}) that resolves to ${Et(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function RV(e){let{operations:t}=Xm(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}})}}nt.projectConnectorOperations=RV;function LV(e,t){if(typeof t!="string"||t==="")throw new El.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=Xm(e),i=n.find(u=>u.id===t);if(!i)throw new El.SdkError(nt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Xe(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Jm)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Jm(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=ME(r,i.node,i.where),l=s===void 0?{}:new Ym(r,`${i.where} (${Xe(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}nt.projectConnectorOperationSchema=LV});var Bo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Sl=Q(),kV=ye(),$V=Al();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=yr;function Ba(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ba;function qa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=qa;function BE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=BE;function xV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=xV;var FV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,MV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function UV(e){let t=BE(e),r=t?t.host.toLowerCase():"";if(MV.test(r))return"Test";let n=FV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=UV;function Vn(e,t){return new Sl.SdkError($V.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Vn;function BV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=BV;function qV(e){if(typeof e=="string"&&e.length>0)return qa(e,500);if(yr(e)){let t=yr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return qa(r,500)}return"request failed"}J.messageOf=qV;function qE(e){return yr(e)&&yr(e.error)?e.error.code:void 0}J.errorCodeOf=qE;function VV(e){if(yr(e)&&yr(e.error)&&yr(e.error.innererror))return e.error.innererror.code}function GV(e,t,r){let n=[],i=qE(t);typeof i=="string"&&i.length>0&&n.push(qa(i,80));let o=VV(t);typeof o=="string"&&o.length>0&&n.push(qa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Sl.attachCause)(new Sl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=GV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var WV=/^[A-Za-z0-9_.-]{1,128}$/,zV=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function jV(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(WV.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Sl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${qa(e,80)}'`:Ba(e)}.`)}J.connectorShortName=jV;function HV(e,t,r){let n=`Connection row ${t}`;if(!yr(e))throw Vn(n,`it is ${Ba(e)}, not an object`);let i=e.properties;if(!yr(i))throw Vn(n,`its properties are ${Ba(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 Vn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Vn(n,"its apiId names no single connector");if(zV.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Vn(n,"it has no name");let l=i.environment,u=yr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Vn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Vn(n,`its displayName is ${Ba(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Vn(n,`its statuses are ${Ba(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=yr(f)?f.status:void 0;if(typeof m!="string")throw Vn(n,"one of its statuses has no string status");return m})}}J.readConnection=HV;var UE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function KV(e){let t=(0,kV.ensureSuccess)(await e.get(UE),e.apiUrl(UE)).body,r=yr(t)?t.Detail:void 0,n=yr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Sl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=KV});var KE=v(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.ConnectivityApi=br.CONNECTIVITY_UNAUTHORIZED_CODE=br.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=br.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=br.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=br.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Wt=Q(),JV=ye(),Bc=Al(),_l=Bo(),Tl=Bo();Object.defineProperty(br,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(br,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(br,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_UNAUTHORIZED_CODE}});var VE="2016-11-01",YV="2021-04-01",QV="https://api.bap.microsoft.com",XV="https://test.api.bap.microsoft.com",ZV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,e4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,GE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",bi="/providers/Microsoft.PowerApps/apis/",t4=/^[A-Za-z0-9_.-]{1,128}$/,r4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),n4="ServiceDecommissioned";function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eo(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Gn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Nl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function WE(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function i4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function Xr(e,t){return new Wt.SdkError(Bc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function Uc(e){return new Wt.SdkError(_l.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function zE(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function jE(e){if(typeof e=="string"&&e.length>0)return Gn(e,500);if(ct(e)){let t=ct(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Gn(r,500)}return"request failed"}function o4(e){return ct(e)&&ct(e.error)?e.error.code:void 0}function HE(e){if(typeof e=="string"){let r=e.slice(0,bi.length).toLowerCase()===bi.toLowerCase()?e.slice(bi.length):e;if(t4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Wt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${bi}shared_office365users'); got ${typeof e=="string"?`'${Gn(e,80)}'`:eo(e)}.`)}function a4(e,t,r){let n=`Connection row ${t}`;if(!ct(e))throw Xr(n,`it is ${eo(e)}, not an object`);let i=e.properties;if(!ct(i))throw Xr(n,`its properties are ${eo(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,bi.length).toLowerCase()!==bi.toLowerCase())throw Xr(n,`its apiId is not '${bi}<connector>'`);let a=o.slice(bi.length);if(a===""||a.includes("/"))throw Xr(n,"its apiId names no single connector");if(r4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Xr(n,"it has no name");let l=i.environment,u=ct(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Xr(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Xr(n,`its displayName is ${eo(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Xr(n,`its statuses are ${eo(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ct(f)?f.status:void 0;if(typeof m!="string")throw Xr(n,"one of its statuses has no string status");return m})}}var Zm=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=${VE}&$filter=${zE(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 Xr(u,`its value is ${eo(d)}, not an array`);for(let m of d){let p=a4(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 Xr(u,`its nextLink is ${f===""?"an empty string":eo(f)}, not a non-empty string`);if(i.has(f))throw new Wt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Gn(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=HE(t);return(0,Bc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=HE(t);if(typeof r!="string"||r==="")throw new Wt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Bc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Wt.SdkError(_l.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${YV}`,o=(await this.send(t,i,!1)).body,a=ct(o)?o.properties:void 0,s=ct(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw Uc(`BAP's environment row is not the one named '${Gn(n,80)}' (its name)`);let l=ct(a)&&ct(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Nl(l):void 0,c=Nl(this.instanceUrl);if(!u||!c||!WE(u,c))throw Uc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ct(a)?a.runtimeEndpoints:void 0,f=ct(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Nl(f):void 0;if(!m||m.protocol!=="https:"||!i4(m.host.toLowerCase()))throw Uc("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=Nl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=ZV.exec(r);if(n&&n[1]!=="9")return QV;if(e4.test(r))return XV;throw new Wt.SdkError(_l.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Gn(t.host,80)}'`:`'${Gn(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,JV.ensureSuccess)(await this.org.get(GE),this.org.apiUrl(GE)).body,r=ct(t)?t.Detail:void 0,n=ct(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw Uc("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}${bi}${i}?api-version=${VE}&$filter=${zE(n.id)}`,a=(await this.send(t,o,!0)).body,s=ct(a)?a.properties:void 0,l=ct(s)?s.swagger:void 0;if(!ct(l))throw Xr(`The connector '${Gn(r,80)}'`,`its properties.swagger is ${eo(l)}, not an object`);return(0,Bc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Nl(t);if(!n)throw new Wt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Gn(t)}'`);if(!WE(n,r))throw new Wt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Gn(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 Wt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Wt.SdkError?o:new Wt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Wt.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 Wt.ConnectionError(t,r,jE(n),n);return i&&r===410&&o4(n)===n4?(0,Wt.attachCause)(new Wt.SdkError(_l.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${jE(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,_l.connectivityUnauthorized)(r,n,a):a}};br.ConnectivityApi=Zm});var ih=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 qo=Q(),M=Bo(),s4=/^[A-Za-z0-9_.-]{1,128}$/,Vo=/^\.{1,2}$/,l4="shared_sharepointonline",u4=/^[0-9]{1,9}$/,c4=/^[A-Za-z0-9._~-]+$/,d4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,f4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,p4=/^[A-Za-z0-9._~!'()*-]$/,m4=/^[0-9A-Fa-f]{2}$/;function vi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function eh(e,t){return new qo.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function qc(e,t){return new qo.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 h4(e){if(typeof e=="string"&&s4.test(e)&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Dl(e)}.`)}function g4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Vo.test(r))===void 0)return e;throw new qo.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Dl(e)}.`)}}function y4(e){if(typeof e=="string"&&e!==""&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Dl(e)}.`)}function YE(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:h4(t),dataset:g4(r)}}Me.checkListTablesArguments=YE;function b4(e,t,r,n){return{...YE(e,t,r),table:y4(n)}}Me.checkTableSchemaArguments=b4;function v4(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(!vi(n,"interfaces"))throw eh(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(!vi(i,"CDPTabular1"))throw eh(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(!u4.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=w4(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 eh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=v4;function w4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>c4.test(i)&&!Vo.test(i))?t:void 0}function C4(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 qc(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 qc(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:d4.exec(l);if(!c||Vo.test(c[1]))throw qc(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:f4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Vo.test(c)))throw qc(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=C4;function E4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Dl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Dl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=E4;function JE(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function A4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!m4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!p4.test(e[t]))return!1;return!0}function QE(e,t){let r,n,i;try{r=JE(e),n=JE(r),i=decodeURIComponent(n)}catch{throw new qo.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!A4(n)||Vo.test(n)||i!==r)throw new qo.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function nh(e){return e.split(",").map((t,r)=>QE(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=nh;function XE(e){return QE(e,"table")}Me.encodeTable=XE;function S4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===l4?"allTables":"tables";return`/datasets/${nh(t)}/${r}`}Me.tablesSuffix=S4;function N4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${nh(e)}`}/tables/${XE(t)}`}Me.tableSchemaSuffix=N4;function Va(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 _4(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(Va(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=Va(e,"value"),i=n.found?n:Va(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)=>T4(n,i))}}Me.projectConnectorTables=_4;function T4(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=Va(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=Va(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=Va(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 th(e,t,r){if(!vi(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 rh(e,t,r){if(!vi(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 D4(e,t){var r,n;if(vi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=rh(e,"type",t),o=rh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!vi(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(vi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=rh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function I4(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=th(e,"items","items"),i=th(e,"schema","schema"),o=i?th(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&&vi(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&&vi(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:D4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=I4});var ZE=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.PowerPlatformApiDiscovery=void 0;var oh=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}`)}}};Vc.PowerPlatformApiDiscovery=oh});var eA=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.PowerPlatformApiDiscovery=void 0;var O4=ZE();Object.defineProperty(Gc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return O4.PowerPlatformApiDiscovery}})});var iA=v(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.platformTokenAudience=to.platformEnvironment=to.platformClusterOf=void 0;var tA=eA(),rA=Q(),nA=Bo(),P4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,R4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,L4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,k4=/^default-/i;function ah(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function $4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function x4(e){let t=$4(e);if(t){if(R4.test(t))return{cloud:"Test",category:"test"};let r=P4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new rA.SdkError(nA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${ah(t)}'`:`'${ah(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.`)}to.platformClusterOf=x4;function F4(e,t){let r=k4.test(e)?e.slice(8):e;if(!L4.test(r))throw new rA.SdkError(nA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${ah(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 tA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}to.platformEnvironment=F4;function M4(e){return new tA.PowerPlatformApiDiscovery(e).getTokenAudience()}to.platformTokenAudience=M4});var aA=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.PlatformConnectivityApi=Ga.assertTabularCloud=void 0;var wn=Q(),sh=Al(),fe=Bo(),oA=iA(),wi=ih(),lh="1";function uh(e){let t=(0,fe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new wn.SdkError(fe.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.")}Ga.assertTabularCloud=uh;var ch=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=${lh}`,[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,fe.unreadable)(s,`its value is ${(0,fe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,fe.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,fe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,fe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new wn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,fe.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,fe.connectorShortName)(t);return(0,sh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,fe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new wn.InvalidArgumentError("operationId must be a non-empty string.");return(0,sh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){uh(this.instanceUrl);let i=(0,wi.checkListTablesArguments)(t,r,n),o=(0,wi.tablesSuffix)(i.short,i.dataset);return(0,wi.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){uh(this.instanceUrl);let o=(0,wi.checkTableSchemaArguments)(t,r,n,i),a=(0,wi.tableSchemaSuffix)(o.dataset,o.table);return(0,wi.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,wi.tabularRevision)(o,t.short),s=(0,wi.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,fe.environmentFilter)(i.name)}&api-version=${lh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,wi.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 wn.SdkError(fe.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,oA.platformClusterOf)(this.instanceUrl),n=await(0,fe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,oA.platformEnvironment)(n,r),a=(0,fe.parseUrl)(i);if(!a)throw(0,fe.unreadable)("The Power Platform API origin",`'${(0,fe.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,fe.environmentFilter)(r.name)}&api-version=${lh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,fe.isObject)(i)?i.name:void 0;if(!(0,fe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,fe.bounded)(o,80)}'`:(0,fe.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,fe.isObject)(n)?n.swagger:void 0;if(!(0,fe.isObject)(i))throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`its properties.swagger is ${(0,fe.kindOf)(i)}, not an object`);return(0,sh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,fe.parseUrl)(t);if(!n)throw new wn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,fe.bounded)(t)}'`);if(!(0,fe.sameOrigin)(n,r))throw new wn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,fe.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 wn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof wn.SdkError?s:new wn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new wn.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 wn.ConnectionError(t,r,(0,fe.messageOf)(n),n);return i.includes(r)?(0,fe.connectivityUnauthorized)(r,n,a):a}};Ga.PlatformConnectivityApi=ch});var lA=v(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.ConnectivityRouter=void 0;var dh=Q(),U4=KE(),Wc=Bo(),sA=ih(),fh=aA(),ph=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,fh.assertTabularCloud)(this.instanceUrl),(0,sA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,fh.assertTabularCloud)(this.instanceUrl),(0,sA.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 fh.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 dh.SdkError(Wc.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,Wc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new dh.SdkError(Wc.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 U4.ConnectivityApi(this.org,this.instanceUrl,r);throw new dh.SdkError(Wc.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.")}};zc.ConnectivityRouter=ph});var Wa=v(Ci=>{"use strict";function B4(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 hh(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 uA=hh({HTML:"text/html",isHTML:function(e){return e===uA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),cA=hh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===cA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),jc=/[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]/,mh=new RegExp("[\\-\\.0-9"+jc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),V4=new RegExp("^"+jc.source+mh.source+"*(?::"+jc.source+mh.source+"*)?$");Ci.assign=q4;Ci.find=B4;Ci.freeze=hh;Ci.MIME_TYPE=uA;Ci.NAMESPACE=cA;Ci.nameStartChar=jc;Ci.nameChar=mh;Ci.tagNamePattern=V4});var Th=v(Ni=>{var gh=Wa(),Wn=gh.find,Ol=gh.NAMESPACE,za=gh.tagNamePattern;function G4(e){return e!==""}function W4(e){return e?e.split(/[\t\n\f\r ]+/).filter(G4):[]}function z4(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function dA(e){if(!e)return[];var t=W4(e);return Object.keys(t.reduce(z4,{}))}function j4(e){return function(t){return e&&e.indexOf(t)!==-1}}function Rl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function wr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Rl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Cr={},Zr=Cr.ELEMENT_NODE=1,ja=Cr.ATTRIBUTE_NODE=2,Il=Cr.TEXT_NODE=3,vA=Cr.CDATA_SECTION_NODE=4,wA=Cr.ENTITY_REFERENCE_NODE=5,H4=Cr.ENTITY_NODE=6,yh=Cr.PROCESSING_INSTRUCTION_NODE=7,bh=Cr.COMMENT_NODE=8,CA=Cr.DOCUMENT_NODE=9,EA=Cr.DOCUMENT_TYPE_NODE=10,Ei=Cr.DOCUMENT_FRAGMENT_NODE=11,K4=Cr.NOTATION_NODE=12,zt={},St={},Ise=zt.INDEX_SIZE_ERR=(St[1]="Index size error",1),Ose=zt.DOMSTRING_SIZE_ERR=(St[2]="DOMString size error",2),vr=zt.HIERARCHY_REQUEST_ERR=(St[3]="Hierarchy request error",3),Pse=zt.WRONG_DOCUMENT_ERR=(St[4]="Wrong document",4),fA=zt.INVALID_CHARACTER_ERR=(St[5]="Invalid character",5),Rse=zt.NO_DATA_ALLOWED_ERR=(St[6]="No data allowed",6),Lse=zt.NO_MODIFICATION_ALLOWED_ERR=(St[7]="No modification allowed",7),AA=zt.NOT_FOUND_ERR=(St[8]="Not found",8),kse=zt.NOT_SUPPORTED_ERR=(St[9]="Not supported",9),pA=zt.INUSE_ATTRIBUTE_ERR=(St[10]="Attribute in use",10),Cn=zt.INVALID_STATE_ERR=(St[11]="Invalid state",11),$se=zt.SYNTAX_ERR=(St[12]="Syntax error",12),xse=zt.INVALID_MODIFICATION_ERR=(St[13]="Invalid modification",13),Fse=zt.NAMESPACE_ERR=(St[14]="Invalid namespace",14),Mse=zt.INVALID_ACCESS_ERR=(St[15]="Invalid access",15);function pe(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,St[e]),this.message=St[e],Error.captureStackTrace&&Error.captureStackTrace(this,pe);return r.code=e,t&&(this.message=this.message+": "+t),r}pe.prototype=Error.prototype;Rl(zt,pe);function Ai(){}Ai.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++)_h(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 Ha(e,t){this._node=e,this._refresh=t,vh(this)}function vh(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(xA(e,"length",r.length),!e.$$length||r.length<e.$$length)for(var n=r.length;n in e;n++)Object.prototype.hasOwnProperty.call(e,n)&&delete e[n];Rl(r,e),e._inc=t}}Ha.prototype.item=function(e){return vh(this),this[e]||null};wr(Ha,Ai);function Kc(){this._nameIndex=Object.create(null)}function SA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function J4(e,t){e._nameIndex[t.nodeName]=t}function NA(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function mA(e,t,r,n){if(n?(t[SA(t,n)]=r,NA(t,n)):t[t.length++]=r,J4(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&DA(i,e,n),Y4(i,e,r))}}function hA(e,t,r){var n=SA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,NA(t,r),e){var o=e.ownerDocument;o&&(DA(o,e,r),r.ownerElement=null)}}else throw new pe(AA,new Error(e.tagName+"@"+r))}Kc.prototype={length:0,item:Ai.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 pe(pA);var r=this._nameIndex[e.nodeName];return mA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new pe(pA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),mA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return hA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return hA(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 _A(){}_A.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ll;if(n.implementation=this,n.childNodes=new Ai,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 Zc;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 Yc(this,e,t)},replaceChild:function(e,t){Yc(this,e,t,OA),t&&this.removeChild(t)},removeChild:function(e){return IA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return $A(this.ownerDocument||this,this,e)},normalize:function(){At(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Il&&t.nodeType===Il){for(var n=[],i=r;i!==null&&i.nodeType===Il;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Xc(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 TA(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Rl(Cr,De);Rl(Cr,De.prototype);function Jc(e,t){return At(e,null,{enter:function(r){return t(r)?At.STOP:!0}})===At.STOP}function At(e,t,r){for(var n=[{node:e,context:t,phase:At.ENTER}];n.length>0;){var i=n.pop();if(i.phase===At.ENTER){var o=r.enter(i.node,i.context);if(o===At.STOP)return At.STOP;if(n.push({node:i.node,context:o,phase:At.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:At.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}At.STOP=Symbol("walkDOM.STOP");At.ENTER=0;At.EXIT=1;function Ll(){this.ownerDocument=this}function Y4(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ol.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function DA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ol.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Xc(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 IA(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,Xc(e.ownerDocument,e),t}function Q4(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function X4(e){return e&&(zn(e)||wh(e)||Si(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Si(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function wh(e){return e&&e.nodeType===De.TEXT_NODE}function gA(e,t){var r=e.childNodes||[];if(Wn(r,zn)||Si(t))return!1;var n=Wn(r,Si);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function yA(e,t){var r=e.childNodes||[];function n(o){return zn(o)&&o!==t}if(Wn(r,n))return!1;var i=Wn(r,Si);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Z4(e,t,r){if(!Q4(e))throw new pe(vr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new pe(AA,"child not in parent");if(!X4(t)||Si(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new pe(vr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function eG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!gA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!gA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){if(Wn(n,Si))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element");if(!r&&a)throw new pe(vr,"Doctype can not be appended since element is present")}}function OA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!yA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!yA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){let l=function(u){return Si(u)&&u!==r};var s=l;if(Wn(n,l))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element")}}function Yc(e,t,r,n){Z4(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||eG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ei){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Pl(o,l)}while(o!==a&&(o=o.nextSibling));return Xc(e.ownerDocument||e,e),t.nodeType==Ei&&(t.firstChild=t.lastChild=null),t}function Pl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Zr&&e.attributes)for(var r=0;r<e.attributes.length;r++){var n=e.attributes.item(r);n&&(n.ownerDocument=t)}for(var i=e.firstChild;i;)Pl(i,t),i=i.nextSibling}}function tG(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,Xc(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Pl(t,r),t}Ll.prototype={nodeName:"#document",nodeType:CA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ei){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Yc(this,e,t),Pl(e,this),this.documentElement===null&&e.nodeType===Zr&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),IA(this,e)},replaceChild:function(e,t){Yc(this,e,t,OA),Pl(e,this),t&&this.removeChild(t),zn(e)&&(this.documentElement=e)},importNode:function(e,t){return rG(this,e,t)},getElementById:function(e){var t=null;return Jc(this.documentElement,function(r){if(r.nodeType==Zr&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=dA(e);return new Ha(this,function(r){var n=[];return t.length>0&&Jc(r.documentElement,function(i){if(i!==r&&i.nodeType===Zr){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=dA(o);a=t.every(j4(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Go;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ai;var r=t.attributes=new Kc;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new ed;return e.ownerDocument=this,e.childNodes=new Ai,e},createTextNode:function(e){var t=new Ch;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Eh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new pe(fA,'data contains "]]>"');var t=new Ah;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Nh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Qc;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!za.test(e))throw new pe(fA,'not a valid xml name "'+e+'"');var t=new Sh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Go,n=t.split(":"),i=r.attributes=new Kc;return r.childNodes=new Ai,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 Qc,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}};wr(Ll,De);function Go(){this._nsMap={}}Go.prototype={nodeType:Zr,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===Ei?this.insertBefore(e,null):tG(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 Ha(this,function(t){var r=[];return Jc(t,function(n){n!==t&&n.nodeType==Zr&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ha(this,function(r){var n=[];return Jc(r,function(i){i!==r&&i.nodeType===Zr&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ll.prototype.getElementsByTagName=Go.prototype.getElementsByTagName;Ll.prototype.getElementsByTagNameNS=Go.prototype.getElementsByTagNameNS;wr(Go,De);function Qc(){}Qc.prototype.nodeType=ja;wr(Qc,De);function kl(){}kl.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(St[vr])},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}};wr(kl,De);function Ch(){}Ch.prototype={nodeName:"#text",nodeType:Il,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}};wr(Ch,kl);function Eh(){}Eh.prototype={nodeName:"#comment",nodeType:bh};wr(Eh,kl);function Ah(){}Ah.prototype={nodeName:"#cdata-section",nodeType:vA};wr(Ah,kl);function Zc(){}Zc.prototype.nodeType=EA;wr(Zc,De);function PA(){}PA.prototype.nodeType=K4;wr(PA,De);function RA(){}RA.prototype.nodeType=H4;wr(RA,De);function Sh(){}Sh.prototype.nodeType=wA;wr(Sh,De);function ed(){}ed.prototype.nodeName="#document-fragment";ed.prototype.nodeType=Ei;wr(ed,De);function Nh(){}Nh.prototype.nodeType=yh;wr(Nh,De);function LA(){}LA.prototype.serializeToString=function(e,t,r,n){return kA.call(e,t,r,n)};De.prototype.toString=kA;function kA(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 _h(this,i,e,t,l,n),i.join("")}function bA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ol.XML||i===Ol.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function Hc(e,t,r,n){if(n&&!za.test(t))throw new pe(Cn,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,TA),'"')}function _h(e,t,r,n,i,o){i||(i=[]),At(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 Zr:var c=a.attributes,d=c.length,f=a.tagName;u=Ol.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&&!za.test(m))throw new pe(Cn,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),E=0;E<d;E++){var S=c.item(E);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var E=0;E<d;E++){var S=c.item(E);if(bA(S,u,w)){var P=S.prefix||"",L=S.namespaceURI;Hc(t,P?"xmlns:"+P:"xmlns",L,o),w.push({prefix:P,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):Hc(t,I.name,I.value,o))}if(f===m&&bA(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;Hc(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var O=a.firstChild;if(O||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;O;)O.data?t.push(O.data):_h(O,t,u,n,w.slice(),o),O=O.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case CA:case Ei:return{ns:l.slice(),isHTML:u,tag:null};case ja:return Hc(t,a.name,a.value,o),null;case Il:return t.push(a.data.replace(/[<&>]/g,TA)),null;case vA:if(o&&a.data.indexOf("]]>")!==-1)throw new pe(Cn,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case bh:if(o&&a.data.indexOf("-->")!==-1)throw new pe(Cn,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case EA:if(o){if(!za.test(a.name))throw new pe(Cn,'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 pe(Cn,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new pe(Cn,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new pe(Cn,'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 Re=a.internalSubset;Re&&t.push(" [",Re,"]"),t.push(">")}return null;case yh:if(o){if(!za.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new pe(Cn,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new pe(Cn,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case wA:if(o&&!za.test(a.nodeName))throw new pe(Cn,'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 rG(e,t,r){var n;return At(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 $A(e,t,r){var n;return At(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 Ai),a.ownerDocument=e;var u=r;switch(a.nodeType){case Zr:var c=i.attributes,d=a.attributes=new Kc,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode($A(e,c.item(m),!0));break;case ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function xA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ha.prototype,"length",{get:function(){return vh(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===Zr||this.nodeType===Ei){var e=[];return At(this,null,{enter:function(t){if(t.nodeType===Zr||t.nodeType===Ei)return!0;if(t.nodeType===yh||t.nodeType===bh)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Zr:case Ei: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}}}),xA=function(e,t,r){e["$$"+t]=r})}catch{}Ni.DocumentType=Zc;Ni.DOMException=pe;Ni.DOMImplementation=_A;Ni.Element=Go;Ni.Node=De;Ni.NodeList=Ai;Ni.walkDOM=At;Ni.XMLSerializer=LA});var MA=v($l=>{"use strict";var FA=Wa().freeze;$l.XML_ENTITIES=FA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});$l.HTML_ENTITIES=FA({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"});$l.entityMap=$l.HTML_ENTITIES});var GA=v(Ih=>{var Ml=Wa().NAMESPACE,Dh=Wa().tagNamePattern,Ka=0,ro=1,Ja=2,xl=3,Ya=4,Qa=5,Fl=6,td=7;function Xa(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Xa)}Xa.prototype=new Error;Xa.prototype.name=Xa.name;function qA(){}qA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),sG(t,t={}),nG(e,t,r,n,this.errorHandler),n.endDocument()}};function nG(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var He=55296+(de>>10),bn=56320+(de&1023);return String.fromCharCode(He,bn)}else return String.fromCharCode(de)}function a(de){var He=de.slice(1,-1);return Object.hasOwnProperty.call(r,He)?r[He]:He.charAt(0)==="#"?o(parseInt(He.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var He=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(He,0,de-h),h=de}}function l(de,He){for(;de>=c&&(He=d.exec(e));)u=He.index,c=u+He[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),E=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+S.tagName),K=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),K=g+1+E.length):/[ \t\n\r]/.test(E)&&Dh.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var P=S.localNSMap,L=S.tagName==E,I=L||S.tagName&&S.tagName.toLowerCase()==E.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,E),P)for(var D in P)Object.prototype.hasOwnProperty.call(P,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=uG(e,g,n);break;case"!":f&&l(g),K=lG(e,g,n,i);break;default:f&&l(g);var O=new VA,x=m[m.length-1].currentNSMap,K=iG(e,g,O,x,a,i),Re=O.length;if(!O.closed&&aG(e,K,O.tagName,p)&&(O.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Re){for(var qt=UA(f,{}),ge=0;ge<Re;ge++){var je=O[ge];l(je.offset),je.locator=UA(f,{})}n.locator=qt,BA(O,n,x)&&m.push(O),n.locator=f}else BA(O,n,x)&&m.push(O);Ml.isHTML(O.uri)&&!O.closed?K=oG(e,K,O.tagName,a,n):K++}}catch(de){if(de instanceof Xa)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function UA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function iG(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=Ka;;){var d=e.charAt(u);if(c===Ka&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ro)s=e.slice(t,u),c=xl;else if(c===Ja)c=xl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===xl||c===ro)if(c===ro&&(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=Qa;else throw new Error("attribute value no end '"+d+"' match");else if(c==Ya)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Qa;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:c=td,r.closed=!0;case Ya:case ro:break;case Ja:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Ka&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:break;case Ya:case ro:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ja:c===Ja&&(l=s),c==Ya?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Ml.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case xl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Ka:r.setTagName(e.slice(t,u)),c=Fl;break;case ro:s=e.slice(t,u),c=Ja;break;case Ya:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case Qa:c=Fl;break}else switch(c){case Ja:var f=r.tagName;(!Ml.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ro;break;case Qa:o.warning('attribute space is required"'+s+'"!!');case Fl:c=ro,t=u;break;case xl:c=Ya,t=u;break;case td:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function BA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Ml.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Ml.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var 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 oG(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 aG(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 sG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function lG(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=cG(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 uG(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 VA(){this.attributeNames={}}VA.prototype={setTagName:function(e){if(!Dh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Dh.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 cG(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}Ih.XMLReader=qA;Ih.ParseError=Xa});var YA=v(nd=>{var dG=Wa(),fG=Th(),WA=MA(),HA=GA(),pG=fG.DOMImplementation,zA=dG.NAMESPACE,mG=HA.ParseError,hG=HA.XMLReader;function KA(e){return e.replace(/\r[\n\u0085]/g,``).replace(/[\r\u0085\u2028]/g,`-`)}function VS(e){this.options=e||{locator:{}}}VS.prototype.parseFromString=function(e,t){var r=this.options,n=new J8,i=r.domBuilder||new au,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?FS.HTML_ENTITIES:FS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=Y8(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=MS.HTML),s.xml=s.xml||MS.XML;var c=r.normalizeLineEndings||qS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function Y8(e,t,r){if(!e){if(t instanceof au)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+fg(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function au(){this.cdata=!1}function gs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}au.prototype={startDocument:function(){this.doc=new H8().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;Td(this,o),this.currentElement=o,this.locator&&gs(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&gs(n.getLocator(s),u),u.value=u.nodeValue=l,o.setAttributeNode(u)}},endElement:function(e,t,r){var n=this.currentElement,i=n.tagName;this.currentElement=n.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var r=this.doc.createProcessingInstruction(e,t);this.locator&&gs(this.locator,r),Td(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=US.apply(this,arguments),e){if(this.cdata)var n=this.doc.createCDATASection(e);else var n=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(n):/^\s*$/.test(e)&&this.doc.appendChild(n),this.locator&&gs(this.locator,n)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,r){e=US.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&gs(this.locator,n),Td(this,n)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,r){var n=this.doc.implementation;if(n&&n.createDocumentType){var i=n.createDocumentType(e,t,r);this.locator&&gs(this.locator,i),Td(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,fg(this.locator))},error:function(e){console.error("[xmldom error] "+e,fg(this.locator))},fatalError:function(e){throw new K8(e,this.locator)}};function fg(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function US(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){au.prototype[e]=function(){return null}});function Td(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Dd.__DOMHandler=au;Dd.normalizeLineEndings=qS;Dd.DOMParser=VS});var ys=v(Id=>{var WS=ug();Id.DOMImplementation=WS.DOMImplementation;Id.XMLSerializer=WS.XMLSerializer;Id.DOMParser=GS().DOMParser});var jS={};nn(jS,{CCFControlConstants:()=>zS,CCFPropertyConstants:()=>mg,CustomControlDataType:()=>F,CustomControlNames:()=>Mi,DefaultControlNameKeys:()=>pg,ICCModeEnum:()=>go,JSONParametersConstants:()=>hg,LookUpType:()=>Od,ManifestXMLConstants:()=>Xt,NumberType:()=>Pd,Usage:()=>ia});var zS,mg,hg,Xt,F,pg,Mi,go,ia,Od,Pd,oa=k(()=>{"use strict";zS={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},mg={Name:"Name",Value:"Value",Type:"Type",TypeGroup:"TypeGroup",Usage:"Usage",Static:"Static",Primary:"Primary",Columns:"Columns",EnableViewPicker:"EnableViewPicker",EntityName:"EntityName",FilteredViewIds:"FilteredViewIds",ReferencingName:"ReferencingName",RelationshipName:"RelationshipName",RelationshipType:"RelationshipType",TargetEntityType:"TargetEntityType",ViewId:"ViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DefaultViewId:"DefaultViewId",BindAttribute:"BindAttribute",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",QuickForms:"QuickForms",EntityNameKey:"EntityNameKey",CardFormType:"Form.Card",CardFormId:"CardFormId",Hidden:"Hidden",Required:"Required",DefaultValue:"DefaultValue"},hg={GroupDefinition:"GroupDefinition"},Xt={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(F||(F={}));(function(e){e.BooleanType="CC_FlipLabel_Name",e.DateTimeType="CC_TextBox_Name",e.DecimalType="CC_TextBox_Name",e.DoubleType="CC_TextBox_Name",e.IntegerType="CC_TextBox_Name",e.LookupType="CC_TextBox_Name",e.MemoType="CC_TextArea_Name",e.MoneyType="CC_TextBox_Name",e.OptionSetType="CC_OptionSet_Name",e.StringType="CC_TextBox_Name",e.GridType="CC_ReadOnlyGrid_Name",e.UnboundCustomControlType="CC_UnboundCustomControl_Name"})(pg||(pg={}));(function(e){e.ArcKnobControl="MscrmControls.Knob.ArcKnobControl",e.CardFeedNameControl="MscrmControls.CardFeedContainer.CardFeedContainer",e.CheckboxControl="MscrmControls.FieldControls.CheckboxControl",e.DateTimeControl="MscrmControls.FieldControls.DateTimeControl",e.DurationControl="MscrmControls.FieldControls.DurationControl",e.EditableGridControl="MscrmControls.Grid.GridControl",e.EmailEngagementActionsControl="MscrmControls.EmailEngagement.EmailEngagementActionsControl",e.FormComponent="MscrmControls.ModelForm.ModelFormControl",e.LanguageCodeControl="MscrmControls.FieldControls.LanguagePickerControl",e.LinearSliderControl="MscrmControls.Slider.LinearSliderControl",e.MultiSelectOptionSetControl="MscrmControls.MultiSelectPicklist.UpdMSPicklistControl",e.OptionSetControl="MscrmControls.OptionSet.OptionSetControl",e.PowerBIPCFControl="MscrmControls.PowerBIPCFControl",e.PredictiveScoringWidget="MscrmControls.Sales.PredictiveScoringWidget.PredictiveScoringWidget",e.ReadonlyGrid="MscrmControls.Grid.ReadOnlyGrid",e.SimilarCasesGrid="MscrmControls.Containers.SimilarCasesGridControl",e.StarRatingControl="MscrmControls.Rating.StarRatingControl",e.TimeZoneControl="MscrmControls.FieldControls.TimeZonePickListControl",e.ModelFormControl="MscrmControls.ModelForm.ModelFormControl",e.AutoCompleteControl="MscrmControls.AutoComplete.AutoCompleteControl",e.CanvasAppControl="MscrmControls.Canvas.CanvasControl",e.PowerAppsOneGrid="Microsoft.PowerApps.PowerAppsOneGrid"})(Mi||(Mi={}));(function(e){e[e.Read=0]="Read",e[e.Edit=1]="Edit",e[e.Both=2]="Both",e[e.Container=3]="Container",e[e.Unknown=4]="Unknown"})(go||(go={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ia||(ia={}));Od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],Pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var bs,dr,su=k(()=>{"use strict";bs=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,r){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(r),!0)}upsert(t,r){this.update(t,r)||this.add(t,r)}sortedUpsert(t,r){if(!this.update(t,r)){let n=0;for(;n<this.keys.length&&this.keys[n]<t;)n++;this.keys.splice(n,0,t),this.values.splice(n,0,r)}}clear(){this.keys=[],this.values=[]}containsKey(t){return this.keys.indexOf(t)!==-1}containsValue(t){return this.values.indexOf(t)!==-1}count(){return this.keys.length}getValue(t){let r=this.keys.indexOf(t);return r!==-1?this.values[r]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let r=this.keys.indexOf(t);return r!==-1?(this.keys.splice(r,1),this.values.splice(r,1),!0):!1}update(t,r){let n=this.keys.indexOf(t);return n!==-1?(this.values[n]=r,!0):!1}},dr=class{data={};add(t,r){return this.containsKey(t)?!1:(this.data[t]=r,!0)}upsert(t,r){this.data[t]=r}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let r in this.data)if(this.data[r]===t)return!0;return!1}count(){return Object.keys(this.data).length}getValue(t){return this.containsKey(t)?this.data[t]:!1}getKeys(){return Object.keys(this.data)}getValues(){let t=[];for(let r in this.data)t.push(this.data[r]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,r){return this.containsKey(t)?(this.data[t]=r,!0):!1}getInternalObject(){return this.data}}});var HS={};nn(HS,{AttributeDataSourceType:()=>lu,AttributeDataSourceTypeMask:()=>Rd,AttributePrecisionSource:()=>uu,EntityAttributeDataSourceType:()=>aa,EntityAttributeDateTimeBehavior:()=>bg,EntityAttributeImeMode:()=>yg,EntityAttributePrecisionSource:()=>vg,EntityAttributeRequiredLevel:()=>yo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ui,EntityResxKeyLookUp:()=>Ld,SourceTypeMask:()=>gg});var Ui,$,W,yo,aa,gg,lu,Rd,yg,bg,vg,uu,Ld,vs=k(()=>{"use strict";su();Ui=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return Ld.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})($||($={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));yo=class extends Ui{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},aa=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?lu.Persistent:parseInt(lu[this.name])}},gg=class e extends Ui{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(Rd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(lu||(lu={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(Rd||(Rd={}));yg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},bg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},vg=class e extends Ui{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?uu.Currency:parseInt(uu[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(uu||(uu={}));Ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new bs;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(aa.Persistent,"SystemCustomization.String.Source.persistent"),t.add(aa.Calculated,"SystemCustomization.String.Source.calculated"),t.add(aa.Rollup,"SystemCustomization.String.Source.rollup"),t.add(aa.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var cu=v(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.parsePcfManifest=ut.parseControlElement=ut.parseManifestRoot=ut.firstLevel=ut.attr=ut.elementChildren=ut.manifestTypesForColumn=ut.DEFAULT_TYPE_GROUPS=void 0;var Q8=ys(),H=(oa(),zr(jS)),ve=(vs(),zr(HS));ut.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var X8="Phone";function Z8(e,t,r){switch(e){case ve.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case ve.EntityAttributeType.Customer:case ve.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case ve.EntityAttributeType.DateTime:return t===ve.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case ve.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case ve.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case ve.EntityAttributeType.File:return[H.CustomControlDataType.File];case ve.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case ve.EntityAttributeType.WholeNumber:return t===ve.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===ve.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===ve.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case ve.EntityAttributeType.LookupType:case ve.EntityAttributeType.Lookup:return t===ve.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case ve.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case ve.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case ve.EntityAttributeType.Owner:case ve.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case ve.EntityAttributeType.PartyList:case ve.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case ve.EntityAttributeType.Status:case ve.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case ve.EntityAttributeType.SingleLineofText:switch(t){case ve.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case ve.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case ve.EntityAttributeTypeFormat.Text:return r===X8?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case ve.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case ve.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case ve.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case ve.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ut.manifestTypesForColumn=Z8;function wg(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}ut.elementChildren=wg;function On(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ut.attr=On;function ei(e,...t){return wg(e).filter(r=>t.includes(r.tagName))}ut.firstLevel=ei;function e9(e){let t=new Map;for(let r of ei(e,"type-group"))t.set(String(On(r,"name")),ei(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function t9(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(wg(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var r9={input:"input",bound:"bound",output:"output"};function n9(e,t,r){let n=On(e,"usage"),i=n!==null&&r9[n]||"input",o=On(e,"default-value"),a=ei(e,"value").map(m=>{let p={name:On(m,"name"),value:String(m.textContent),isDefault:On(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=On(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ut.DEFAULT_TYPE_GROUPS,s)?ut.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=On(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:On(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:On(e,"required")==="true",hidden:On(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function KS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new Q8.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}ut.parseManifestRoot=KS;function JS(e){let t=ei(KS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ut.parseControlElement=JS;function i9(e){let t=JS(e),r=e9(t),n=ei(t,"data-set"),i=ei(t,"property"),o=ei(t,"groups"),a=[],s=!1;for(let u of i){let c=n9(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>ei(u,"group").some(c=>ei(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:t9(t)}}ut.parsePcfManifest=i9});var QS=v(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.readPcfColumn=Cs.readControlManifest=void 0;var ws=oe(),o9=cu();function Cg(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function a9(e,t){var r;let n="/customcontrols"+(0,ws.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ws.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Cg(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,o9.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}Cs.readControlManifest=a9;var s9=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function YS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function l9(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ws.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ws.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ws.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Cg(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=YS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=s9.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ws.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Cg(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=YS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}Cs.readPcfColumn=l9});var sa=v(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});kd.DEFAULT_LCID=void 0;kd.DEFAULT_LCID=1033});var ct=v(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.assignMissingIds=ti.pointerTouchesValueMap=ti.isValueMapKey=ti.newId=void 0;var u9=Xa();function XS(){return globalThis.crypto.randomUUID().toLowerCase()}ti.newId=XS;function c9(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ag=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function d9(e){return Ag.has(e)}ti.isValueMapKey=d9;function f9(e){return u9.JsonPointer.parse(e).some(t=>Ag.has(t))}ti.pointerTouchesValueMap=f9;function p9(e){return Eg(e),e}ti.assignMissingIds=p9;function Eg(e){if(Array.isArray(e)){e.forEach(t=>Eg(t));return}if(c9(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=XS());for(let t of Object.keys(e))t==="id"||Ag.has(t)||Eg(e[t])}}});var Es=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.sendChangeSet=Or.partResponse=Or.postChangeSet=Or.parseChangeSetParts=Or.parseChangeSetStatuses=Or.renderChangeSet=void 0;var bo=Q(),Sg=fe(),ZS=ct(),du=oe();function Ng(e,t){let r=`batch_${(0,ZS.newId)()}`,n=`changeset_${(0,ZS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new bo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,du.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,du.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,du.assertNoControlChars)(m,"batch operation header name"),(0,du.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new bo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,du.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r+`)}function JA(e){this.options=e||{locator:{}}}JA.prototype.parseFromString=function(e,t){var r=this.options,n=new hG,i=r.domBuilder||new Ul,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?WA.HTML_ENTITIES:WA.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=gG(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=zA.HTML),s.xml=s.xml||zA.XML;var c=r.normalizeLineEndings||KA;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function gG(e,t,r){if(!e){if(t instanceof Ul)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Oh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Ul(){this.cdata=!1}function Za(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Ul.prototype={startDocument:function(){this.doc=new pG().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;rd(this,o),this.currentElement=o,this.locator&&Za(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&&Za(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&&Za(this.locator,r),rd(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=jA.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&&Za(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=jA.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Za(this.locator,n),rd(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&&Za(this.locator,i),rd(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Oh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Oh(this.locator))},fatalError:function(e){throw new mG(e,this.locator)}};function Oh(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function jA(e,t,r){return typeof e=="string"?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){Ul.prototype[e]=function(){return null}});function rd(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}nd.__DOMHandler=Ul;nd.normalizeLineEndings=KA;nd.DOMParser=JA});var es=v(id=>{var QA=Th();id.DOMImplementation=QA.DOMImplementation;id.XMLSerializer=QA.XMLSerializer;id.DOMParser=YA().DOMParser});var ZA={};Hr(ZA,{CCFControlConstants:()=>XA,CCFPropertyConstants:()=>Rh,CustomControlDataType:()=>F,CustomControlNames:()=>_i,DefaultControlNameKeys:()=>Ph,ICCModeEnum:()=>no,JSONParametersConstants:()=>Lh,LookUpType:()=>od,ManifestXMLConstants:()=>jt,NumberType:()=>ad,Usage:()=>Wo});var XA,Rh,Lh,jt,F,Ph,_i,no,Wo,od,ad,zo=k(()=>{"use strict";XA={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"},Rh={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"},Lh={GroupDefinition:"GroupDefinition"},jt={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"})(Ph||(Ph={}));(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"})(_i||(_i={}));(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"})(no||(no={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(Wo||(Wo={}));od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],ad=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var ts,nr,Bl=k(()=>{"use strict";ts=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}},nr=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 eS={};Hr(eS,{AttributeDataSourceType:()=>ql,AttributeDataSourceTypeMask:()=>sd,AttributePrecisionSource:()=>Vl,EntityAttributeDataSourceType:()=>jo,EntityAttributeDateTimeBehavior:()=>xh,EntityAttributeImeMode:()=>$h,EntityAttributePrecisionSource:()=>Fh,EntityAttributeRequiredLevel:()=>io,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ti,EntityResxKeyLookUp:()=>ld,SourceTypeMask:()=>kh});var Ti,$,W,io,jo,kh,ql,sd,$h,xh,Fh,Vl,ld,rs=k(()=>{"use strict";Bl();Ti=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return ld.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})($||($={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(W||(W={}));io=class extends Ti{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},jo=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Persistent(){return"Persistent"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}GetValue(){return this.name===e.None?ql.Persistent:parseInt(ql[this.name])}},kh=class e extends Ti{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(sd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ql||(ql={}));(function(e){e[e.Undefined=0]="Undefined",e[e.Simple=1]="Simple",e[e.Related=2]="Related",e[e.Logical=4]="Logical",e[e.Calculated=8]="Calculated",e[e.Rollup=16]="Rollup",e[e.Invalid=32]="Invalid"})(sd||(sd={}));$h=class e extends Ti{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"}},xh=class e extends Ti{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"}},Fh=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?Vl.Currency:parseInt(Vl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Vl||(Vl={}));ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new ts;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(jo.Persistent,"SystemCustomization.String.Source.persistent"),t.add(jo.Calculated,"SystemCustomization.String.Source.calculated"),t.add(jo.Rollup,"SystemCustomization.String.Source.rollup"),t.add(jo.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Uh=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.parsePcfManifest=it.parseControlElement=it.parseManifestRoot=it.firstLevel=it.attr=it.elementChildren=it.manifestTypesForColumn=it.DEFAULT_TYPE_GROUPS=void 0;var yG=es(),H=(zo(),Fr(ZA)),we=(rs(),Fr(eS));it.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 bG="Phone";function vG(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===bG?[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}}it.manifestTypesForColumn=vG;function Mh(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}it.elementChildren=Mh;function En(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}it.attr=En;function jn(e,...t){return Mh(e).filter(r=>t.includes(r.tagName))}it.firstLevel=jn;function wG(e){let t=new Map;for(let r of jn(e,"type-group"))t.set(String(En(r,"name")),jn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function CG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(Mh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var EG={input:"input",bound:"bound",output:"output"};function AG(e,t,r){let n=En(e,"usage"),i=n!==null&&EG[n]||"input",o=En(e,"default-value"),a=jn(e,"value").map(m=>{let p={name:En(m,"name"),value:String(m.textContent),isDefault:En(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=En(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(it.DEFAULT_TYPE_GROUPS,s)?it.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=En(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:En(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:En(e,"required")==="true",hidden:En(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function tS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new yG.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}it.parseManifestRoot=tS;function rS(e){let t=jn(tS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}it.parseControlElement=rS;function SG(e){let t=rS(e),r=wG(t),n=jn(t,"data-set"),i=jn(t,"property"),o=jn(t,"groups"),a=[],s=!1;for(let u of i){let c=AG(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=>jn(u,"group").some(c=>jn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:CG(t)}}it.parsePcfManifest=SG});var iS=v(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.readPcfColumn=is.readControlManifest=void 0;var ns=se(),NG=Uh();function Bh(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 _G(e,t){var r;let n="/customcontrols"+(0,ns.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ns.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Bh(`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,NG.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}is.readControlManifest=_G;var TG=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 nS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function DG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ns.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ns.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ns.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:Bh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=nS(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=TG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ns.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Bh(`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=nS(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))}}}is.readPcfColumn=DG});var Ho=v(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.DEFAULT_LCID=void 0;ud.DEFAULT_LCID=1033});var dt=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.assignMissingIds=Hn.pointerTouchesValueMap=Hn.isValueMapKey=Hn.newId=void 0;var IG=$a();function oS(){return globalThis.crypto.randomUUID().toLowerCase()}Hn.newId=oS;function OG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Vh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function PG(e){return Vh.has(e)}Hn.isValueMapKey=PG;function RG(e){return IG.JsonPointer.parse(e).some(t=>Vh.has(t))}Hn.pointerTouchesValueMap=RG;function LG(e){return qh(e),e}Hn.assignMissingIds=LG;function qh(e){if(Array.isArray(e)){e.forEach(t=>qh(t));return}if(OG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=oS());for(let t of Object.keys(e))t==="id"||Vh.has(t)||qh(e[t])}}});var Wl=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.sendChangeSet=Er.partResponse=Er.postChangeSet=Er.parseChangeSetParts=Er.parseChangeSetStatuses=Er.renderChangeSet=void 0;var oo=Q(),Gh=ye(),aS=dt(),Gl=se();function Wh(e,t){let r=`batch_${(0,aS.newId)()}`,n=`changeset_${(0,aS.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 oo.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 oo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Gl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Gl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,Gl.assertNoControlChars)(m,"batch operation header name"),(0,Gl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new oo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Gl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([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}}Or.renderChangeSet=Ng;function eN(e,t){var r;return(r=_g(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Or.parseChangeSetStatuses=eN;function _g(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r+`),batchId:r,contentIds:i}}Er.renderChangeSet=Wh;function sS(e,t){var r;return(r=zh(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Er.parseChangeSetStatuses=sS;function zh(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}Or.parseChangeSetParts=_g;async function m9(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Sg.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=eN(a.body,o);if(l===void 0)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new bo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Or.postChangeSet=m9;function tN(e){let t=e.text.replace(/\r\n/g,`+`);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}Er.parseChangeSetParts=zh;async function kG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Gh.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new oo.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=sS(a.body,o);if(l===void 0)throw new oo.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 oo.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 oo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Er.postChangeSet=kG;function lS(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}}Or.partResponse=tN;async function h9(e,t,r){let{body:n,batchId:i,contentIds:o}=Ng(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=_g(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Sg.ensureSuccess)(tN(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Sg.ensureSuccess)(a,s),!l||l.length!==t.length)throw new bo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Or.sendChangeSet=h9});var $d=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var Se=fe(),te=oe(),ri=sa(),he=Q(),g9=Es(),y9={String:"Microsoft.Dynamics.CRM.StringAttributeMetadata",Memo:"Microsoft.Dynamics.CRM.MemoAttributeMetadata",Integer:"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",Decimal:"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",Money:"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",Boolean:"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",DateTime:"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",Picklist:"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",Lookup:"Microsoft.Dynamics.CRM.LookupAttributeMetadata"};function tt(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:b9(e,t)}}var rN=65535;function b9(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new he.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new he.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>rN)throw new he.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${rN})`);if(i.has(s))throw new he.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new he.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function sN(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new he.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=sN;function fu(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var nN=["None","ApplicationRequired","Recommended"];function Ig(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function iN(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function pu(e){let t=(0,Se.readCreatedId)(e,"MetadataId");if(!t)throw new he.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function v9(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,L,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new he.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new he.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:tt((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:tt((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(O=t.dateFormat)!==null&&O!==void 0?O:"DateAndTime"};case"choice":return oN(t,r,!1);case"multiChoice":return oN(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((P=t.autoNumberFormat)===null||P===void 0)&&P.trim()))throw new he.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new he.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function oN(e,t,r){let i={"@odata.type":r?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:r?"Virtual":"Picklist",AttributeTypeName:{Value:r?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new he.InvalidArgumentError(`choice column '${e.schemaName}' requires at least one option (or a globalChoiceMetadataId)`);return i.OptionSet={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",IsGlobal:!1,OptionSetType:"Picklist",Options:e.options.map(o=>({Value:o.value,Label:tt(o.label,t)}))},i}var Tg=new WeakMap;async function w9(e,t){var r,n;let i=(r=Tg.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new he.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Tg.get(e);return l||(l=new Map,Tg.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=w9;async function C9(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!nN.includes(b))throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${nN.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new he.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let C=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,S=Ig(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:fu(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:tt((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&dN(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:tt(t.displayName,C),DisplayCollectionName:tt((a=t.pluralName)!==null&&a!==void 0?a:sN(t.displayName),C),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ur=>Og(ur,C))]};t.description&&(I.Description=tt(t.description,C));let D="/EntityDefinitions",P=(0,Se.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=pu(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Le=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),lr=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${O.toLowerCase()}', { required: '${b}' }).`:"",Ut;try{Ut=await lN(e,K,Le,lr)}catch(ur){throw w?(0,he.attachCause)(new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ur instanceof Error?ur.message:String(ur)}).${Ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),ur):ur}if(!Ut)throw new he.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Le} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${Ge}`);let de=Ut.body,Ke={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(Ke.primaryColumnRequired=await E9(e,t.schemaName,Ke,b,Le,lr)),Ke}ie.createTable=C9;async function lN(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,Se.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function E9(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await lN(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new he.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await hN(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,he.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function Og(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...v9(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:fu((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:tt(e.displayName,i)};return e.description&&(o.Description=tt(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),uN(o,e),o}function uN(e,t){t.isValidForCreate!==void 0&&(e.IsValidForCreate=t.isValidForCreate),t.isValidForUpdate!==void 0&&(e.IsValidForUpdate=t.isValidForUpdate),t.isValidForRead!==void 0&&(e.IsValidForRead=t.isValidForRead)}async function A9(e,t,r){var n;let i=Og(r,(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,Se.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:pu(a)};if(r.visualization&&r.visualization!=="None")try{await mN(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new he.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw(0,he.attachCause)(u,l),u}return s}ie.createColumn=A9;var As="/controlconfigurations",cN="CustomRenderersConfiguration",Dg={RadialDial:"c3d4e5f6-a7b8-9012-cdef-345678901234",LineChart:"a1b2c3d4-e5f6-7890-abcd-ef1234567890",HeatMap:"e7f8a9b0-c1d2-4e3f-5a6b-7c8d9e0f1a2b",StarRating:"b5e4c3d2-f1a0-4e2b-8a7c-9d3f5c1e6b04"};function dN(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new he.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${r.schemaName}') is not supported \u2014 the attribute metadata and its control-configuration row are separate writes. Create the column, then call setColumnVisualization; or use the single-column createColumn.`)}function fN(e){return JSON.stringify({type:Dg[e]})}function S9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Dg).find(i=>Dg[i]===r);return n??"None"}async function pN(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${As}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,Se.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function N9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,Se.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new he.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function mN(e,t,r,n,i){let o={name:cN,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:fN(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.post(As,o),e.apiUrl(As))}async function _9(e,t,r){var n;let i=await pN(e,t,r);return S9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=_9;async function T9(e,t,r,n){let o=(await pN(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await N9(e,t,r);if(a){let u=`${As}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:cN,metadatajson:fN(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,Se.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await mN(e,t,r,l,n);for(let u of s){let c=`${As}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,Se.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=T9;async function D9(e,t,r){if(r.length===0)return;if(dN(r,"createColumns"),!e.supportsAtomicBatch)throw new he.InvalidArgumentError(`createColumns writes ${r.length} columns on '${t}' as ONE atomic change set, which needs a verbatim request body. Implement HttpClient.postRaw, or call createColumn per column and accept that a failure can leave the table partly extended.`);let n=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`;await(0,g9.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Og(i,(o=i.languageCode)!==null&&o!==void 0?o:ri.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=D9;async function I9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,l=Ig(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,s),RequiredLevel:fu((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,Se.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=I9;async function O9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:tt(r.label,l),StateCode:(i=r.stateCode)!==null&&i!==void 0?i:0};typeof r.value=="number"&&(u.Value=r.value),r.color&&(u.Color=r.color);let c=(0,Se.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=O9;async function P9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new he.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Ig(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:fu((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:tt((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new he.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,Se.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:pu(d),lookupLogicalName:u}}ie.createRelationship=P9;async function R9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=R9;async function hN(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:ri.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,Se.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=y9[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new he.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,Se.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=tt(n.displayName,a)),n.description!==void 0&&(p.Description=tt(n.description,a)),n.required!==void 0&&(p.RequiredLevel=fu(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new he.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);if(n.integerFormat!==void 0&&c.AttributeType!=="Integer")throw new he.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),uN(p,n);let h=`${s}(${f})`;(0,Se.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=hN;async function L9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=L9;async function k9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new he.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=k9;async function aN(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,Se.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function $9(e,t){var r;let n=t.name.toLowerCase(),i=await aN(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:ri.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:tt(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:tt(l.label,o)}))};t.description&&(a.Description=tt(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,Se.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:pu(l)}}catch(l){let u;try{u=await aN(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=$9;async function x9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,Se.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=x9;async function F9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:tt(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,Se.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:pu(s)}}ie.createAlternateKey=F9;async function M9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new he.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,Se.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=M9;async function U9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:ri.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,Se.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new he.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.normalizeGuid)(l,"MetadataId");for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",r.displayName!==void 0&&(s.DisplayName=tt(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=tt(r.pluralName,i)),r.description!==void 0&&(s.Description=tt(r.description,i)),r.auditEnabled!==void 0&&iN(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&iN(s,"IsDuplicateDetectionEnabled",r.duplicateDetectionEnabled),r.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=r.changeTrackingEnabled),r.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=r.quickCreateEnabled),r.iconVectorName!==void 0&&(s.IconVectorName=r.iconVectorName),r.iconSmallName!==void 0&&(s.IconSmallName=r.iconSmallName),r.iconMediumName!==void 0&&(s.IconMediumName=r.iconMediumName),r.iconLargeName!==void 0&&(s.IconLargeName=r.iconLargeName);let c=`/EntityDefinitions(${u})`;(0,Se.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=U9});var wo=v(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.rebuildRaw=Pr.assembleChildren=Pr.spliceChildren=Pr.mergeAttrs=Pr.rawFromNode=Pr.emptyBag=void 0;var vo=Q(),gN=1e6,Fd=512;function B9(){return{a:[],c:[]}}Pr.emptyBag=B9;function yN(e,t=0){if(t>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>yN(r,t+1))}}Pr.rawFromNode=yN;function q9(e,t,r=[]){let n=new Map;for(let[s,l]of t)n.set(s,l);let i=new Set(r.filter(s=>!n.has(s))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Pr.mergeAttrs=q9;function xd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>gN)throw new vo.InvalidArgumentError(`Bag child index must be an integer in [0, ${gN}] (got ${String(l)})`);if(r.has(l))throw new vo.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Pr.spliceChildren=xd;function V9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:xd(e.w.c,t)};return xd(e.c,[r])}return xd(e.c,t)}Pr.assembleChildren=V9;function bN(e,t,r,n=0){if(n>Fd)throw new vo.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${Fd}`);G9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,bN(o,t,i,n+1));return i}Pr.rebuildRaw=bN;function G9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new vo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new vo.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(r.a)||!Array.isArray(r.c))throw new vo.InvalidArgumentError(`Malformed hybrid node '${r.n}': 'a' and 'c' must be arrays`);for(let n of r.a)if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||typeof n[1]!="string")throw new vo.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Co=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.installDomShim=void 0;var vN=ys(),wN=!1,W9={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12};function z9(){if(wN)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=vN.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=vN.XMLSerializer),typeof e.Node>"u"&&(e.Node=W9),wN=!0}Md.installDomShim=z9});var Eo=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.projectElementBag=rt.serializeNode=rt.domEngine=rt.nodeLikeFromDom=rt.parseXmlRoot=rt.EMPTY_FORM_SENTINEL=rt.TEXT_SENTINEL=void 0;var j9=wo(),Ss=Q(),H9=Co();rt.TEXT_SENTINEL="#text";rt.EMPTY_FORM_SENTINEL="#empty";var Bd=new WeakSet;function K9(e,t){(0,H9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new Ss.InvalidArgumentError("XML source has no root element (empty or malformed input)");return J9(r),Q9(n),Z9(i),e5(i),n5(i,r),i}rt.parseXmlRoot=K9;function J9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw EN(3)}var Y9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function Q9(e){var t;for(let r of Y9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new Ss.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var X9=new Set([1,3]);function Z9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!X9.has(o.nodeType))throw new Ss.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function e5(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw EN(a.nodeType)}}function EN(e){return new Ss.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function t5(e){let t=[],r=/<([^>]*)>/g;for(let n=r.exec(e);n!==null;n=r.exec(e)){let i=n[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function r5(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function AN(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function n5(e,t){let r=t5(t),n=r5(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];AN(a)||Bd.add(a)}}function Pg(e){let t=e.nodeType===3;return{getNodeName:()=>t?rt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:rt.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return Bd.has(e)&&!AN(e)&&i.push({key:rt.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Pg(o))}return r}}}rt.nodeLikeFromDom=Pg;function i5(e){return{make:t=>t===rt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===rt.EMPTY_FORM_SENTINEL?Bd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}rt.domEngine=i5;function SN(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=31&&r!==9&&r!==10&&r!==13||r===65534||r===65535)throw Ud(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ud(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ud(r)}}function Ud(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Ss.InvalidArgumentError(`Value contains U+${t}, a character not permitted in XML 1.0 (control char / lone surrogate / non-character); it cannot be serialized losslessly`)}function o5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function a5(e){return SN(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function s5(e){return NN(e,0)}rt.serializeNode=s5;var CN=512;function NN(e,t){var r;if(t>CN)throw new Ss.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${CN}`);if(e.nodeType===3)return a5((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+o5(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return Bd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=NN(l,t+1);return i+"</"+n.tagName+">"}function l5(e){let t=Pg(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,j9.rawFromNode)(r)}))}}rt.projectElementBag=l5});var cn=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.rejectUnknownKeys=Zt.childObjects=Zt.optionalGuidId=Zt.optionalEnum=Zt.eachObject=Zt.issue=Zt.isJsonObject=void 0;function _N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Zt.isJsonObject=_N;function Ns(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Zt.issue=Ns;function TN(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{_N(o)?i.push({node:o,index:a}):n.push(Ns(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Zt.eachObject=TN;function u5(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(Ns(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Zt.optionalEnum=u5;var c5=/^(?:\{[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}\}|[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})$/;function d5(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!c5.test(o)&&i.push(Ns(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Zt.optionalGuidId=d5;function f5(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?TN(o,a,n,i):(i.push(Ns(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Zt.childObjects=f5;function p5(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(Ns(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Zt.rejectUnknownKeys=p5});var zd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var m5=ys(),h5=Xa(),Rg=ct(),dn=cn();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var g5=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Rr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),g5.test(t)?t:""}B.normGuid=Rr;function Ao(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=Ao;function hu(e){return Ee(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=hu;function Ee(e){return Array.isArray(e)?e:[]}function Mg(e,t){let r=Ee(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function ON(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function PN(e){return Pn(e).map(t=>t.cell)}B.typedCells=PN;function Pn(e){let t=[];return Ee(e?.tabs).forEach((r,n)=>{Ee(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ee(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ee(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ee(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Pn;function Bi(e){return Pe(e)?Rr(Mg(e.bag,"uniqueid")):""}B.controlUniqueId=Bi;function y5(e){let t=new Set;for(let{cell:r}of Pn(e)){let n=ca(r.control)?Bi(r.control):"";n&&t.add(n)}return t}function b5(e){let t=new Map;for(let{cell:r}of Pn(e)){let n=Pe(r.control)?Bi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function v5(e){return e!==void 0&&e.genPage===void 0&&(qg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Wd(e))}function Lg(e,t){if(Pe(e)){t(e);for(let r of Ee(e.c))Lg(r,t)}}function la(e,t){var r;if(Pe(e)){for(let n of Ee(e.c))Lg(n?.node,t);for(let n of Ee((r=e.w)===null||r===void 0?void 0:r.c))Lg(n?.node,t)}}function Vd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Rr(Ao(i,"uniqueid")))};return la(e?.bag,n),Ee(e?.tabs).forEach(i=>{Pe(i)&&(la(i.bag,n),Ee(i.columns).forEach(o=>{Pe(o)&&(la(o.bag,n),Ee(o.sections).forEach(a=>{Pe(a)&&(la(a.bag,n),Ee(a.rows).forEach(s=>{Pe(s)&&(la(s.bag,n),Ee(s.cells).forEach(l=>{Pe(l)&&(la(l.bag,n),Pe(l.control)&&(r(Bi(l.control)),la(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Vd;function _s(e){return Ee(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=_s;function ua(e,t){var r;let n=Rr(t);if(n)return Ee((r=_s(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Rr(Ao(i,"forControl"))===n)}B.descriptionFor=ua;function gu(e){return Ee(e.c).filter(RN)}B.pageEntries=gu;function RN(e){return e?.n==="customControl"&&Ao(e,"name")===B.GENPAGE_CONTROL_NAME}function kg(e,t){let r=Ee(e.c).find(n=>n?.n==="parameters");return Ee(r?.c).find(n=>n?.n===t)}B.entryParameter=kg;function $g(e){return Ao(e,"static")==="true"}B.isStaticParameter=$g;function yu(e){let t=gu(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=kg(t[i],"RefId");if(!o||!$g(o))return{kind:"unsupported"};let a=Rr(hu(o));if(!a)return{kind:"unsupported"};let s=kg(t[i],"PageInput");if(s&&!$g(s))return{kind:"unsupported"};let l=s?hu(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=yu;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ug(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=Ug;function Bg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Bg;function qg(e){return ON(e.classId!==void 0?e.classId:Mg(e.bag,"classid"))}B.effectiveClassId=qg;function Wd(e){return!e.fieldName}B.isUnbound=Wd;function Vg(e,t){if(Bg(e)!=="Main"||!Wd(t)||qg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Bi(t),n=r?ua(e.bag,r):void 0;return n!==void 0&&yu(n).kind==="projectable"}B.isRecognizedEmbed=Vg;function w5(e){for(let t of PN(e)){let r=t.control;if(!r||!Vg(e,r))continue;let n=yu(ua(e.bag,Bi(r)));if(n.kind!=="projectable")continue;let i=Ug(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=w5;var C5=new Set(["pageId","inputData"]);function mu(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function E5(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new m5.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=Rr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=mu(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?mu(l):[]){let d=Rr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of mu(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=mu(f).find(g=>g.nodeName==="parameters"),p=m?mu(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Rr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=E5;function qd(e){return{n:`<${e}`,a:[],c:[]}}function xg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[qd(t)]}}function Fg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function A5(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[xg("RefId",t),...r===void 0?[]:[xg("PageInput",Fg(r))]]}]}))}}function Gd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>Gd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&Gd(e[n],t[n]))}return e===t}function S5(e,t,r){let n=Ee(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Rr(hu(i))!==t&&(i.c=[qd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?hu(a):void 0;if(Gd(Ug(s),r))return;if(r!==void 0){a?a.c=[qd(Fg(r,s))]:n.c.push(xg("PageInput",Fg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[qd(JSON.stringify(l))]}function Gg(e){let t=Ee(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=Gg;function N5(e,t){var r;let n=e.bag,i=_s(n);if(i&&t){let o=Vd(t),a=Vd(e),s=y5(t),l=b5(e),u=Ee(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&gu(d).length>0?Rr(Ao(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&v5(l.get(f))&&Gd(d,ua(t.bag,f))){let m=Ee(d.c).filter(p=>!RN(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of Pn(e)){let a=o.control;if(!ca(a)||!Pe(a.genPage))continue;let s=Rr(a.genPage.pageId),l=a.genPage.inputData,u=Bi(a);if(!u){if(bu(a)!==void 0)continue;u=Wg(a)}let c=ua(n,u);if(c){for(let m of gu(c))S5(m,s,l);continue}i||(i={i:Gg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Mg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(A5(f,s,l))}}B.reconcileEmbedDescriptions=N5;function _5(e,t){let r=_s(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Pn(e).some(({cell:a})=>ca(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=_s(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ee(o.bag.c),o.bag.c.push({i:Gg(e.bag),node:a}))}for(let{cell:a}of Pn(o))ca(a.control)&&(LN(a.control),kN(a));return o}B.commitEmbedState=_5;function T5(e){if(Pn(e).some(({cell:r})=>ca(r.control)))return!0;let t=_s(e.bag);return Ee(t?.node.c).some(r=>r?.n==="controlDescription"&&gu(r).length>0)}B.mayCommitEmbedState=T5;function LN(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=LN;function kN(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=kN;function ca(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=ca;function DN(e){return ca(e.control)&&(!e.control.id||!e.id||bu(e.control)===void 0)}function bu(e){let t=Ee(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=bu;function D5(e){if(!Pn(e).some(({cell:r})=>DN(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Pn(t)){if(!DN(r))continue;let n=r.control;n.id||(n.id=(0,Rg.newId)()),r.id||(r.id=(0,Rg.newId)()),bu(n)===void 0&&Wg(n)}return t}B.mintEmbedIdentity=D5;function Wg(e){let t=(0,Rg.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ee(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ee(e.bag.c),t}B.setUniqueId=Wg;function IN(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function I5(e){let t=Ee(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=Ao(r,"name"))!==null&&n!==void 0?n:Ao(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function O5(e){let t=[],r;for(let{cell:n,pointer:i}of Pn(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){P5(e,o,a,t);continue}r=r??Vd(e),R5(e,o,a,r,t)}return t}B.genPageEmbedIssues=O5;function P5(e,t,r,n){if(!Vg(e,t))return;let i=yu(ua(e.bag,Bi(t)));n.push((0,dn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function R5(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,dn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${IN(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Rr(s.pageId))&&i.push((0,dn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,dn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${IN(s.inputData)}`));for(let m of Object.keys(s))C5.has(m)||i.push((0,dn.issue)(h5.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Wd(t)||i.push((0,dn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&ON(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,dn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=Bg(e);l!=="Main"&&i.push((0,dn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=bu(t);u!==void 0&&!Rr(u)&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Bi(t);if(!c)return;let d=ua(e.bag,c),f=d?yu(d):void 0;d&&f?.kind==="none"?i.push((0,dn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${I5(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,dn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,dn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var jg=v(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.findMissingGenPages=So.GENPAGE_LOOKUP_CHUNK=void 0;var L5=Tt(),zg=oe();So.GENPAGE_LOOKUP_CHUNK=50;async function k5(e,t,r){let n=[...new Set(t.map(o=>(0,zg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=So.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+So.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,zg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,L5.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,zg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}So.findMissingGenPages=k5});var vu=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertSystemFormKind=Pt.readSystemFormType=Pt.decodeCode=Pt.assertSystemFormRecordKind=Pt.describeSystemFormType=Pt.systemFormKindOf=Pt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var xN=Q(),$5=fe(),$N=oe();Pt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var x5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},F5={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function jd(e){return Number.isInteger(e)?x5[e]:void 0}Pt.systemFormKindOf=jd;function FN(e){var t;return Number.isFinite(e)?`a ${(t=F5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Pt.describeSystemFormType=FN;function MN(e,t,r,n){let i=FN(r),o=jd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function M5(e,t,r,n){let i=Hg(e?.type);if(jd(i)!==r)throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,i,n));return i}Pt.assertSystemFormRecordKind=M5;function Hg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Pt.decodeCode=Hg;async function U5(e,t){return await UN(e,t,!1)}Pt.readSystemFormType=U5;async function B5(e,t){return UN(e,t,!0)}async function UN(e,t,r){var n;let o=`/systemforms(${(0,$N.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$N.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,$5.ensureSuccess)(a,e.apiUrl(o)),Hg((n=a.body)===null||n===void 0?void 0:n.type)}async function q5(e,t,r){let n=await B5(e,t);if(!(n===void 0||jd(n)===r))throw new xN.SdkError(Pt.SYSTEMFORM_KIND_MISMATCH_CODE,MN(t,r,n,"delete"))}Pt.assertSystemFormKind=q5});var Jg=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.patchSystemForm=Yr.assertSystemFormContentUnchanged=Yr.readSystemFormRowEtag=Yr.unpublishedSystemFormPath=Yr.FORM_TYPE_IMMUTABLE_CODE=void 0;var fn=fe(),V5=oe(),Hd=Q(),No=vu();Yr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function Kg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,V5.odataQuery)([["$select",t]])}Yr.unpublishedSystemFormPath=Kg;function BN(e,t){return(0,fn.readRowEtag)(e,"systemforms","formid",t)}Yr.readSystemFormRowEtag=BN;async function qN(e,t,r,n,i){(0,fn.requireEtag)(i,r,t);let o=(0,fn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,No.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,fn.readEtag)(o);if(s===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Yr.assertSystemFormContentUnchanged=qN;async function G5(e,t,r,n,i,o){(0,fn.requireEtag)(i,r,t);let a=await BN(e,t);if(a===null)throw new Hd.SdkError(fn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await qN(e,t,r,Kg(t,"formid,type"),i);if(n.type!==void 0&&(0,No.decodeCode)(n.type)!==s)throw new Hd.SdkError(Yr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,No.describeSystemFormType)(s)} to ${(0,No.describeSystemFormType)((0,No.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,fn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,fn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),W5(e,t,r,o)}Yr.patchSystemForm=G5;async function W5(e,t,r,n){let i;try{let o=Kg(t,n.select),a=(0,fn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,fn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,No.decodeCode)(s?.type),m=(0,No.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,No.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var e0=v(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.getFormSecurityRoles=qt.setFormSecurityRoles=qt.formApi=qt.readPrimaryCreateRefusal=qt.FORM_GENPAGE_TARGET_UNVERIFIABLE=qt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var z5=Tt(),Rt=fe(),pn=oe(),da=Q(),Yg=Eo(),GN=zd(),j5=jg(),Qg=Jg(),wu=vu();qt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";qt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var WN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",H5={select:WN,required:["name","type","objecttypecode"]},K5="formid,name,type,objecttypecode",J5=2,Y5={Main:J5,QuickView:6,QuickCreate:7,Card:11},zN=new WeakMap;function Q5(e){return typeof e=="object"&&e!==null?zN.get(e):void 0}qt.readPrimaryCreateRefusal=Q5;qt.formApi={async get(e,t){let r=(0,pn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select",WN]]),i=(0,Rt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,wu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Rt.readEtag)(i)}},async list(e,t){var r;let n=!((r=t?.formTypes)===null||r===void 0)&&r.length?t.formTypes:["Main"],i=[...new Set(n.map(u=>Y5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,pn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,pn.odataQuery)([["$select",K5],["$filter",a.join(" and ")]])}`;return(await(0,z5.collectPages)(e,s,"listArtifacts('form')")).map(u=>{var c,d;return{type:"form",id:(c=u.formid)!==null&&c!==void 0?c:"",name:(d=u.name)!==null&&d!==void 0?d:"",entityLogicalName:u.objecttypecode,isDirty:!1}})},async create(e,t,r){let n=VN(t);n!==void 0&&await jN(e,Zg(n,"payload"),[]);let i=(0,Rt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Rt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Rt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Rt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&zN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Rt.resolveCreatedId)(l,"formid","form",r),etag:(0,Rt.readEtag)(l)}},async update(e,t,r,n){let i=(0,pn.normalizeGuid)(t,"id"),o=VN(r);return o!==void 0&&await Z5(e,i,o,n),(0,Qg.patchSystemForm)(e,i,"form",r,n,H5)},readContentThenToken(e,t){return qt.formApi.get(e,t)},async delete(e,t){let r=(0,pn.normalizeGuid)(t,"id");return await(0,wu.assertSystemFormKind)(e,r,"form"),(0,Rt.deleteRecord)(e,"systemforms",r)}};var Xg="DisplayConditions";async function X5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new da.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,pn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Rt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,wu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Rt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new da.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Yg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new da.InvalidArgumentError(`form '${s}' produced no owner document`);let h=HN(m,Xg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new da.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(Xg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",P),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,pn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Yg.serializeNode)(m);await(0,Qg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Qg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,Rt.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Rt.requireEtag)(O,"form",s)}}),e.apiUrl(L))}qt.setFormSecurityRoles=X5;function VN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(GN.GENPAGE_CONTROL_NAME)?t:void 0}function Zg(e,t){try{return(0,GN.activeEmbedBindings)(e)}catch(r){throw new da.SdkError(qt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function jN(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,j5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new da.SdkError(qt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function Z5(e,t,r,n){var i;(0,Rt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Rt.readEtag)(a);if(s===null||s!==n)throw new da.SdkError(Rt.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?Zg(l,"server"):[];await jN(e,Zg(r,"payload"),u)}function HN(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName===t)return i}}async function eW(e,t){var r,n;let i=(0,pn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Rt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,wu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Yg.parseXmlRoot)(s,"<form/>"),u=HN(l,Xg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.replace(/[{}]/g,"").toLowerCase())}}let m=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...m!==null&&m!==""?{order:Number(m)}:{}}}qt.getFormSecurityRoles=eW});var Jd=v(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.deleteSolution=ye.getDeploymentSettingsTemplate=ye.importSolution=ye.exportSolution=ye.removeSolutionComponent=ye.addSolutionComponent=ye.setSolutionVersion=ye.createSolution=ye.createPublisher=ye.getSolution=ye.fetchSolutionComponents=ye.resolveGenPageComponentType=ye.SolutionComponentType=void 0;var tW=Tt(),Gt=fe(),mr=oe(),rW=ct(),er=Q();ye.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var nW=[ye.SolutionComponentType.SavedQuery,ye.SolutionComponentType.Workflow,ye.SolutionComponentType.SavedQueryVisualization,ye.SolutionComponentType.SystemForm,ye.SolutionComponentType.AppModule],KN="uxagentproject",JN=new WeakMap;async function t_(e){var t;let r=JN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${KN}')${(0,mr.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Gt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new er.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${KN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return JN.set(e,o),o}ye.resolveGenPageComponentType=t_;var YN=1,QN=0;async function iW(e,t){let r=(0,mr.normalizeGuid)(t,"solutionId"),n=await t_(e),o=[YN,...nW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,mr.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,tW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===YN){let f=c.rootcomponentbehavior;(f===QN||f===String(QN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}ye.fetchSolutionComponents=iW;function oW(e){let t=e.length===38&&e.startsWith("{")&&e.endsWith("}")?e.slice(1,-1):e;return/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(t)}async function aW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new er.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=oW(f)?`solutionid eq ${(0,mr.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,mr.odataLiteral)(f)}'`,p=`/solutions${(0,mr.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Gt.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new er.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new er.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new er.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,mr.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,mr.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}ye.getSolution=aW;async function sW(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,Gt.ensureSuccess)(await(0,Gt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Gt.readCreatedId)(i,"publisherid");if(!o)throw new er.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}ye.createPublisher=sW;async function lW(e,t){var r;let n=(0,mr.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(r=t.version)!==null&&r!==void 0?r:"1.0.0.0","[email protected]":`/publishers(${n})`};t.description&&(i.description=t.description);let o=(0,Gt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Gt.readCreatedId)(o,"solutionid");if(!a)throw new er.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}ye.createSolution=lW;async function uW(e,t,r){let i=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}ye.setSolutionVersion=uW;async function cW(e,t){var r;let i={ComponentId:(0,mr.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(r=t.addRequiredComponents)!==null&&r!==void 0?r:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,Gt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}ye.addSolutionComponent=cW;async function dW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,mr.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Gt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}ye.removeSolutionComponent=dW;async function fW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Gt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new er.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}ye.exportSolution=fW;async function pW(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new er.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:SW(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,mr.normalizeGuid)(t.importJobId,"importJobId"):(0,rW.newId)()};if(!n)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await r_(e,t.base64,Cu,o),{parameters:s,applied:l}=NW(a,n);return i.ComponentParameters=s,(0,Gt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,er.withCleanupWarnings)(a,o)}}ye.importSolution=pW;var Cu="importSolution",XN="getDeploymentSettingsTemplate";async function mW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new er.InvalidArgumentError(`${XN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await r_(e,n,XN,i),a=Kd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Kd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,er.withCleanupWarnings)(o,i)}}ye.getDeploymentSettingsTemplate=mW;function Kd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function r_(e,t,r,n){var i;let a=(i=(0,Gt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return gW(a,r)}finally{await hW(e,fa(a)?a.StageSolutionUploadId:void 0,n)}}async function hW(e,t,r){let n;try{n=(0,mr.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${Vt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Gt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function pr(e,t){return new er.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===Cu?" Nothing was imported.":""}`)}function ZN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>fa(r)&&typeof r.Message=="string"?r.Message:Vt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function gW(e,t){if(!fa(e))throw pr(t,`it holds no StageSolutionResults (${Vt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new er.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${Vt(r)}). Missing dependencies: ${ZN(e.MissingDependencies)}. Validation: ${ZN(e.SolutionValidationResults)}.${t===Cu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw pr(t,`StageSolutionStatus is ${Vt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw pr(t,`SolutionComponentsDetails is not a list (${Vt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!fa(l))throw pr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw pr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=yW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw pr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw pr(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw pr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=bW(f.get("type"),`${c}.type`,t),b=vW(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw pr(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function yW(e,t,r){if(!fa(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw pr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw pr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw pr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw pr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function bW(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw pr(r,`${t} is not a whole number (${Vt(e,40)})`)}}function vW(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw pr(r,`${t} is not true or false (${Vt(e,40)})`)}}var wW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),CW=["Workflows","CanvasApps","CopilotAgents"],EW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),AW=new Set(["LogicalName","ConnectionId","ConnectorId"]);function fr(e,t){return new er.InvalidArgumentError(`${Cu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function SW(e){let t="deploymentSettings";if(!fa(e))throw fr(t,`must be an object \u2014 the settings file, parsed (it was ${Vt(e,40)})`);for(let l of Object.keys(e))if(!wW.has(l))throw fr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of CW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw fr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw fr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw fr(`${t}.${l}`,`must be a list (it was ${Vt(u,40)})`);return u.map((c,d)=>{if(!fa(c))throw fr(`${t}.${l}[${d}]`,`must be an object (it was ${Vt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw fr(c,`must be a non-empty string (it was ${Vt(d,40)})`);if(d.trim()!==d)throw fr(c,`must not begin or end with whitespace (it was ${Vt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw fr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!EW.has(f))throw fr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw fr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${Vt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!AW.has(m))throw fr(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw fr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${Vt(f,40)})`);if(f.trim()!==f)throw fr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${Vt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw fr(`${c}.ConnectorId`,`must be a string (it was ${Vt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function e_(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function NW(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=e_(Kd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=e_(Kd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new er.InvalidArgumentError(`${Cu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function _W(e,t){let n=`/solutions(${(0,mr.normalizeGuid)(t,"solutionId")})`;(0,Gt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ye.deleteSolution=_W});var l_=v(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.recoverFormCreate=yt.solutionMembershipProblem=yt.formWriteMismatches=yt.validateExistingForm=yt.formExistsAtId=yt.isFormRecordAt=yt.MAIN_FORM_TYPE=void 0;var Ts=oe(),n_=Tt(),i_=Jd();yt.MAIN_FORM_TYPE=2;function Yd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qd(e){return e instanceof Error?e.message:String(e)}function t0(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,Ts.normalizeGuid)(e,"a GUID")===(0,Ts.normalizeGuid)(t,"a GUID")}catch{return!1}}function r0(e,t){return Yd(e)&&t0(e.formid,t)}yt.isFormRecordAt=r0;async function TW(e,t){try{return r0((await e()).raw,t)}catch{return!1}}yt.formExistsAtId=TW;function o_(e,t){let r=e.raw;if(!Yd(r))return{problem:"it is not a record"};if(!r0(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==yt.MAIN_FORM_TYPE)return{problem:`its type is not ${yt.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}yt.validateExistingForm=o_;function a_(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}yt.formWriteMismatches=a_;async function s_(e,t){let r=e.solutionName;if(r)try{let n=await(0,n_.collectPages)(e,`/solutions${(0,Ts.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,Ts.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Yd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,Ts.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,n_.collectPages)(e,`/solutioncomponents${(0,Ts.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${i_.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Yd(l)&&l.componenttype===i_.SolutionComponentType.SystemForm&&t0(l.objectid,t)&&t0(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Qd(n)})`}}yt.solutionMembershipProblem=s_;async function DW(e){try{return await IW(e)}catch(t){return{refused:`the recovery could not be completed (${Qd(t)})`}}}yt.recoverFormCreate=DW;async function IW(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==yt.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Qd(f)})`}}let l=o_(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=a_(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Qd(f)})`}}let d=await s_(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Zd=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.disassociateRecords=Ye.associateRecords=Ye.createRecordsBulk=Ye.upsertRecord=Ye.queryAllRecords=Ye.queryRecords=Ye.getRecord=Ye.deleteRecord=Ye.updateRecord=Ye.createRecord=void 0;var n0=Tt(),Rn=fe(),tr=oe(),Ds=Q(),ni=$d();function Xd(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function OW(e,t,r){let i=`/${await(0,ni.resolveEntitySetName)(e,t)}`,o=(0,Rn.ensureSuccess)(await e.post(i,Xd(r)),e.apiUrl(i)),a=(0,Rn.readCreatedId)(o,`${t}id`);if(!a)throw new Ds.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ye.createRecord=OW;async function PW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),a=`/${await(0,ni.resolveEntitySetName)(e,t)}(${i})`;(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a))}Ye.updateRecord=PW;async function RW(e,t,r){let n=(0,tr.normalizeGuid)(r,"id"),o=`/${await(0,ni.resolveEntitySetName)(e,t)}(${n})`;(0,Rn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ye.deleteRecord=RW;async function LW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=await(0,ni.resolveEntitySetName)(e,t),a=(0,tr.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Rn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new Ds.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,n0.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ye.getRecord=LW;function kW(e){return e?.fetchXml?(0,tr.odataQuery)([["fetchXml",e.fetchXml]]):(0,tr.odataQuery)([["$select",e?.select&&e.select.length>0?e.select.join(","):void 0],["$filter",e?.filter],["$orderby",e?.orderBy],["$expand",e?.expand],["$top",e?.top]])}async function u_(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new Ds.InvalidArgumentError("queryRecords: `paginate` cannot be combined with `top` \u2014 Dataverse honors $top as a hard cap and omits @odata.nextLink, so the result would be silently capped at one page.");if(r.fetchXml)throw new Ds.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let o=`/${await(0,ni.resolveEntitySetName)(e,t)}${kW(r)}`;if(r?.paginate)return(0,n0.collectPages)(e,o,"queryRecords");let a=(0,Rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ds.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,n0.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ye.queryRecords=u_;async function $W(e,t,r){return u_(e,t,{...r,paginate:!0})}Ye.queryAllRecords=$W;function xW(e){if("id"in e)return`(${(0,tr.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,tr.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,tr.assertODataName)(e.key,"alternate key name")}=${t})`}async function FW(e,t,r,n){let i=xW(r),a=`/${await(0,ni.resolveEntitySetName)(e,t)}${i}`,s=(0,Rn.ensureSuccess)(await e.patch(a,Xd(n)),e.apiUrl(a)),l=s.status===201,u=(0,Rn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,tr.normalizeGuid)(r.id,"id"):""),created:l}}Ye.upsertRecord=FW;async function MW(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,ni.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Xd(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Rn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new Ds.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ye.createRecordsBulk=MW;async function UW(e,t,r,n){let i=(0,tr.normalizeGuid)(r,"id"),o=(0,tr.normalizeGuid)(n.targetId,"targetId"),a=await(0,ni.resolveEntitySetName)(e,t),s=await(0,ni.resolveEntitySetName)(e,n.targetEntity),l=(0,tr.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Rn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ye.associateRecords=UW;async function BW(e,t,r,n,i){let o=(0,tr.normalizeGuid)(r,"id"),a=(0,tr.normalizeGuid)(i,"targetId"),s=await(0,ni.resolveEntitySetName)(e,t),l=(0,tr.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Rn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ye.disassociateRecords=BW});var pa=v(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.base64ToUtf8=mn.base64ToBytes=mn.bytesToBase64=mn.utf8ToBase64=mn.utf8ToBytes=void 0;var i0=32768,Lr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Eu(){return globalThis}function c_(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function qW(e){let t="";for(let r=0;r<e.length;r+=i0)t+=String.fromCharCode(...e.subarray(r,r+i0));return t}function VW(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Lr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function GW(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Lr[i>>18&63]+Lr[i>>12&63]+Lr[i>>6&63]+Lr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Lr[i>>18&63]}${Lr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Lr[i>>18&63],a=Lr[i>>12&63],s=Lr[i>>6&63];t+=`${o}${a}${s}=`}return t}function WW(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Lr.indexOf(e[o])<<18|Lr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Lr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Lr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function zW(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):c_(e)}mn.utf8ToBytes=zW;function jW(e){let t=Eu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return d_(r?new r().encode(e):c_(e))}mn.utf8ToBase64=jW;function d_(e){let t=Eu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(qW(e)):GW(e)}mn.bytesToBase64=d_;function f_(e){let t=Eu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=VW(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return WW(r)}mn.base64ToBytes=f_;function HW(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=i0&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function KW(e){let t=Eu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):HW(f_(e))}mn.base64ToUtf8=KW});var g_=v(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.deleteWebResource=ii.getWebResource=ii.updateWebResource=ii.createWebResource=void 0;var JW=jr(),Au=fe(),ef=oe(),YW=pa(),p_=Q(),QW={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function m_(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,YW.utf8ToBase64)(e.content)}async function h_(e,t){return(0,JW.publishWebResourceById)(e,t)}async function XW(e,t){var r;let n=m_(t);if(n===void 0)throw new p_.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(r=t.displayName)!==null&&r!==void 0?r:t.name,webresourcetype:QW[t.type],content:n};t.description&&(i.description=t.description);let o=(0,Au.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,Au.readCreatedId)(o,"webresourceid");if(!a)throw new p_.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await h_(e,a),{id:a,name:t.name}}ii.createWebResource=XW;async function ZW(e,t,r){let n=(0,ef.normalizeGuid)(t,"id"),i={},o=m_(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,Au.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await h_(e,n)}ii.updateWebResource=ZW;async function e6(e,t){var r;let i=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})${(0,ef.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,Au.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}ii.getWebResource=e6;async function t6(e,t){let n=`/webresourceset(${(0,ef.normalizeGuid)(t,"id")})`;(0,Au.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ii.deleteWebResource=t6});var tf=v(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.applyAppSettings=Lt.setAppSetting=Lt.readAppSettings=Lt.resolveSettingDefinitions=Lt.APP_SETTING_UNSET=Lt.APP_SETTING_OFF=Lt.APP_SETTING_ON=Lt.HEADER_AND_NAVIGATION_REFRESH=void 0;var Is=fe(),qi=oe();Lt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Lt.APP_SETTING_ON="2";Lt.APP_SETTING_OFF="1";Lt.APP_SETTING_UNSET="0";function v_(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,qi.odataQuery)([["$select",e],["$filter",t]])}async function w_(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,qi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,Is.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}Lt.resolveSettingDefinitions=w_;async function r6(e,t){var r,n,i,o;let a=(0,qi.normalizeGuid)(t,"App id"),s=v_("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,Is.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,qi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,qi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,Is.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Lt.readAppSettings=r6;async function y_(e,t,r){var n,i,o;let a=v_("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Is.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function C_(e,t,r,n){let i=(0,qi.normalizeGuid)(t,"App id"),a=(await w_(e,[r])).get(r),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${r}' is not available in this environment: no settingdefinition row has that uniquename. The feature may be version-gated or its solution may not be installed.`);let l=(0,qi.normalizeGuid)(s,"Setting definition id"),u=await y_(e,i,l);if(u)return b_(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await y_(e,i,l)}catch{p=void 0}if(p)return b_(e,p,n);throw f&&(0,Is.ensureSuccess)(f,e.apiUrl(c)),m}Lt.setAppSetting=C_;async function b_(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,qi.normalizeGuid)(t.id,"App setting id")})`;return(0,Is.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function n6(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await C_(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Lt.applyAppSettings=n6});var nf=v(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.HEADER_NAV_BOOLEAN_RULE=void 0;rf.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var o0=v(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});af.asUint8Array=void 0;var i6=Object.getPrototypeOf(Uint8Array.prototype);function of(e){let t=Object.getOwnPropertyDescriptor(i6,e);if(!t?.get)throw new Error(`this JavaScript engine has no %TypedArray%.prototype getter for ${String(e)}`);return t.get}var o6=of(Symbol.toStringTag),a6=of("buffer"),s6=of("byteOffset"),l6=of("byteLength");function u6(e){if(o6.call(e)==="Uint8Array")return new Uint8Array(a6.call(e),s6.call(e),l6.call(e))}af.asUint8Array=u6});var I_=v(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.zipStored=Os.crc32=void 0;var c6=Q(),d6=pa(),f6=o0(),p6=67324752,m6=33639248,h6=101010256,sf=30,a0=46,g6=22,E_=10,y6=20,A_=2048,S_=0,N_=0,__=33,b6=65535,v6=65535,T_=4294967295,w6=3988292384,lf;function C6(){if(!lf){lf=new Uint32Array(256);for(let e=0;e<256;e+=1){let t=e;for(let r=0;r<8;r+=1)t=t&1?w6^t>>>1:t>>>1;lf[e]=t}}return lf}function D_(e){let t=C6(),r=4294967295;for(let n=0;n<e.length;n+=1)r=t[(r^e[n])&255]^r>>>8;return(r^4294967295)>>>0}Os.crc32=D_;function oi(e){return new c6.InvalidArgumentError(`zip: ${e}`)}function E6(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!1;t+=1}else if(r>=56320&&r<=57343)return!1}return!0}function A6(e){if(typeof e!="string"||e.length===0)throw oi("every entry needs a non-empty name.");if(e.includes("\\"))throw oi(`'${e}' contains a backslash; ZIP paths use '/'.`);if(/^[A-Za-z]:/.test(e))throw oi(`'${e}' starts with a drive letter; ZIP paths are relative.`);if(e.split("/").some(t=>t===""||t==="."||t===".."))throw oi(`'${e}' is not a relative path of named segments (no leading, trailing or doubled '/', no '.' or '..').`);if(!E6(e))throw oi(`'${e}' contains an unpaired surrogate, which has no UTF-8 form.`);return e}function S6(e,t=T_){if(e.length>b6)throw oi(`${e.length} entries is more than the 65,535 a ZIP can count without ZIP64.`);let r=Math.min(t,T_),n=new Set,i=[],o=g6;for(let f of e){let m=A6(f.name);if(n.has(m))throw oi(`'${m}' appears twice.`);n.add(m);let p=(0,f6.asUint8Array)(f.data);if(!p)throw oi(`the data for '${m}' must be a Uint8Array.`);let h=(0,d6.utf8ToBytes)(m);if(h.length>v6)throw oi(`a name of ${h.length} UTF-8 bytes is more than the 65,535 a header can record.`);o+=sf+a0+2*h.length+p.byteLength,i.push({nameBytes:h,data:p})}if(o>r)throw oi(`the archive would be ${o} bytes, more than the ${r} allowed.`);let a=new Uint8Array(o),s=new DataView(a.buffer),l=[],u=[],c=0;for(let{nameBytes:f,data:m}of i){let p=D_(m);l.push(c),u.push(p),s.setUint32(c,p6,!0),s.setUint16(c+4,E_,!0),s.setUint16(c+6,A_,!0),s.setUint16(c+8,S_,!0),s.setUint16(c+10,N_,!0),s.setUint16(c+12,__,!0),s.setUint32(c+14,p,!0),s.setUint32(c+18,m.byteLength,!0),s.setUint32(c+22,m.byteLength,!0),s.setUint16(c+26,f.length,!0),a.set(f,c+sf),a.set(m,c+sf+f.length),c+=sf+f.length+m.byteLength}let d=c;return i.forEach(({nameBytes:f,data:m},p)=>{s.setUint32(c,m6,!0),s.setUint16(c+4,y6,!0),s.setUint16(c+6,E_,!0),s.setUint16(c+8,A_,!0),s.setUint16(c+10,S_,!0),s.setUint16(c+12,N_,!0),s.setUint16(c+14,__,!0),s.setUint32(c+16,u[p],!0),s.setUint32(c+20,m.byteLength,!0),s.setUint32(c+24,m.byteLength,!0),s.setUint16(c+28,f.length,!0),s.setUint32(c+42,l[p],!0),a.set(f,c+a0),c+=a0+f.length}),s.setUint32(c,h6,!0),s.setUint16(c+8,i.length,!0),s.setUint16(c+10,i.length,!0),s.setUint32(c+12,c-d,!0),s.setUint32(c+16,d,!0),a}Os.zipStored=S6});var W_=v($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.pcfManifestsEquivalent=$e.buildPcfSolutionZip=$e.pcfContentTypesXml=$e.pcfCustomizationsXml=$e.pcfSolutionXml=$e.pcfWebResourceName=$e.pcfControlName=$e.checkPcfControlPackage=$e.unboundPrefixes=$e.PCF_WEB_RESOURCE_TYPES=void 0;var N6=Q(),Qr=cu(),uf=pa(),_6=o0(),T6=I_();$e.PCF_WEB_RESOURCE_TYPES={html:1,htm:1,css:2,js:3,xml:4,png:5,jpg:6,jpeg:6,gif:7,xsl:9,xslt:9,ico:10,svg:11,resx:12};var D6=["code","css","resx","img","html"],O_=/^[A-Za-z_][A-Za-z0-9_]*$/,I6=/^\d+\.\d+\.\d+$/,O6=/^[A-Za-z0-9_.-]+$/;function bt(e){return new N6.InvalidArgumentError(`registerPcfControl: ${e}`)}function x_(e){return(0,Qr.elementChildren)(e).filter(t=>t.localName==="control"&&!t.namespaceURI)}function F_(e){let t=[],r=n=>{n.prefix&&!n.namespaceURI&&t.push(`<${n.tagName}>`);for(let i=0;i<n.attributes.length;i+=1){let o=n.attributes.item(i);o.prefix&&!o.namespaceURI&&t.push(`${o.name}="\u2026" on <${n.tagName}>`)}(0,Qr.elementChildren)(n).forEach(r)};return r(e),t}$e.unboundPrefixes=F_;function s0(e){let t=(0,Qr.parseManifestRoot)(e),r=F_(t);if(r.length>0)throw new Error(`the manifest uses a prefix no namespace declaration binds: ${r.join(", ")}.`);if(t.localName!=="manifest")throw new Error(`the manifest's root element is <${t.tagName}>, not <manifest>.`);if(t.namespaceURI)throw new Error(`the manifest's root element is <manifest> in the namespace '${t.namespaceURI}', not in no namespace.`);let n=x_(t)[0];if(!n)throw new Error("the control manifest has no <control> element");return{root:t,control:n}}function P6(e){let t=e.split("/");if(!t.every(a=>O6.test(a)&&a!=="."&&a!==".."))throw bt(`the resource path '${e}' is not a web resource name: use letters, digits, '_', '.' and '-' in '/'-separated segments, with no '.' or '..' segment.`);let r=t[t.length-1],n=r.lastIndexOf("."),i=n>0?r.slice(n+1).toLowerCase():"",o=Object.prototype.hasOwnProperty.call($e.PCF_WEB_RESOURCE_TYPES,i)?$e.PCF_WEB_RESOURCE_TYPES[i]:void 0;if(o===void 0)throw bt(`the resource path '${e}' has no web resource type; the extensions are ${Object.keys($e.PCF_WEB_RESOURCE_TYPES).join(", ")}.`);return o}function R6(e){var t,r,n;if(typeof e!="object"||e===null)throw bt("the control package must be an object with a manifest and files.");let{manifest:i,files:o}=e;if(typeof i!="string"||i.length===0)throw bt("the manifest must be the built ControlManifest.xml, as a string.");if(typeof o!="object"||o===null||Array.isArray(o))throw bt("files must be an object mapping each resource path to its bytes.");let a,s;try{({root:a,control:s}=s0(i))}catch(b){throw bt(b.message)}if(x_(a).length!==1)throw bt("the manifest must hold exactly one <control>.");let l=(t=(0,Qr.attr)(s,"namespace"))!==null&&t!==void 0?t:"",u=(r=(0,Qr.attr)(s,"constructor"))!==null&&r!==void 0?r:"",c=(n=(0,Qr.attr)(s,"version"))!==null&&n!==void 0?n:"";if(!l.split(".").every(b=>O_.test(b)))throw bt(`the control's namespace '${l}' is not a dotted identifier.`);if(!O_.test(u))throw bt(`the control's constructor '${u}' is not an identifier.`);if(!I6.test(c))throw bt(`the control's version '${c}' is not major.minor.patch.`);let d=(0,Qr.firstLevel)(s,"resources");if(d.length!==1)throw bt("the manifest must hold exactly one <resources> element.");let f=[],m=0;for(let b of(0,Qr.elementChildren)(d[0])){let w=(0,Qr.attr)(b,"path");if(!D6.includes(b.tagName)){if(w!==null)throw bt(`<${b.tagName} path="${w}"> is not a resource kind the SDK registers.`);continue}if(!w)throw bt(`a <${b.tagName}> resource has no path.`);m+=b.tagName==="code"?1:0,f.push(w)}if(m!==1)throw bt(`the manifest must name exactly one <code> resource; it names ${m}.`);let p=new Map,h=[];for(let b of f){let w=P6(b),C=b.toLowerCase();if(C==="controlmanifest.xml")throw bt(`the resource path '${b}' is where the package puts the manifest itself.`);let S=p.get(C);if(S!==void 0)throw bt(`the manifest names '${b}' and '${S}', which are the same web resource.`);if(p.set(C,b),!Object.prototype.hasOwnProperty.call(o,b))throw bt(`the manifest names '${b}', but files has no such key.`);let O=(0,_6.asUint8Array)(o[b]);if(!O)throw bt(`files['${b}'] must be a Uint8Array.`);h.push({path:b,data:O,webResourceType:w})}let g=Object.keys(o).filter(b=>!f.includes(b));if(g.length>0)throw bt(`files holds ${g.map(b=>`'${b}'`).join(", ")}, which the manifest does not name.`);return{namespace:l,constructorName:u,version:c,manifest:i,files:h}}$e.checkPcfControlPackage=R6;function L6(e,t){return`${e}_${t.namespace}.${t.constructorName}`}$e.pcfControlName=L6;function k6(e,t){return`cc_${e.namespace}.${e.constructorName}/${t}`}$e.pcfWebResourceName=k6;function Ps(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var $6=["City","County","Country","Fax","FreightTermsCode","ImportSequenceNumber","Latitude","Line1","Line2","Line3","Longitude","Name","PostalCode","PostOfficeBox","PrimaryContactName"],x6=["StateOrProvince","Telephone1","Telephone2","Telephone3","TimeZoneRuleVersionNumber","UPSZone","UTCOffset","UTCConversionTimeZoneCode"];function P_(e){let t=r=>r.map(n=>`<${n} xsi:nil="true"></${n}>`).join("");return`<Address><AddressNumber>${e}</AddressNumber><AddressTypeCode>1</AddressTypeCode>${t($6)}<ShippingMethodCode>1</ShippingMethodCode>${t(x6)}</Address>`}function M_(e){let t=Ps(e.solutionUniqueName),r=Ps(e.publisherUniqueName);return`<ImportExportXml version="9.1.0.643" SolutionPackageVersion="9.1" languagecode="1033" generatedBy="CrmLive" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SolutionManifest><UniqueName>${t}</UniqueName><LocalizedNames><LocalizedName description="${t}" languagecode="1033" /></LocalizedNames><Descriptions /><Version>1.0</Version><Managed>0</Managed><Publisher><UniqueName>${r}</UniqueName><LocalizedNames><LocalizedName description="${r}" languagecode="1033" /></LocalizedNames><Descriptions><Description description="${r}" languagecode="1033" /></Descriptions><EMailAddress xsi:nil="true"></EMailAddress><SupportingWebsiteUrl xsi:nil="true"></SupportingWebsiteUrl><CustomizationPrefix>${Ps(e.prefix)}</CustomizationPrefix><CustomizationOptionValuePrefix>${e.optionValuePrefix}</CustomizationOptionValuePrefix><Addresses>${P_(1)}${P_(2)}</Addresses></Publisher><RootComponents><RootComponent type="66" schemaName="${Ps(e.controlName)}" behavior="0" /></RootComponents><MissingDependencies /></SolutionManifest></ImportExportXml>`}$e.pcfSolutionXml=M_;function U_(e){let t=Ps(e);return`<ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Entities></Entities><Roles></Roles><Workflows></Workflows><FieldSecurityProfiles></FieldSecurityProfiles><Templates /><EntityMaps /><EntityRelationships /><OrganizationSettings /><optionsets /><CustomControls><CustomControl><Name>${t}</Name><FileName>/Controls/${t}/ControlManifest.xml</FileName><ForceUpdate>true</ForceUpdate></CustomControl></CustomControls><EntityDataProviders /><Languages><Language>1033</Language></Languages></ImportExportXml>`}$e.pcfCustomizationsXml=U_;function B_(e){let t=["xml"];for(let n of e){let i=n.slice(n.lastIndexOf(".")+1).toLowerCase();t.includes(i)||t.push(i)}return`<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${t.map(n=>`<Default Extension="${Ps(n)}" ContentType="application/octet-stream" />`).join("")}</Types>`}$e.pcfContentTypesXml=B_;function F6(e){let t=`Controls/${e.controlName}`,r=[{name:"customizations.xml",data:(0,uf.utf8ToBytes)(U_(e.controlName))},{name:"solution.xml",data:(0,uf.utf8ToBytes)(M_(e))},...e.control.files.map(n=>({name:`${t}/${n.path}`,data:n.data})),{name:`${t}/ControlManifest.xml`,data:(0,uf.utf8ToBytes)(e.control.manifest)},{name:"[Content_Types].xml",data:(0,uf.utf8ToBytes)(B_(e.control.files.map(n=>n.path)))}];return(0,T6.zipStored)(r)}$e.buildPcfSolutionZip=F6;var M6=/^[ \t\r\n]*$/,q_=1,c0=3,U6=4,V_=7;function cf(e,t){let r=(0,Qr.attr)(e,"xml:space");return r==="preserve"?!0:r==="default"?!1:t}function R_(e,t){var r;let n=[],i=e.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];(a.nodeType===q_||a.nodeType===U6||a.nodeType===V_||a.nodeType===c0&&(t||!M6.test((r=a.nodeValue)!==null&&r!==void 0?r:"")))&&n.push(a)}return n}function L_(e){return e.length>0&&e.every(t=>t.nodeType===c0)?e.map(t=>{var r;return(r=t.nodeValue)!==null&&r!==void 0?r:""}).join(""):void 0}function k_(e,t){var r;let n="",i=t;for(;i<e.length&&e[i].nodeType===c0;)n+=(r=e[i].nodeValue)!==null&&r!==void 0?r:"",i+=1;return{text:n,next:i}}function l0(e,t){return(e.namespaceURI||null)===(t.namespaceURI||null)&&e.localName===t.localName}function B6(e,t,r,n){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType===q_)return G_(e,t,r,n);if(e.nodeType===V_){let i=e,o=t;return i.target===o.target&&i.data===o.data}return e.nodeValue===t.nodeValue}function q6(e,t,r,n){let i=L_(e);if(i!==void 0)return i===L_(t);if(e.length===0)return t.length===0;let o=0,a=0;for(;;){let s=k_(e,o),l=k_(t,a);if(s.text!==l.text)return!1;if(o=s.next,a=l.next,o>=e.length&&a>=t.length)return!0;if(o>=e.length||a>=t.length||!B6(e[o],t[a],r,n))return!1;o+=1,a+=1}}function G_(e,t,r,n){if(!l0(e,t)||e.attributes.length!==t.attributes.length)return!1;for(let a=0;a<e.attributes.length;a+=1){let s=e.attributes.item(a),l=t.attributes.item(a);if(!l0(s,l)||s.value!==l.value)return!1}let i=cf(e,r),o=cf(t,n);return q6(R_(e,i),R_(t,o),i,o)}function u0(e){return(0,Qr.elementChildren)(e).reduce((t,r)=>t+1+u0(r),0)}function $_(e){return cf(e,cf(e.parentNode,!1))}function V6(e,t){let r,n;try{r=s0(t).control,n=s0(e).control}catch{return!1}if(r.attributes.length!==n.attributes.length)return!1;for(let u=0;u<r.attributes.length;u+=1){let c=r.attributes.item(u),d;for(let m=0;m<n.attributes.length&&!d;m+=1){let p=n.attributes.item(m);d=l0(c,p)?p:void 0}if(!d||!(c.localName==="version"&&!c.namespaceURI)&&c.value!==d.value)return!1}if(u0(r)!==u0(n))return!1;let i=(0,Qr.elementChildren)(r),o=(0,Qr.elementChildren)(n),a=$_(r),s=$_(n),l=Math.min(i.length,o.length);for(let u=0;u<l;u+=1)if(!G_(i[u],o[u],a,s))return!1;return!0}$e.pcfManifestsEquivalent=V6});var z_=v(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});df.sha256Hex=void 0;var G6=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ai=(e,t)=>e>>>t|e<<32-t;function W6(e){let t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint8Array(Math.ceil((e.length+9)/64)*64);r.set(e),r[e.length]=128;let n=new DataView(r.buffer);n.setUint32(r.length-8,Math.floor(e.length/536870912)),n.setUint32(r.length-4,e.length%536870912*8);let i=new Uint32Array(64);for(let o=0;o<r.length;o+=64){for(let p=0;p<16;p+=1)i[p]=n.getUint32(o+p*4);for(let p=16;p<64;p+=1){let h=ai(i[p-15],7)^ai(i[p-15],18)^i[p-15]>>>3,g=ai(i[p-2],17)^ai(i[p-2],19)^i[p-2]>>>10;i[p]=i[p-16]+h+i[p-7]+g>>>0}let[a,s,l,u,c,d,f,m]=t;for(let p=0;p<64;p+=1){let h=m+(ai(c,6)^ai(c,11)^ai(c,25))+(c&d^~c&f)+G6[p]+i[p]>>>0,g=(ai(a,2)^ai(a,13)^ai(a,22))+(a&s^a&l^s&l)>>>0;m=f,f=d,d=c,c=u+h>>>0,u=l,l=s,s=a,a=h+g>>>0}t[0]+=a,t[1]+=s,t[2]+=l,t[3]+=u,t[4]+=c,t[5]+=d,t[6]+=f,t[7]+=m}return Array.from(t,o=>o.toString(16).padStart(8,"0")).join("")}df.sha256Hex=W6});var aT=v(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.registerPcfControl=Ne.readJobVerdict=Ne.PCF_REGISTRATION_UNVERIFIED_CODE=Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE=Ne.PCF_RESOURCE_NAME_TAKEN_CODE=Ne.PCF_CONTROL_MANAGED_CODE=Ne.PCF_CONTROL_AMBIGUOUS_CODE=Ne.PCF_CONTROL_NAME_TAKEN_CODE=Ne.PCF_TARGET_SOLUTION_MANAGED_CODE=void 0;var z6=Es(),_o=Tt(),Vi=W_(),X_=jr(),d0=Jd(),We=Q(),j6=cu(),Su=pa(),To=fe(),Z_=ct(),nt=oe(),H6=z_();Ne.PCF_TARGET_SOLUTION_MANAGED_CODE="PCF_TARGET_SOLUTION_MANAGED";Ne.PCF_CONTROL_NAME_TAKEN_CODE="PCF_CONTROL_NAME_TAKEN";Ne.PCF_CONTROL_AMBIGUOUS_CODE="PCF_CONTROL_AMBIGUOUS";Ne.PCF_CONTROL_MANAGED_CODE="PCF_CONTROL_MANAGED";Ne.PCF_RESOURCE_NAME_TAKEN_CODE="PCF_RESOURCE_NAME_TAKEN";Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE="PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL";Ne.PCF_REGISTRATION_UNVERIFIED_CODE="PCF_REGISTRATION_UNVERIFIED";var it="registerPcfControl",f0=66,K6=5e3,j_=300*1e3,J6={hash:"webresourceid,name,ismanaged,webresourcetype,contenthash",tokens:"webresourceid,name,ismanaged,webresourcetype",content:"webresourceid,name,ismanaged,webresourcetype,content"},ff=new WeakMap;function pf(e){return new We.InvalidArgumentError(`${it}: ${e}`)}function Rs(e,t){return e.toLowerCase()===t.toLowerCase()}function si(e){return e.map(t=>`'${t}'`).join(", ")}function Y6(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Nu(e){return e instanceof We.ConnectionError&&(e.statusCode===0||To.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}function Q6(e,t){var r;if(e!==void 0&&(typeof e!="object"||e===null))throw pf("options must be an object.");let{solutionUniqueName:n,publishAll:i}=e??{};if(i!==void 0&&i!==!0)throw pf(`publishAll must be absent or the literal true (it was ${String(i)}): it consents to PublishAllXml, which publishes every pending customization in the org. Nothing was sent.`);if(n!==void 0&&(typeof n!="string"||!n.trim()))throw pf("solutionUniqueName must be a non-empty string. Nothing was sent.");let o=(r=n)!==null&&r!==void 0?r:t;if(!o)throw pf("name the solution the control joins \u2014 options.solutionUniqueName or MakerSdkOptions.solutionUniqueName: its publisher's prefix names the control, and the SDK never guesses one. Nothing was sent.");return{target:o,publishAll:i===!0}}function eT(e,t,r){let n=e?.["@odata.etag"];if(!(0,To.isVersionToken)(n))throw new We.ConnectionError(r,200,`${it}: ${t} came back without a version token (@odata.etag ${n===void 0?"missing":JSON.stringify(n)}), so a change since it was read could not be detected`);return n}function tT(e,t){var r,n,i,o;let a=e,s=String((r=a?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=a?.customcontrolid)!==null&&n!==void 0?n:""),"customcontrolid"),name:s,version:String((i=a?.version)!==null&&i!==void 0?i:""),manifest:String((o=a?.manifest)!==null&&o!==void 0?o:""),managed:a?.ismanaged===!0,etag:eT(e,`the control '${s}'`,t)}}function X6(e,t){var r,n;let i=e,o=String((r=i?.name)!==null&&r!==void 0?r:"");return{id:(0,nt.normalizeGuid)(String((n=i?.webresourceid)!==null&&n!==void 0?n:""),"webresourceid"),name:o,managed:i?.ismanaged===!0,type:Number(i?.webresourcetype),content:typeof i?.content=="string"?i.content:"",contentHash:typeof i?.contenthash=="string"?i.contenthash.toLowerCase():"",etag:eT(e,`the web resource '${o}'`,t)}}async function p0(e){let t=(0,nt.odataLiteral)(e.key),r=`/customcontrols${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"],["$filter",`endswith(name,'_${t}') or name eq '${t}'`]])}`,n=e.client.apiUrl(r),i=e.key.toLowerCase();return(await(0,_o.collectPages)(e.client,r,it)).filter(o=>{let a=typeof o.name=="string"?o.name.toLowerCase():"";return a===i||a.slice(a.indexOf("_")+1)===i}).map(o=>tT(o,n))}async function mf(e,t){let r=`cc_${e.key}/`,n=`/webresourceset${(0,nt.odataQuery)([["$select",J6[t]],["$filter",`startswith(name,'${(0,nt.odataLiteral)(r)}')`]])}`,i=e.client.apiUrl(n);return(await(0,_o.collectPages)(e.client,n,it)).filter(o=>typeof o.name=="string"&&o.name.toLowerCase().startsWith(r.toLowerCase())).map(o=>X6(o,i))}function Z6(e){let t=ff.get(e.sdkClient);if(t)return t;let r=`/EntityDefinitions(LogicalName='webresource')/Attributes${(0,nt.odataQuery)([["$select","LogicalName"],["$filter","LogicalName eq 'contenthash'"]])}`,n=e.client.apiUrl(r),i=e.client.get(r).then(o=>{var a;let s=(a=(0,To.ensureSuccess)(o,n).body)===null||a===void 0?void 0:a.value;if(!Array.isArray(s))throw new We.ConnectionError(n,o.status,`${it}: the columns of webresource came back unreadable`);return s.some(l=>l?.LogicalName==="contenthash")}).catch(o=>{throw ff.get(e.sdkClient)===i&&ff.delete(e.sdkClient),o});return ff.set(e.sdkClient,i),i}async function rT(e,t){let r=await(0,_o.collectPages)(e.client,`/customcontrols(${t})/customcontrol_resource_id${(0,nt.odataQuery)([["$select","webresourceid,name"]])}`,it);return new Set(r.map(n=>n.webresourceid).filter(n=>typeof n=="string"&&n!=="").map(n=>n.toLowerCase()))}async function m0(e,t){let r=`/customcontrols(${t})${(0,nt.odataQuery)([["$select","customcontrolid,name,version,manifest,ismanaged"]])}`,n=await e.client.get(r);if(n.status!==404)return(0,To.ensureSuccess)(n,e.client.apiUrl(r)),tT(n.body,e.client.apiUrl(r))}function H_(e,t,r){return new We.SdkError(Ne.PCF_RESOURCE_NAME_TAKEN_CODE,`${it}: ${si(t.map(n=>n.name))} ${t.length===1?"is":"are"} named as a file of ${e.name} but ${r}. An import would create a second web resource of the same name (the runtime loads by name); rename or delete ${t.length===1?"it":"them"} first. Nothing was written.`)}async function ez(e){let t=await p0(e),r=t.filter(u=>!Rs(u.name,e.name));if(r.length>0)throw new We.SdkError(Ne.PCF_CONTROL_NAME_TAKEN_CODE,`${it}: the control ${e.key} is registered as ${si(r.map(u=>u.name))}, under another publisher prefix \u2014 the platform keeps one control per namespace and constructor. Target a solution whose publisher has that prefix, or remove that control. Nothing was written.`);if(t.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${t.length} control rows are named ${e.name}; the SDK cannot tell which one to update. Nothing was written.`);let n=t[0];if(n?.managed)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${n.name} is managed; a managed control is changed by its solution's upgrade, not in place. Nothing was written.`);let i=await mf(e,await Z6(e)?"hash":"tokens");if(!n){if(i.length>0)throw H_(e,i,"no control of that name exists");return}e.progress.customControlId=n.id;let o=await rT(e,n.id),a=i.filter(u=>!o.has(u.id));if(a.length>0)throw H_(e,a,`${n.name} does not reference ${a.length===1?"it":"them"}`);let s=i.filter(u=>u.managed);if(s.length>0)throw new We.SdkError(Ne.PCF_CONTROL_MANAGED_CODE,`${it}: ${si(s.map(u=>u.name))} of ${n.name} ${s.length===1?"is":"are"} managed. Nothing was written.`);let l=new Map;for(let u of e.checked.files){let c=(0,Vi.pcfWebResourceName)(e.checked,u.path),d=i.filter(f=>Rs(f.name,c));if(d.length>1)throw new We.SdkError(Ne.PCF_CONTROL_AMBIGUOUS_CODE,`${it}: ${n.name} references ${d.length} web resources named '${c}'; the SDK cannot tell which one the runtime loads. Nothing was written.`);d.length===1&&l.set(u.path,d[0])}return{control:n,folder:i,files:l}}function tz(e){return(0,H6.sha256Hex)((0,Su.utf8ToBytes)((0,Su.bytesToBase64)(e.data)))}function rz(e,t){if(!t)return{mode:"created"};let{control:r}=t,n=(0,Vi.pcfManifestsEquivalent)(r.manifest,e.checked.manifest),i=e.checked.files.filter(s=>!t.files.has(s.path)).map(s=>s.path),o=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l!==void 0&&l.type!==s.webResourceType).map(({file:s,row:l})=>`'${l.name}' (type ${l.type}, not ${s.webResourceType})`);if(!n||i.length>0||o.length>0){if(!e.publishAll){let s=n?i.length>0?`${r.name} lacks ${si(i)}, which only a re-import restores`:`${r.name}'s ${o.join(", ")} cannot be repaired by a files-only write \u2014 only a re-import may`:`the manifest of ${r.name} changed`;throw new We.SdkError(Ne.PCF_MANIFEST_CHANGE_NEEDS_PUBLISH_ALL_CODE,`${it}: ${s}, and a re-imported control is applied only by PublishAllXml \u2014 which publishes EVERY pending customization in the org. Pass publishAll: true to consent. Nothing was written.`)}return{mode:"reimported",snapshot:t}}if(r.version!==e.checked.version){if(e.publishAll)return{mode:"reimported",snapshot:t};e.warnings.push(`${r.name} keeps version ${r.version}: a files-only update does not change it (pac's --incremental neither); applying ${e.checked.version} needs publishAll: true.`)}let a=e.checked.files.map(s=>({file:s,row:t.files.get(s.path)})).filter(({file:s,row:l})=>l.contentHash!==tz(s));return a.length>0?{mode:"updated",snapshot:t,changed:a}:{mode:"unchanged",snapshot:t}}async function hf(e,t){var r;if(!t){let s=await p0(e),l=await mf(e,"tokens");if(s.length>0||l.length>0)throw new We.VersionConflictError("customcontrol",e.name,null,null,`Since this registration first read the org, ${si([...s.map(u=>u.name),...l.map(u=>u.name)])} appeared. Nothing was written; retry the registration.`);return}let n=[],i=await m0(e,t.control.id);i?i.etag!==t.control.etag&&n.push(i.name):n.push(`${t.control.name} (deleted)`);let o=await mf(e,"tokens"),a=new Map(t.folder.map(s=>[s.id,s.etag]));for(let s of o)a.has(s.id)?a.get(s.id)!==s.etag&&n.push(s.name):n.push(`${s.name} (new)`);for(let s of t.folder)o.some(l=>l.id===s.id)||n.push(`${s.name} (deleted)`);if(n.length>0)throw new We.VersionConflictError("customcontrol",e.name,t.control.etag,(r=i?.etag)!==null&&r!==void 0?r:null,`Changed since this registration read it: ${si(n)} \u2014 by another writer, or by the platform touching them (an import or publish elsewhere in the org can move these tokens with no change). Nothing was written; retry the registration.`)}function nT(e){let t;try{t=(0,j6.parseManifestRoot)(typeof e=="string"?e:"")}catch{return{state:"unknown",reason:"settled, but its data log does not parse"}}if(t.tagName!=="importexportxml"||t.namespaceURI)return{state:"unknown",reason:`settled, but its data log's root is <${t.tagName}>`};let r=(0,Vi.unboundPrefixes)(t);if(r.length>0)return{state:"unknown",reason:`settled, but its data log uses a prefix no declaration binds (${r.join(", ")})`};let n=t.getAttribute("succeeded");return n==="success"||n==="warning"?{state:"success"}:n==="failure"?{state:"failure",message:t.getAttribute("status")||"the import failed"}:{state:"unknown",reason:"settled without a success, warning or failure verdict"}}Ne.readJobVerdict=nT;function nz(e,t){return new Promise(r=>{let n=setTimeout(()=>r("late"),t);e.then(i=>{clearTimeout(n),r({value:i})},i=>{clearTimeout(n),r({error:i})})})}async function iz(e,t){let r=`/importjobs(${t})${(0,nt.odataQuery)([["$select","completedon,data"]])}`,n=Date.now()+j_,i={state:"unknown",reason:`had not settled after ${j_/6e4} minutes`};for(;;){let o=Math.min(K6,n-Date.now());if(o<=0)return i;await new Promise(c=>setTimeout(c,o));let a=n-Date.now();if(a<=0)return i;let s=await nz(e.client.get(r),a);if(s==="late")return i;if("error"in s){if(Nu(s.error))continue;return{state:"unknown",reason:`could not be read (${s.error.message})`}}let l=s.value;if(l.status===404)continue;if(l.status<200||l.status>=300)return{state:"unknown",reason:`could not be read (HTTP ${l.status})`};let u=l.body;if(u?.completedon)return nT(u.data)}}async function oz(e,t,r){let n=(0,Z_.newId)(),i=e.checked.files.map(s=>s.path),o=r?i.filter(s=>!r.files.has(s)):i;e.progress.phase="import",e.progress.importJobId=n,e.started=!0;let a;try{await(0,d0.importSolution)(e.client,{base64:(0,Su.bytesToBase64)(t),overwriteUnmanagedCustomizations:!1,publishWorkflows:!1,importJobId:n})}catch(s){if(!Nu(s))throw s;a=s}if(a){let s=await iz(e,n);if(s.state==="failure")throw new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} reports that it FAILED: ${s.message}`,a);if(s.state==="unknown")throw e.progress.imported="unknown",e.progress.unconfirmed=[...i],e.progress.publishedUnknown=[...o],new We.ConnectionError(a.url,a.statusCode,`the import's answer was lost, and its job ${n} ${s.reason}: whether it committed is unknown. Read importjobs(${n}), then retry the registration.`,a)}e.progress.imported="yes",e.progress.written=[...i],e.progress.published=[...o]}async function az(e){e.progress.phase="publish-all";let t=e.checked.files.map(r=>r.path).filter(r=>!e.progress.published.includes(r));try{await(0,X_.publishAllXml)(e.client)}catch(r){throw Nu(r)?(e.progress.publishAll="unknown",e.progress.publishedUnknown=[...e.progress.publishedUnknown,...t]):e.progress.publishAll="failed",r}e.progress.publishAll="succeeded",e.progress.published=[...e.progress.published,...t]}async function K_(e,t){var r,n;if(e.progress.imported==="unknown")return e.progress.temporaries.push(t.solution,t.publisher),[`The temporary solution '${t.solution}' and publisher '${t.publisher}' were left in place: the import's outcome is unknown, and an import still running may be using them. Delete them once importjobs(${e.progress.importJobId}) has settled.`];let i=(o,a)=>(e.progress.temporaries.push(...a),[`${si(a)} ${a.length===1?"was":"were"} left in place: ${o}. Delete ${a.length===1?"it":"them"} when convenient.`]);try{let o=await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.solution)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((r=a.solutionid)!==null&&r!==void 0?r:""),"solutionid");if(!await sz(e,s))return i(`the temporary solution holds components other than ${e.name}`,[t.solution,t.publisher]);let l=`/solutions(${s})`;(0,To.ensureSuccess)(await e.client.delete(l),e.client.apiUrl(l))}}catch(o){return i(`the temporary solution could not be removed (${o.message})`,[t.solution,t.publisher])}try{let o=await(0,_o.collectPages)(e.client,`/publishers${(0,nt.odataQuery)([["$select","publisherid"],["$filter",`uniquename eq '${(0,nt.odataLiteral)(t.publisher)}'`]])}`,it);for(let a of o){let s=(0,nt.normalizeGuid)(String((n=a.publisherid)!==null&&n!==void 0?n:""),"publisherid");if((await(0,_o.collectPages)(e.client,`/solutions${(0,nt.odataQuery)([["$select","solutionid"],["$filter",`_publisherid_value eq ${s}`]])}`,it)).length>0)return i("a solution uses the temporary publisher",[t.publisher]);let u=`/publishers(${s})`;(0,To.ensureSuccess)(await e.client.delete(u),e.client.apiUrl(u))}}catch(o){return i(`the temporary publisher could not be removed (${o.message})`,[t.publisher])}return[]}async function sz(e,t){var r,n;let i=await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t}`]])}`,it);for(let o of i){if(o.componenttype!==f0||typeof o.objectid!="string")return!1;let a=(0,nt.normalizeGuid)(o.objectid,"objectid");if(a!==e.progress.customControlId&&!Rs((n=(r=await m0(e,a))===null||r===void 0?void 0:r.name)!==null&&n!==void 0?n:"",e.name))return!1}return!0}async function J_(e,t,r){let n=(0,Z_.newId)().replace(/-/g,"").slice(0,12),i={solution:`CdsMakerSdkPcf${n}`,publisher:`CdsMakerSdkPcfPub${n}`},o=(0,Vi.buildPcfSolutionZip)({controlName:e.name,solutionUniqueName:i.solution,publisherUniqueName:i.publisher,prefix:e.solution.publisherPrefix,optionValuePrefix:e.solution.publisherOptionValuePrefix,control:e.checked});await hf(e,r);let a;try{await oz(e,o,r),t==="reimported"&&await az(e);let s=await fz(e,r),l=await h0(e,s.id);a=g0(e,t,s,l,e.checked.files.map(u=>u.path),[])}catch(s){throw(0,We.withCleanupWarnings)(s,await K_(e,i))}return a.warnings.push(...await K_(e,i)),a}async function Y_(e,t,r){try{return await r()}catch(n){throw Nu(n)&&e.progress.unconfirmed.push(...t),n}}function lz(e){return e instanceof We.SdkError&&e.code===To.VERSION_CONFLICT_CODE&&!(e instanceof We.VersionConflictError)}async function uz(e,t,r){let n=({file:a})=>({content:(0,Su.bytesToBase64)(a.data)}),i=r.map(({file:a})=>a.path);if(e.client.supportsAtomicBatch){let a=s=>Y_(e,i,()=>(0,z6.sendChangeSet)(e.client,r.map(l=>({method:"PATCH",path:`/webresourceset(${l.row.id})`,body:n(l),etag:s?l.row.etag:"*"})),`the files of ${e.name}`));try{await a(!0)}catch(s){if(!lz(s))throw s;await hf(e,t),await a(!1)}e.progress.written.push(...i);return}let o;for(let a of r){let s=`/webresourceset(${a.row.id})`,l=c=>Y_(e,[a.file.path],async()=>{let d=await e.client.patch(s,n(a),{headers:{"If-Match":c}});return d.status===412?d:(0,To.ensureSuccess)(d,e.client.apiUrl(s))}),u=await l(o===!1?"*":a.row.etag);if(u.status===412&&o===void 0&&(await hf(e,t),o=!1,u=await l("*")),u.status===412)throw new We.VersionConflictError("webresource",a.row.id,a.row.etag,null,`'${a.row.name}' changed after this registration read it${e.progress.written.length>0?`; ${si(e.progress.written)} had been written before it`:""}. Retry the registration once the other writer is done.`);o=o??!0,e.progress.written.push(a.file.path)}}async function cz(e,t){e.progress.phase="publish";let r=t.map(({file:i})=>i.path),n=t.map(({row:i})=>`<webresource>${(0,nt.xmlText)(i.id)}</webresource>`).join("");try{await(0,X_.publishXml)(e.client,`<importexportxml><webresources>${n}</webresources></importexportxml>`)}catch(i){throw Nu(i)&&e.progress.publishedUnknown.push(...r),i}e.progress.published.push(...r)}async function dz(e,t,r){await hf(e,t),e.progress.phase="write",e.started=!0,await uz(e,t,r),await cz(e,r),e.progress.phase="verify";let n=await m0(e,t.control.id);if(!n)throw gf(e,"updated",["the control was deleted"]);let i=[];if((n.version!==t.control.version||n.manifest!==t.control.manifest)&&i.push("its control row changed since it was read \u2014 another registration re-imported it"),i.push(...await oT(e,n.id)),i.length>0)throw gf(e,"updated",i);let o=await h0(e,n.id);return g0(e,"updated",n,o,[...e.progress.written],[...e.progress.published])}function gf(e,t,r){return new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} did not verify after it was ${t}: ${r.join("; ")}. Retrying the registration is safe.`)}function iT(e,t){let r=new Set(e.checked.files.map(n=>(0,Vi.pcfWebResourceName)(e.checked,n.path).toLowerCase()));for(let n of t){let i=`'${n.name}' is a file of ${e.name} that its manifest no longer names; the platform keeps it after a re-import, and the SDK does not delete it.`;!r.has(n.name.toLowerCase())&&!e.warnings.includes(i)&&e.warnings.push(i)}}async function oT(e,t){let r=await rT(e,t),n=await mf(e,"content"),i=[],o=n.filter(s=>!r.has(s.id));o.length>0&&i.push(`${si(o.map(s=>s.name))} in its folder ${o.length===1?"is":"are"} not its own`);let a=n.filter(s=>r.has(s.id));for(let s of e.checked.files){let l=(0,Vi.pcfWebResourceName)(e.checked,s.path),u=a.filter(d=>Rs(d.name,l));if(u.length!==1){i.push(`it references ${u.length} web resources named '${l}'`);continue}let[c]=u;c.type!==s.webResourceType&&i.push(`'${c.name}' has the web resource type ${c.type}, not ${s.webResourceType}`),c.managed&&i.push(`'${c.name}' is managed`),Y6((0,Su.base64ToBytes)(c.content),s.data)||i.push(`the published content of '${c.name}' is not the file sent`)}return iT(e,a),i}async function fz(e,t){e.progress.phase="verify";let r=t?"reimported":"created",n=await p0(e),i=n.filter(l=>Rs(l.name,e.name)),o=[],a=n.filter(l=>!Rs(l.name,e.name));if(a.length>0&&o.push(`${si(a.map(l=>l.name))} also ${a.length===1?"holds":"hold"} ${e.key}`),i.length!==1)throw gf(e,r,[...o,`${i.length} control rows are named ${e.name}`]);let[s]=i;if(e.progress.customControlId=s.id,t&&s.id!==t.control.id&&o.push(`its row is ${s.id}, not the re-imported ${t.control.id}`),s.managed&&o.push("it is managed"),s.version!==e.checked.version&&o.push(`its version is ${s.version}, not ${e.checked.version}`),(0,Vi.pcfManifestsEquivalent)(s.manifest,e.checked.manifest)||o.push("its stored manifest is not equivalent to the one sent"),o.push(...await oT(e,s.id)),o.length>0)throw gf(e,r,o);return s}async function Q_(e,t){return(await(0,_o.collectPages)(e.client,`/solutioncomponents${(0,nt.odataQuery)([["$select","solutioncomponentid"],["$filter",`_solutionid_value eq ${e.solution.solutionId} and objectid eq ${t} and componenttype eq ${f0}`]])}`,it)).length>0}async function h0(e,t){if(e.progress.phase="membership",await Q_(e,t))return"present";if(e.started=!0,await(0,d0.addSolutionComponent)(e.client,{componentId:t,componentType:f0,solutionUniqueName:e.solution.uniqueName,addRequiredComponents:!1}),!await Q_(e,t))throw new We.SdkError(Ne.PCF_REGISTRATION_UNVERIFIED_CODE,`${it}: ${e.name} is not in the solution '${e.solution.uniqueName}' after AddSolutionComponent. Retrying the registration is safe.`);return"added"}function g0(e,t,r,n,i,o){return{name:r.name,customControlId:r.id,mode:t,written:i,published:o,publishedAll:t==="reimported",storedVersion:r.version,membership:n,warnings:[...e.warnings]}}async function pz(e,t,r){let n=(0,Vi.checkPcfControlPackage)(t),{target:i,publishAll:o}=Q6(r,e.solutionName),a=e.withSolutionScope(void 0),s=await(0,d0.getSolution)(a,i);if(s.isManaged||!s.publisherPrefix)throw new We.SdkError(Ne.PCF_TARGET_SOLUTION_MANAGED_CODE,`${it}: the solution '${s.uniqueName}' ${s.isManaged?"is managed; a control joins an unmanaged solution":"has a publisher without a customization prefix, which would leave the control's name unprefixed"}. Nothing was written.`);let l=(0,Vi.pcfControlName)(s.publisherPrefix,n),u={client:a,sdkClient:e,checked:n,key:`${n.namespace}.${n.constructorName}`,name:l,solution:s,publishAll:o,progress:{phase:"import",name:l,imported:"no",written:[],unconfirmed:[],published:[],publishedUnknown:[],publishAll:"not-sent",temporaries:[]},warnings:[],started:!1};try{let c=rz(u,await ez(u));switch(c.mode){case"created":return await J_(u,"created",void 0);case"reimported":return await J_(u,"reimported",c.snapshot);case"updated":return await dz(u,c.snapshot,c.changed);default:{iT(u,c.snapshot.folder);let d=await h0(u,c.snapshot.control.id);return g0(u,"unchanged",c.snapshot.control,d,[],[])}}}catch(c){throw u.started?(0,We.withPcfRegistrationProgress)(c,u.progress):c}}Ne.registerPcfControl=pz});var v0=v(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.compileGenPage=Re.legacyEnumsNeeded=Re.createGenPageTypeScriptLoader=Re.acceptGenPageTypeScript=Re.isLoadableGenPageOutput=Re.runtimeTypesImportSpans=Re.GENPAGE_RUNTIME_TYPES_END=Re.GENPAGE_RUNTIME_TYPES_BEGIN=Re.GENPAGE_TYPESCRIPT_VERSION=void 0;var Ls=Q();Re.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Re.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Re.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Ln="./RuntimeTypes",mz="'\"`",sT=/\s/;function hz(e){return e===10||e===13||e===8232||e===8233}function gz(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function dT(e){let t=[],r=Ln.length;for(let l=e.indexOf(Ln);l!==-1;l=e.indexOf(Ln,l+1)){let u=l-1;u>=0&&mz.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&sT.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&sT.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Re.runtimeTypesImportSpans=dT;var yz=/\b(?:import\s*['"]|export\s)/;function bz(e){let t=gz(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!hz(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function vz(e){return e!==void 0&&e!==""&&(yz.test(e)||bz(e))}Re.isLoadableGenPageOutput=vz;var lT=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function fT(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?lT.filter(s=>typeof n?.[s]!="function"):[...lT];if(!n||i.length>0)throw new Ls.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Re.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new Ls.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Re.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Re.acceptGenPageTypeScript=fT;function wz(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Re.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(fT).catch(r=>{throw t=void 0,r instanceof Ls.SdkError?r:new Ls.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Re.createGenPageTypeScriptLoader=wz;var pT=e=>`${e.kind}:${e.pos}:${e.end}`;function Cz(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(pT(o)),e.forEachChild(i,n)};return n(r),r}}function b0(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var Ez=2301;function uT(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:b0(e),reportDiagnostics:!0,...r?{transformers:{after:[Cz(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`-`)}});return{code:i.outputText,diagnostics:o}}var cT=e=>e.startsWith(".")||e.startsWith("/"),yf={line:1,column:1};function y0(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):yf},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return yf}}}function Az(e,t,r,n){var i,o;let a=[],s=y0(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let C=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;C===Ln?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&cT(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Ln){cT(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>m.add(C.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let C=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,O=s.element(h,C);S!==C?l(O,d,`'${S} as ${C}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(C)||l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(yf,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function mT(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`-`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===Ez&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===Ln},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function Sz(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=mT(e,t,b0(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has(pT(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function Nz(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===Ln)}function hT(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Ln).map(r=>r.getStart(t))}function _z(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=hT(e,r),i=new Set(n),o,a="",s=0;for(let l of dT(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function Tz(e,t,r){let n=new Set(hT(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return yf}function gT(e,t,r){if(!r||r.size===0)return[];let n=mT(e,t,{...b0(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Ln&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Re.legacyEnumsNeeded=gT;function Dz(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function Iz(e,t,r,n){var i;let o=new Set,a=uT(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=Dz(r,n,gT(e,l,n)),c=[...Az(e,l,s,u),...Sz(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=uT(e,u.text);if(d.diagnostics.length>0)throw new Ls.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=_z(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...Tz(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&Nz(e,m)&&c.push({...y0(e,s).statement(Ln,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[Re.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Re.GENPAGE_RUNTIME_TYPES_END,m].join(`+`).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}}Er.partResponse=lS;async function $G(e,t,r){let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=zh(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Gh.ensureSuccess)(lS(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Gh.ensureSuccess)(a,s),!l||l.length!==t.length)throw new oo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Er.sendChangeSet=$G});var cd=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=se(),Kn=Ho(),me=Q(),xG=Wl(),FG={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 Ze(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:MG(e,t)}}var uS=65535;function MG(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 me.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 me.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>uS)throw new me.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${uS})`);if(i.has(s))throw new me.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new me.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function mS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new me.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=mS;function zl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var cS=["None","ApplicationRequired","Recommended"];function Kh(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function dS(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new me.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function UG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,E,S,P,L,I,D,O,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new me.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new me.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:Ze((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Ze((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:(P=t.dateFormat)!==null&&P!==void 0?P:"DateAndTime"};case"choice":return fS(t,r,!1);case"multiChoice":return fS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((O=t.autoNumberFormat)===null||O===void 0)&&O.trim()))throw new me.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 me.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function fS(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 me.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:Ze(o.label,t)}))},i}var jh=new WeakMap;async function BG(e,t){var r,n;let i=(r=jh.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 me.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=jh.get(e);return l||(l=new Map,jh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=BG;async function qG(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 me.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 me.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 E=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,S=Kh(t.schemaName),P=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:P,RequiredLevel:zl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Ze((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&bS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Ze(t.displayName,E),DisplayCollectionName:Ze((a=t.pluralName)!==null&&a!==void 0?a:mS(t.displayName),E),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(l=t.hasActivities)!==null&&l!==void 0?l:!1,HasNotes:(u=t.hasNotes)!==null&&u!==void 0?u:!1,Attributes:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(bn=>Jh(bn,E))]};t.description&&(I.Description=Ze(t.description,E));let D="/EntityDefinitions",O=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=jl(O),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Re=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),qt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${P.toLowerCase()}', { required: '${b}' }).`:"",je;try{je=await hS(e,K,Re,qt)}catch(bn){throw w?(0,me.attachCause)(new me.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${bn instanceof Error?bn.message:String(bn)}).${ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),bn):bn}if(!je)throw new me.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Re} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${ge}`);let de=je.body,He={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:P.toLowerCase()};return w&&(He.primaryColumnRequired=await VG(e,t.schemaName,He,b,Re,qt)),He}ie.createTable=qG;async function hS(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 VG(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 hS(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 me.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 ES(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,me.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 Jh(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...UG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:zl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Ze(e.displayName,i)};return e.description&&(o.Description=Ze(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),gS(o,e),o}function gS(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 GG(e,t,r){var n;let i=Jh(r,(n=r.languageCode)!==null&&n!==void 0?n:Kn.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:jl(a)};if(r.visualization&&r.visualization!=="None")try{await CS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new me.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,me.attachCause)(u,l),u}return s}ie.createColumn=GG;var os="/controlconfigurations",yS="CustomRenderersConfiguration",Hh={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 bS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new me.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 vS(e){return JSON.stringify({type:Hh[e]})}function WG(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Hh).find(i=>Hh[i]===r);return n??"None"}async function wS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${os}${(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 zG(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 me.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function CS(e,t,r,n,i){let o={name:yS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:vS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(os,o),e.apiUrl(os))}async function jG(e,t,r){var n;let i=await wS(e,t,r);return WG((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=jG;async function HG(e,t,r,n){let o=(await wS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await zG(e,t,r);if(a){let u=`${os}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:yS,metadatajson:vS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await CS(e,t,r,l,n);for(let u of s){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=HG;async function KG(e,t,r){if(r.length===0)return;if(bS(r,"createColumns"),!e.supportsAtomicBatch)throw new me.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,xG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Jh(i,(o=i.languageCode)!==null&&o!==void 0?o:Kn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=KG;async function JG(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,l=Kh(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:Ze(r.displayName,s),RequiredLevel:zl((a=r.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:u,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=JG;async function YG(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Ze(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=YG;async function QG(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new me.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Kh(t.schemaName)}_${t.referencedEntity}Id`;u=f.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:f,RequiredLevel:zl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Ze((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new me.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:jl(d),lookupLogicalName:u}}ie.createRelationship=QG;async function XG(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=XG;async function ES(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Kn.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=FG[(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 me.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=Ze(n.displayName,a)),n.description!==void 0&&(p.Description=Ze(n.description,a)),n.required!==void 0&&(p.RequiredLevel=zl(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 me.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 me.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),gS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=ES;async function ZG(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 me.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=ZG;async function e9(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 me.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=e9;async function pS(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 t9(e,t){var r;let n=t.name.toLowerCase(),i=await pS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Ze(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Ze(l.label,o)}))};t.description&&(a.Description=Ze(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:jl(l)}}catch(l){let u;try{u=await pS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=t9;async function r9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=r9;async function n9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Ze(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:jl(s)}}ie.createAlternateKey=n9;async function i9(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 me.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=i9;async function o9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.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 me.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=Ze(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Ze(r.pluralName,i)),r.description!==void 0&&(s.Description=Ze(r.description,i)),r.auditEnabled!==void 0&&dS(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&dS(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=o9});var so=v(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.rebuildRaw=Ar.assembleChildren=Ar.spliceChildren=Ar.mergeAttrs=Ar.rawFromNode=Ar.emptyBag=void 0;var ao=Q(),AS=1e6,fd=512;function a9(){return{a:[],c:[]}}Ar.emptyBag=a9;function SS(e,t=0){if(t>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>SS(r,t+1))}}Ar.rawFromNode=SS;function s9(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}Ar.mergeAttrs=s9;function dd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>AS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${AS}] (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}Ar.spliceChildren=dd;function l9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:dd(e.w.c,t)};return dd(e.c,[r])}return dd(e.c,t)}Ar.assembleChildren=l9;function NS(e,t,r,n=0){if(n>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);u9(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,NS(o,t,i,n+1));return i}Ar.rebuildRaw=NS;function u9(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(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.installDomShim=void 0;var _S=es(),TS=!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 d9(){if(TS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=_S.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=_S.XMLSerializer),typeof e.Node>"u"&&(e.Node=c9),TS=!0}pd.installDomShim=d9});var uo=v(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.projectElementBag=et.serializeNode=et.domEngine=et.nodeLikeFromDom=et.parseXmlRoot=et.EMPTY_FORM_SENTINEL=et.TEXT_SENTINEL=void 0;var f9=so(),as=Q(),p9=lo();et.TEXT_SENTINEL="#text";et.EMPTY_FORM_SENTINEL="#empty";var hd=new WeakSet;function m9(e,t){(0,p9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new as.InvalidArgumentError("XML source has no root element (empty or malformed input)");return h9(r),y9(n),v9(i),w9(i),A9(i,r),i}et.parseXmlRoot=m9;function h9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw IS(3)}var g9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function y9(e){var t;for(let r of g9){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 as.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var b9=new Set([1,3]);function v9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!b9.has(o.nodeType))throw new as.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 w9(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 IS(a.nodeType)}}function IS(e){return new as.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function C9(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 E9(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 OS(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r].nodeType;if(n===1||n===3)return!0}return!1}function A9(e,t){let r=C9(t),n=E9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];OS(a)||hd.add(a)}}function Yh(e){let t=e.nodeType===3;return{getNodeName:()=>t?et.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:et.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 hd.has(e)&&!OS(e)&&i.push({key:et.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(Yh(o))}return r}}}et.nodeLikeFromDom=Yh;function S9(e){return{make:t=>t===et.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===et.EMPTY_FORM_SENTINEL?hd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}et.domEngine=S9;function PS(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 md(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw md(r);t+=1;continue}if(r>=56320&&r<=57343)throw md(r)}}function md(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new as.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 N9(e){return PS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function _9(e){return PS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function T9(e){return RS(e,0)}et.serializeNode=T9;var DS=512;function RS(e,t){var r;if(t>DS)throw new as.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${DS}`);if(e.nodeType===3)return _9((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+'="'+N9(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 hd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=RS(l,t+1);return i+"</"+n.tagName+">"}function D9(e){let t=Yh(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,f9.rawFromNode)(r)}))}}et.projectElementBag=D9});var en=v(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.rejectUnknownKeys=Ht.childObjects=Ht.optionalGuidId=Ht.optionalEnum=Ht.eachObject=Ht.issue=Ht.isJsonObject=void 0;function LS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Ht.isJsonObject=LS;function ss(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Ht.issue=ss;function kS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{LS(o)?i.push({node:o,index:a}):n.push(ss(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Ht.eachObject=kS;function I9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(ss(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Ht.optionalEnum=I9;var O9=/^(?:\{[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 P9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!O9.test(o)&&i.push(ss(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Ht.optionalGuidId=P9;function R9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?kS(o,a,n,i):(i.push(ss(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Ht.childObjects=R9;function L9(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(ss(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Ht.rejectUnknownKeys=L9});var wd=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 k9=es(),$9=$a(),Qh=dt(),tn=en();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 x9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Sr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),x9.test(t)?t:""}B.normGuid=Sr;function co(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Kl(e){return Ae(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Kl;function Ae(e){return Array.isArray(e)?e:[]}function ng(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function FS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function MS(e){return An(e).map(t=>t.cell)}B.typedCells=MS;function An(e){let t=[];return Ae(e?.tabs).forEach((r,n)=>{Ae(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ae(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ae(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ae(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=An;function Di(e){return Pe(e)?Sr(ng(e.bag,"uniqueid")):""}B.controlUniqueId=Di;function F9(e){let t=new Set;for(let{cell:r}of An(e)){let n=Yo(r.control)?Di(r.control):"";n&&t.add(n)}return t}function M9(e){let t=new Map;for(let{cell:r}of An(e)){let n=Pe(r.control)?Di(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function U9(e){return e!==void 0&&e.genPage===void 0&&(ag(e)!==B.CUSTOM_CONTROL_CLASS_ID||!vd(e))}function Xh(e,t){if(Pe(e)){t(e);for(let r of Ae(e.c))Xh(r,t)}}function Ko(e,t){var r;if(Pe(e)){for(let n of Ae(e.c))Xh(n?.node,t);for(let n of Ae((r=e.w)===null||r===void 0?void 0:r.c))Xh(n?.node,t)}}function yd(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(Sr(co(i,"uniqueid")))};return Ko(e?.bag,n),Ae(e?.tabs).forEach(i=>{Pe(i)&&(Ko(i.bag,n),Ae(i.columns).forEach(o=>{Pe(o)&&(Ko(o.bag,n),Ae(o.sections).forEach(a=>{Pe(a)&&(Ko(a.bag,n),Ae(a.rows).forEach(s=>{Pe(s)&&(Ko(s.bag,n),Ae(s.cells).forEach(l=>{Pe(l)&&(Ko(l.bag,n),Pe(l.control)&&(r(Di(l.control)),Ko(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=yd;function ls(e){return Ae(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ls;function Jo(e,t){var r;let n=Sr(t);if(n)return Ae((r=ls(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Sr(co(i,"forControl"))===n)}B.descriptionFor=Jo;function Jl(e){return Ae(e.c).filter(US)}B.pageEntries=Jl;function US(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function Zh(e,t){let r=Ae(e.c).find(n=>n?.n==="parameters");return Ae(r?.c).find(n=>n?.n===t)}B.entryParameter=Zh;function eg(e){return co(e,"static")==="true"}B.isStaticParameter=eg;function Yl(e){let t=Jl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Zh(t[i],"RefId");if(!o||!eg(o))return{kind:"unsupported"};let a=Sr(Kl(o));if(!a)return{kind:"unsupported"};let s=Zh(t[i],"PageInput");if(s&&!eg(s))return{kind:"unsupported"};let l=s?Kl(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=Yl;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ig(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=ig;function og(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=og;function ag(e){return FS(e.classId!==void 0?e.classId:ng(e.bag,"classid"))}B.effectiveClassId=ag;function vd(e){return!e.fieldName}B.isUnbound=vd;function sg(e,t){if(og(e)!=="Main"||!vd(t)||ag(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Di(t),n=r?Jo(e.bag,r):void 0;return n!==void 0&&Yl(n).kind==="projectable"}B.isRecognizedEmbed=sg;function B9(e){for(let t of MS(e)){let r=t.control;if(!r||!sg(e,r))continue;let n=Yl(Jo(e.bag,Di(r)));if(n.kind!=="projectable")continue;let i=ig(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=B9;var q9=new Set(["pageId","inputData"]);function Hl(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 V9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new k9.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=Sr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Hl(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Hl(l):[]){let d=Sr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Hl(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Hl(f).find(g=>g.nodeName==="parameters"),p=m?Hl(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Sr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=V9;function gd(e){return{n:`<${e}`,a:[],c:[]}}function tg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[gd(t)]}}function rg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function G9(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:[tg("RefId",t),...r===void 0?[]:[tg("PageInput",rg(r))]]}]}))}}function bd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>bd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&bd(e[n],t[n]))}return e===t}function W9(e,t,r){let n=Ae(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Sr(Kl(i))!==t&&(i.c=[gd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Kl(a):void 0;if(bd(ig(s),r))return;if(r!==void 0){a?a.c=[gd(rg(r,s))]:n.c.push(tg("PageInput",rg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[gd(JSON.stringify(l))]}function lg(e){let t=Ae(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=lg;function z9(e,t){var r;let n=e.bag,i=ls(n);if(i&&t){let o=yd(t),a=yd(e),s=F9(t),l=M9(e),u=Ae(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Jl(d).length>0?Sr(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&U9(l.get(f))&&bd(d,Jo(t.bag,f))){let m=Ae(d.c).filter(p=>!US(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 An(e)){let a=o.control;if(!Yo(a)||!Pe(a.genPage))continue;let s=Sr(a.genPage.pageId),l=a.genPage.inputData,u=Di(a);if(!u){if(Ql(a)!==void 0)continue;u=ug(a)}let c=Jo(n,u);if(c){for(let m of Jl(c))W9(m,s,l);continue}i||(i={i:lg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=ng(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(G9(f,s,l))}}B.reconcileEmbedDescriptions=z9;function j9(e,t){let r=ls(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=An(e).some(({cell:a})=>Yo(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=ls(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ae(o.bag.c),o.bag.c.push({i:lg(e.bag),node:a}))}for(let{cell:a}of An(o))Yo(a.control)&&(BS(a.control),qS(a));return o}B.commitEmbedState=j9;function H9(e){if(An(e).some(({cell:r})=>Yo(r.control)))return!0;let t=ls(e.bag);return Ae(t?.node.c).some(r=>r?.n==="controlDescription"&&Jl(r).length>0)}B.mayCommitEmbedState=H9;function BS(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=BS;function qS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=qS;function Yo(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=Yo;function $S(e){return Yo(e.control)&&(!e.control.id||!e.id||Ql(e.control)===void 0)}function Ql(e){let t=Ae(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=Ql;function K9(e){if(!An(e).some(({cell:r})=>$S(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of An(t)){if(!$S(r))continue;let n=r.control;n.id||(n.id=(0,Qh.newId)()),r.id||(r.id=(0,Qh.newId)()),Ql(n)===void 0&&ug(n)}return t}B.mintEmbedIdentity=K9;function ug(e){let t=(0,Qh.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ae(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=Ae(e.bag.c),t}B.setUniqueId=ug;function xS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function J9(e){let t=Ae(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 Y9(e){let t=[],r;for(let{cell:n,pointer:i}of An(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){Q9(e,o,a,t);continue}r=r??yd(e),X9(e,o,a,r,t)}return t}B.genPageEmbedIssues=Y9;function Q9(e,t,r,n){if(!sg(e,t))return;let i=Yl(Jo(e.bag,Di(t)));n.push((0,tn.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 X9(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,tn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${xS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Sr(s.pageId))&&i.push((0,tn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,tn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${xS(s.inputData)}`));for(let m of Object.keys(s))q9.has(m)||i.push((0,tn.issue)($9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}vd(t)||i.push((0,tn.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&&FS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,tn.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=og(e);l!=="Main"&&i.push((0,tn.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=Ql(t);u!==void 0&&!Sr(u)&&i.push((0,tn.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=Di(t);if(!c)return;let d=Jo(e.bag,c),f=d?Yl(d):void 0;d&&f?.kind==="none"?i.push((0,tn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${J9(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,tn.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,tn.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 dg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var Z9=Lt(),cg=se();fo.GENPAGE_LOOKUP_CHUNK=50;async function e5(e,t,r){let n=[...new Set(t.map(o=>(0,cg.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,cg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,Z9.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,cg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=e5});var Xl=v(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.assertSystemFormKind=Nt.readSystemFormType=Nt.decodeCode=Nt.assertSystemFormRecordKind=Nt.describeSystemFormType=Nt.systemFormKindOf=Nt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var GS=Q(),t5=ye(),VS=se();Nt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var r5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},n5={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 Cd(e){return Number.isInteger(e)?r5[e]:void 0}Nt.systemFormKindOf=Cd;function WS(e){var t;return Number.isFinite(e)?`a ${(t=n5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Nt.describeSystemFormType=WS;function zS(e,t,r,n){let i=WS(r),o=Cd(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 i5(e,t,r,n){let i=fg(e?.type);if(Cd(i)!==r)throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,i,n));return i}Nt.assertSystemFormRecordKind=i5;function fg(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}Nt.decodeCode=fg;async function o5(e,t){return await jS(e,t,!1)}Nt.readSystemFormType=o5;async function a5(e,t){return jS(e,t,!0)}async function jS(e,t,r){var n;let o=`/systemforms(${(0,VS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,VS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,t5.ensureSuccess)(a,e.apiUrl(o)),fg((n=a.body)===null||n===void 0?void 0:n.type)}async function s5(e,t,r){let n=await a5(e,t);if(!(n===void 0||Cd(n)===r))throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,n,"delete"))}Nt.assertSystemFormKind=s5});var mg=v(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.patchSystemForm=qr.assertSystemFormContentUnchanged=qr.readSystemFormRowEtag=qr.unpublishedSystemFormPath=qr.FORM_TYPE_IMMUTABLE_CODE=void 0;var rn=ye(),l5=se(),Ed=Q(),po=Xl();qr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function pg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,l5.odataQuery)([["$select",t]])}qr.unpublishedSystemFormPath=pg;function HS(e,t){return(0,rn.readRowEtag)(e,"systemforms","formid",t)}qr.readSystemFormRowEtag=HS;async function KS(e,t,r,n,i){(0,rn.requireEtag)(i,r,t);let o=(0,rn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,rn.readEtag)(o);if(s===null)throw new Ed.SdkError(rn.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 Ed.SdkError(rn.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}qr.assertSystemFormContentUnchanged=KS;async function u5(e,t,r,n,i,o){(0,rn.requireEtag)(i,r,t);let a=await HS(e,t);if(a===null)throw new Ed.SdkError(rn.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 KS(e,t,r,pg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Ed.SdkError(qr.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,rn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,rn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),c5(e,t,r,o)}qr.patchSystemForm=u5;async function c5(e,t,r,n){let i;try{let o=pg(t,n.select),a=(0,rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,rn.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 vg=v(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.getFormSecurityRoles=kt.setFormSecurityRoles=kt.formApi=kt.readPrimaryCreateRefusal=kt.FORM_GENPAGE_TARGET_UNVERIFIABLE=kt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var d5=Lt(),_t=ye(),nn=se(),Qo=Q(),hg=uo(),YS=wd(),f5=dg(),gg=mg(),Zl=Xl();kt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";kt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var QS="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",p5={select:QS,required:["name","type","objecttypecode"]},m5="formid,name,type,objecttypecode",h5=2,g5={Main:h5,QuickView:6,QuickCreate:7,Card:11},XS=new WeakMap;function y5(e){return typeof e=="object"&&e!==null?XS.get(e):void 0}kt.readPrimaryCreateRefusal=y5;kt.formApi={async get(e,t){let r=(0,nn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select",QS]]),i=(0,_t.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,Zl.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,_t.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=>g5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,nn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,nn.odataQuery)([["$select",m5],["$filter",a.join(" and ")]])}`;return(await(0,d5.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=JS(t);n!==void 0&&await ZS(e,bg(n,"payload"),[]);let i=(0,_t.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,_t.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,_t.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,_t.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&XS.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,_t.resolveCreatedId)(l,"formid","form",r),etag:(0,_t.readEtag)(l)}},async update(e,t,r,n){let i=(0,nn.normalizeGuid)(t,"id"),o=JS(r);return o!==void 0&&await v5(e,i,o,n),(0,gg.patchSystemForm)(e,i,"form",r,n,p5)},readContentThenToken(e,t){return kt.formApi.get(e,t)},async delete(e,t){let r=(0,nn.normalizeGuid)(t,"id");return await(0,Zl.assertSystemFormKind)(e,r,"form"),(0,_t.deleteRecord)(e,"systemforms",r)}};var yg="DisplayConditions";async function b5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Qo.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,nn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,_t.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,Zl.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,_t.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new Qo.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,hg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new Qo.InvalidArgumentError(`form '${s}' produced no owner document`);let h=eN(m,yg),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 Qo.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(yg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let O=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",O),r.everyone)I.appendChild(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,nn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,hg.serializeNode)(m);await(0,gg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let P=await(0,gg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,_t.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,_t.requireEtag)(P,"form",s)}}),e.apiUrl(L))}kt.setFormSecurityRoles=b5;function JS(e){let t=e?.formxml;return typeof t=="string"&&t.includes(YS.GENPAGE_CONTROL_NAME)?t:void 0}function bg(e,t){try{return(0,YS.activeEmbedBindings)(e)}catch(r){throw new Qo.SdkError(kt.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 ZS(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,f5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Qo.SdkError(kt.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 v5(e,t,r,n){var i;(0,_t.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,_t.readEtag)(a);if(s===null||s!==n)throw new Qo.SdkError(_t.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!==""?bg(l,"server"):[];await ZS(e,bg(r,"payload"),u)}function eN(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 w5(e,t){var r,n;let i=(0,nn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.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,hg.parseXmlRoot)(s,"<form/>"),u=eN(l,yg);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)}:{}}}kt.getFormSecurityRoles=w5});var wg=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 C5=Lt(),xt=ye(),ar=se(),E5=dt(),Kt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var A5=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],tN="uxagentproject",rN=new WeakMap;async function lN(e){var t;let r=rN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${tN}')${(0,ar.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,xt.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 Kt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${tN}' \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 rN.set(e,o),o}be.resolveGenPageComponentType=lN;var nN=1,iN=0;async function S5(e,t){let r=(0,ar.normalizeGuid)(t,"solutionId"),n=await lN(e),o=[nN,...A5,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ar.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,C5.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===nN){let f=c.rootcomponentbehavior;(f===iN||f===String(iN))&&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=S5;function N5(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 _5(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Kt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=N5(f)?`solutionid eq ${(0,ar.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ar.odataLiteral)(f)}'`,p=`/solutions${(0,ar.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,xt.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 Kt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Kt.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 Kt.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,ar.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,ar.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=_5;async function T5(e,t){var r;let n={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(r=t.optionValuePrefix)!==null&&r!==void 0?r:1e4};t.description&&(n.description=t.description);let i=(0,xt.ensureSuccess)(await(0,xt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,xt.readCreatedId)(i,"publisherid");if(!o)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=T5;async function D5(e,t){var r;let n=(0,ar.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,xt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,xt.readCreatedId)(o,"solutionid");if(!a)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=D5;async function I5(e,t,r){let i=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=I5;async function O5(e,t){var r;let i={ComponentId:(0,ar.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,xt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=O5;async function P5(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ar.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,xt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=P5;async function R5(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,xt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Kt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=R5;async function L5(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 Kt.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:W5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ar.normalizeGuid)(t.importJobId,"importJobId"):(0,E5.newId)()};if(!n)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await uN(e,t.base64,eu,o),{parameters:s,applied:l}=z5(a,n);return i.ComponentParameters=s,(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Kt.withCleanupWarnings)(a,o)}}be.importSolution=L5;var eu="importSolution",oN="getDeploymentSettingsTemplate";async function k5(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Kt.InvalidArgumentError(`${oN}: '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 uN(e,n,oN,i),a=Ad(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=Ad(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,Kt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=k5;function Ad(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 Xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $t(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 uN(e,t,r,n){var i;let a=(i=(0,xt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return x5(a,r)}finally{await $5(e,Xo(a)?a.StageSolutionUploadId:void 0,n)}}async function $5(e,t,r){let n;try{n=(0,ar.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${$t(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,xt.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 or(e,t){return new Kt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===eu?" Nothing was imported.":""}`)}function aN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>Xo(r)&&typeof r.Message=="string"?r.Message:$t(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function x5(e,t){if(!Xo(e))throw or(t,`it holds no StageSolutionResults (${$t(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Kt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${$t(r)}). Missing dependencies: ${aN(e.MissingDependencies)}. Validation: ${aN(e.SolutionValidationResults)}.${t===eu?" 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 or(t,`StageSolutionStatus is ${$t(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw or(t,`SolutionComponentsDetails is not a list (${$t(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!Xo(l))throw or(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw or(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=F5(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw or(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw or(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 or(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=M5(f.get("type"),`${c}.type`,t),b=U5(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 or(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 F5(e,t,r){if(!Xo(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw or(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw or(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw or(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw or(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function M5(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 or(r,`${t} is not a whole number (${$t(e,40)})`)}}function U5(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 or(r,`${t} is not true or false (${$t(e,40)})`)}}var B5=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),q5=["Workflows","CanvasApps","CopilotAgents"],V5=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),G5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function ir(e,t){return new Kt.InvalidArgumentError(`${eu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function W5(e){let t="deploymentSettings";if(!Xo(e))throw ir(t,`must be an object \u2014 the settings file, parsed (it was ${$t(e,40)})`);for(let l of Object.keys(e))if(!B5.has(l))throw ir(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of q5){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw ir(`${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 ir(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw ir(`${t}.${l}`,`must be a list (it was ${$t(u,40)})`);return u.map((c,d)=>{if(!Xo(c))throw ir(`${t}.${l}[${d}]`,`must be an object (it was ${$t(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw ir(c,`must be a non-empty string (it was ${$t(d,40)})`);if(d.trim()!==d)throw ir(c,`must not begin or end with whitespace (it was ${$t(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw ir(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(!V5.has(f))throw ir(`${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 ir(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${$t(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(!G5.has(m))throw ir(`${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 ir(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${$t(f,40)})`);if(f.trim()!==f)throw ir(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${$t(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw ir(`${c}.ConnectorId`,`must be a string (it was ${$t(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function sN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function z5(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=sN(Ad(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=sN(Ad(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Kt.InvalidArgumentError(`${eu}: 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 j5(e,t){let n=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=j5});var hN=v(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.recoverFormCreate=ft.solutionMembershipProblem=ft.formWriteMismatches=ft.validateExistingForm=ft.formExistsAtId=ft.isFormRecordAt=ft.MAIN_FORM_TYPE=void 0;var us=se(),cN=Lt(),dN=wg();ft.MAIN_FORM_TYPE=2;function Sd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nd(e){return e instanceof Error?e.message:String(e)}function Cg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,us.normalizeGuid)(e,"a GUID")===(0,us.normalizeGuid)(t,"a GUID")}catch{return!1}}function Eg(e,t){return Sd(e)&&Cg(e.formid,t)}ft.isFormRecordAt=Eg;async function H5(e,t){try{return Eg((await e()).raw,t)}catch{return!1}}ft.formExistsAtId=H5;function fN(e,t){let r=e.raw;if(!Sd(r))return{problem:"it is not a record"};if(!Eg(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==ft.MAIN_FORM_TYPE)return{problem:`its type is not ${ft.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}}ft.validateExistingForm=fN;function pN(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}ft.formWriteMismatches=pN;async function mN(e,t){let r=e.solutionName;if(r)try{let n=await(0,cN.collectPages)(e,`/solutions${(0,us.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,us.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 Sd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,us.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,us.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${dN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Sd(l)&&l.componenttype===dN.SolutionComponentType.SystemForm&&Cg(l.objectid,t)&&Cg(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 (${Nd(n)})`}}ft.solutionMembershipProblem=mN;async function K5(e){try{return await J5(e)}catch(t){return{refused:`the recovery could not be completed (${Nd(t)})`}}}ft.recoverFormCreate=K5;async function J5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==ft.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 (${Nd(f)})`}}let l=fN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=pN(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 (${Nd(f)})`}}let d=await mN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Td=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.disassociateRecords=Je.associateRecords=Je.createRecordsBulk=Je.upsertRecord=Je.queryAllRecords=Je.queryRecords=Je.getRecord=Je.deleteRecord=Je.updateRecord=Je.createRecord=void 0;var Ag=Lt(),Sn=ye(),Jt=se(),cs=Q(),Jn=cd();function _d(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 Y5(e,t,r){let i=`/${await(0,Jn.resolveEntitySetName)(e,t)}`,o=(0,Sn.ensureSuccess)(await e.post(i,_d(r)),e.apiUrl(i)),a=(0,Sn.readCreatedId)(o,`${t}id`);if(!a)throw new cs.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Je.createRecord=Y5;async function Q5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${i})`;(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a))}Je.updateRecord=Q5;async function X5(e,t,r){let n=(0,Jt.normalizeGuid)(r,"id"),o=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${n})`;(0,Sn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Je.deleteRecord=X5;async function Z5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=await(0,Jn.resolveEntitySetName)(e,t),a=(0,Jt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Sn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new cs.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,Ag.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Je.getRecord=Z5;function e8(e){return e?.fetchXml?(0,Jt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Jt.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 gN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new cs.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 cs.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,Jn.resolveEntitySetName)(e,t)}${e8(r)}`;if(r?.paginate)return(0,Ag.collectPages)(e,o,"queryRecords");let a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new cs.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Ag.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Je.queryRecords=gN;async function t8(e,t,r){return gN(e,t,{...r,paginate:!0})}Je.queryAllRecords=t8;function r8(e){if("id"in e)return`(${(0,Jt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Jt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Jt.assertODataName)(e.key,"alternate key name")}=${t})`}async function n8(e,t,r,n){let i=r8(r),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}${i}`,s=(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a)),l=s.status===201,u=(0,Sn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Jt.normalizeGuid)(r.id,"id"):""),created:l}}Je.upsertRecord=n8;async function i8(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Jn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,..._d(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Sn.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 cs.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Je.createRecordsBulk=i8;async function o8(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=(0,Jt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Jn.resolveEntitySetName)(e,t),s=await(0,Jn.resolveEntitySetName)(e,n.targetEntity),l=(0,Jt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Sn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Je.associateRecords=o8;async function a8(e,t,r,n,i){let o=(0,Jt.normalizeGuid)(r,"id"),a=(0,Jt.normalizeGuid)(i,"targetId"),s=await(0,Jn.resolveEntitySetName)(e,t),l=(0,Jt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Sn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Je.disassociateRecords=a8});var Dd=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.base64ToUtf8=on.base64ToBytes=on.bytesToBase64=on.utf8ToBase64=on.utf8ToBytes=void 0;var Sg=32768,Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function tu(){return globalThis}function yN(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 s8(e){let t="";for(let r=0;r<e.length;r+=Sg)t+=String.fromCharCode(...e.subarray(r,r+Sg));return t}function l8(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+="/":Nr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function u8(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+=Nr[i>>18&63]+Nr[i>>12&63]+Nr[i>>6&63]+Nr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Nr[i>>18&63]}${Nr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Nr[i>>18&63],a=Nr[i>>12&63],s=Nr[i>>6&63];t+=`${o}${a}${s}=`}return t}function c8(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=Nr.indexOf(e[o])<<18|Nr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Nr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Nr.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 d8(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):yN(e)}on.utf8ToBytes=d8;function f8(e){let t=tu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return bN(r?new r().encode(e):yN(e))}on.utf8ToBase64=f8;function bN(e){let t=tu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(s8(e)):u8(e)}on.bytesToBase64=bN;function vN(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=l8(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return c8(r)}on.base64ToBytes=vN;function p8(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>=Sg&&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 m8(e){let t=tu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):p8(vN(e))}on.base64ToUtf8=m8});var AN=v(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.deleteWebResource=Yn.getWebResource=Yn.updateWebResource=Yn.createWebResource=void 0;var h8=Jr(),ru=ye(),Id=se(),g8=Dd(),wN=Q(),y8={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function CN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,g8.utf8ToBase64)(e.content)}async function EN(e,t){return(0,h8.publishWebResourceById)(e,t)}async function b8(e,t){var r;let n=CN(t);if(n===void 0)throw new wN.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:y8[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ru.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ru.readCreatedId)(o,"webresourceid");if(!a)throw new wN.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await EN(e,a),{id:a,name:t.name}}Yn.createWebResource=b8;async function v8(e,t,r){let n=(0,Id.normalizeGuid)(t,"id"),i={},o=CN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ru.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await EN(e,n)}Yn.updateWebResource=v8;async function w8(e,t){var r;let i=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})${(0,Id.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ru.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Yn.getWebResource=w8;async function C8(e,t){let n=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})`;(0,ru.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Yn.deleteWebResource=C8});var Od=v(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.applyAppSettings=Tt.setAppSetting=Tt.readAppSettings=Tt.resolveSettingDefinitions=Tt.APP_SETTING_UNSET=Tt.APP_SETTING_OFF=Tt.APP_SETTING_ON=Tt.HEADER_AND_NAVIGATION_REFRESH=void 0;var ds=ye(),Ii=se();Tt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Tt.APP_SETTING_ON="2";Tt.APP_SETTING_OFF="1";Tt.APP_SETTING_UNSET="0";function _N(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ii.odataQuery)([["$select",e],["$filter",t]])}async function TN(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,Ii.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,ds.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}Tt.resolveSettingDefinitions=TN;async function E8(e,t){var r,n,i,o;let a=(0,Ii.normalizeGuid)(t,"App id"),s=_N("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,ds.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Ii.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,ds.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}:{}}})}Tt.readAppSettings=E8;async function SN(e,t,r){var n,i,o;let a=_N("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ds.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function DN(e,t,r,n){let i=(0,Ii.normalizeGuid)(t,"App id"),a=(await TN(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,Ii.normalizeGuid)(s,"Setting definition id"),u=await SN(e,i,l);if(u)return NN(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 SN(e,i,l)}catch{p=void 0}if(p)return NN(e,p,n);throw f&&(0,ds.ensureSuccess)(f,e.apiUrl(c)),m}Tt.setAppSetting=DN;async function NN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Ii.normalizeGuid)(t.id,"App setting id")})`;return(0,ds.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function A8(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await DN(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}Tt.applyAppSettings=A8});var Rd=v(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.HEADER_NAV_BOOLEAN_RULE=void 0;Pd.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Tg=v(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.compileGenPage=Le.legacyEnumsNeeded=Le.createGenPageTypeScriptLoader=Le.acceptGenPageTypeScript=Le.isLoadableGenPageOutput=Le.runtimeTypesImportSpans=Le.GENPAGE_RUNTIME_TYPES_END=Le.GENPAGE_RUNTIME_TYPES_BEGIN=Le.GENPAGE_TYPESCRIPT_VERSION=void 0;var fs=Q();Le.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Le.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Le.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Nn="./RuntimeTypes",S8="'\"`",IN=/\s/;function N8(e){return e===10||e===13||e===8232||e===8233}function _8(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 LN(e){let t=[],r=Nn.length;for(let l=e.indexOf(Nn);l!==-1;l=e.indexOf(Nn,l+1)){let u=l-1;u>=0&&S8.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&&IN.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&&IN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Le.runtimeTypesImportSpans=LN;var T8=/\b(?:import\s*['"]|export\s)/;function D8(e){let t=_8(/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&&!N8(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function I8(e){return e!==void 0&&e!==""&&(T8.test(e)||D8(e))}Le.isLoadableGenPageOutput=I8;var ON=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function kN(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?ON.filter(s=>typeof n?.[s]!="function"):[...ON];if(!n||i.length>0)throw new fs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Le.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new fs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Le.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Le.acceptGenPageTypeScript=kN;function O8(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(kN).catch(r=>{throw t=void 0,r instanceof fs.SdkError?r:new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Le.createGenPageTypeScriptLoader=O8;var $N=e=>`${e.kind}:${e.pos}:${e.end}`;function P8(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add($N(o)),e.forEachChild(i,n)};return n(r),r}}function _g(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var R8=2301;function PN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:_g(e),reportDiagnostics:!0,...r?{transformers:{after:[P8(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 RN=e=>e.startsWith(".")||e.startsWith("/"),Ld={line:1,column:1};function Ng(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):Ld},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 Ld}}}function L8(e,t,r,n){var i,o;let a=[],s=Ng(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 E=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;E===Nn?l(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&RN(E)&&c(s.statement(E,"export"),E);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Nn){RN(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(E=>m.add(E.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let E=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,P=s.element(h,E);S!==E?l(P,d,`'${S} as ${E}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(E)||l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(Ld,"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 xN(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===R8&&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===Nn},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 k8(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=xN(e,t,_g(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($N(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 $8(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===Nn)}function FN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Nn).map(r=>r.getStart(t))}function x8(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=FN(e,r),i=new Set(n),o,a="",s=0;for(let l of LN(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 F8(e,t,r){let n=new Set(FN(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 Ld}function MN(e,t,r){if(!r||r.size===0)return[];let n=xN(e,t,{..._g(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===Nn&&((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))}Le.legacyEnumsNeeded=MN;function M8(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 U8(e,t,r,n){var i;let o=new Set,a=PN(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=M8(r,n,MN(e,l,n)),c=[...L8(e,l,s,u),...k8(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=PN(e,u.text);if(d.diagnostics.length>0)throw new fs.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=x8(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...Ng(e,s).statement(Nn,"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({...F8(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&&$8(e,m)&&c.push({...Ng(e,s).statement(Nn,"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:[Le.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Le.GENPAGE_RUNTIME_TYPES_END,m].join(`-`),diagnostics:c}}Re.compileGenPage=Iz});var w0=v(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.isFailureAfterPrimaryWrite=ks.failedAfterPrimaryWrite=void 0;var yT=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Oz(e){return typeof e=="object"&&e!==null&&(e[yT]=!0),e}ks.failedAfterPrimaryWrite=Oz;function Pz(e){return typeof e=="object"&&e!==null&&e[yT]===!0}ks.isFailureAfterPrimaryWrite=Pz});var Af=v(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.appApi=li.deleteAppResolvingOnce=li.mainFormSetShapeIssues=li.unpublishedAppModulesQuery=void 0;var $s=Tt(),Rz=T0(),Lz=jg(),bT=jr(),kz=tf(),$z=w0(),ge=fe(),Ae=oe(),E0=ct(),PT=Es(),_e=Q(),xz=(0,Ae.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),A0="appmoduleid,name,uniquename,description,aiappdescription";function wf(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",e],["$filter",t],["$top",r]])}li.unpublishedAppModulesQuery=wf;function S0(e,t){return wf(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Cf(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ae.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function _u(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function Fz(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Ef(e,t){if(typeof e!="string")return!1;try{return(0,Ae.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function ma(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function Mz(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function RT(e,t){var r,n;let i=u=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ae.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ae.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))return i("returned a malformed body");let l=(n=s[0])===null||n===void 0?void 0:n.sitemapid;return s.length>0&&!l?i("returned a row with no sitemapid"):l}async function Uz(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,Ae.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var vT="627090ff-40a3-4053-8790-584edc5be201";function Gi(e){return e instanceof Error?e.message:String(e)}async function Bz(e,t){var r;try{let n=`/roles${(0,Ae.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${vT}`]])}`,i=await(0,$s.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${vT}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,ge.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Gi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function qz(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,$s.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Gi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ae.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ae.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ae.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ae.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ae.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var wT=new WeakMap;async function Vz(e,t){let r=wT.get(e);r||(r=new Map,wT.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Gz(e,t);return i&&r.set(t,i),i}async function CT(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function Gz(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ae.odataPathLiteral)(t)}')${(0,Ae.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function ET(e,t,r){let n=[],i=ma(t.entities),o=4,a=await CT(i,o,g=>Vz(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new _e.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of ma(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of ma(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of ma(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of ma(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await CT(i,o,g=>qz(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...ma(t.components.forms),...ma(t.components.dashboards)].map(Xr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let C of w.allowed)h.has(C)||(h.add(C),u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));else for(let C of g.forms)u.has(C)||(u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));for(let C of g.views)c.has(C)||(c.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:C}));for(let C of g.charts)d.has(C)||(d.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:C}))}),{components:n,tables:l,warnings:p}}function Xr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var _0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N0="/components/mainFormsByTable",AT=50;function LT(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function kT(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:N0,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${N0}/${LT(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!_0.test(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Xr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Xr(c))})}return r}li.mainFormSetShapeIssues=kT;async function ST(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=kT(n,t.entities);if(i.length>0)throw new _e.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ae.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Xr(h.formid)),Number(h.formactivationstate)===1&&m.add(Xr(h.formid)));let p=u.map(Xr);p.forEach((h,g)=>{let b=`${N0}/${LT(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Xr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new _e.ValidationError("app",r,o);return a}async function Wz(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(wf("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!_0.test(Xr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Xr(l)}}function bf(e,t){let r;return()=>r??(r=Wz(e,t))}async function $T(e,t,r,n=bf(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,$s.collectPages)(e,`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Xr(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>Xr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Gi(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!_0.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=AT){let p=u.slice(m,m+AT);try{let h=await(0,$s.collectPages)(e,`/systemforms${(0,Ae.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Xr(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Gi(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function zz(e,t,r,n){let i=await $T(e,t,r,n);if(i.kind==="inconclusive")throw new _e.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new _e.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function jz(e,t,r,n){let i;try{i=await $T(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Gi(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function NT(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,ge.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function _T(e,t,r,n=bf(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ae.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new _e.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new _e.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function Hz(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await Jz(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Gi(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Gi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Gi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:FT(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await MT(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function Kz(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function Jz(e,t,r){var n,i,o;let a=Cf(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function Yz(e,t){var r;let n;try{n=await e.get(wf("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Ef(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function xT(e,t){var r;let n=(0,Ae.normalizeGuid)(t,"id"),i=b=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${xz}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await Yz(e,n);if(b.kind!=="draft")return i(`reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,ge.readEtag)(a)},c=await RT(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ae.normalizeGuid)(c,"sitemapId"),f=await vf(e,d),m=Cf(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=_u(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Ef(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function Qz(e,t,r){let n=(0,Ae.normalizeGuid)(t,"id"),i=await xT(e,n);await r?.(i.sitemapXml),await BT(e,n,i)}li.deleteAppResolvingOnce=Qz;async function Xz(e,t){let r=await MT(e,t);if(r.kind!=="deleted")throw r.error}function FT(e,t){try{return(0,ge.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return UT(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function Zz(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,PT.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,ge.namesAppSearchIndexRace)(i.text))}async function MT(e,t){let r=`batch_${(0,E0.newId)()}`,n=`changeset_${(0,E0.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r+`),diagnostics:c}}Le.compileGenPage=U8});var Dg=v(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.isFailureAfterPrimaryWrite=ps.failedAfterPrimaryWrite=void 0;var UN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function B8(e){return typeof e=="object"&&e!==null&&(e[UN]=!0),e}ps.failedAfterPrimaryWrite=B8;function q8(e){return typeof e=="object"&&e!==null&&e[UN]===!0}ps.isFailureAfterPrimaryWrite=q8});var Ud=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.appApi=Qn.deleteAppResolvingOnce=Qn.mainFormSetShapeIssues=Qn.unpublishedAppModulesQuery=void 0;var ms=Lt(),V8=$g(),G8=dg(),BN=Jr(),W8=Od(),z8=Dg(),he=ye(),Ne=se(),Og=dt(),e_=Wl(),Se=Q(),j8=(0,Ne.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Pg="appmoduleid,name,uniquename,description,aiappdescription";function xd(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Qn.unpublishedAppModulesQuery=xd;function Rg(e,t){return xd(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Fd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function nu(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function H8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Md(e,t){if(typeof e!="string")return!1;try{return(0,Ne.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Zo(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function K8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function t_(e,t){var r,n;let i=u=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${u}, so it cannot be determined whether this app has a sitemap. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)};if(!t)return i("cannot run because the app record carried no uniquename");let o=`/sitemaps${(0,Ne.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ne.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 J8(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,Ne.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let 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 qN="627090ff-40a3-4053-8790-584edc5be201";function Oi(e){return e instanceof Error?e.message:String(e)}async function Y8(e,t){var r;try{let n=`/roles${(0,Ne.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${qN}`]])}`,i=await(0,ms.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${qN}) 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,he.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 (${Oi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function Q8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,ms.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Oi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ne.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ne.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ne.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ne.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ne.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ne.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var VN=new WeakMap;async function X8(e,t){let r=VN.get(e);r||(r=new Map,VN.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Z8(e,t);return i&&r.set(t,i),i}async function GN(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 Z8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ne.odataPathLiteral)(t)}')${(0,Ne.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function WN(e,t,r){let n=[],i=Zo(t.entities),o=4,a=await GN(i,o,g=>X8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new Se.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of Zo(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of Zo(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of Zo(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of Zo(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 GN(i,o,g=>Q8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...Zo(t.components.forms),...Zo(t.components.dashboards)].map(Vr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let E of w.allowed)h.has(E)||(h.add(E),u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)u.has(E)||(u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:n,tables:l,warnings:p}}function Vr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var kg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Lg="/components/mainFormsByTable",zN=50;function r_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function n_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Lg,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=`${Lg}/${r_(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"||!kg.test(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Vr(c))})}return r}Qn.mainFormSetShapeIssues=n_;async function jN(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=n_(n,t.entities);if(i.length>0)throw new Se.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ne.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(Vr(h.formid)),Number(h.formactivationstate)===1&&m.add(Vr(h.formid)));let p=u.map(Vr);p.forEach((h,g)=>{let b=`${Lg}/${r_(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=Vr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new Se.ValidationError("app",r,o);return a}async function eW(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(xd("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"||!kg.test(Vr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Vr(l)}}function kd(e,t){let r;return()=>r??(r=eW(e,t))}async function i_(e,t,r,n=kd(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,ms.collectPages)(e,`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Vr(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=>Vr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Oi(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=>!kg.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+=zN){let p=u.slice(m,m+zN);try{let h=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.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=Vr(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 (${Oi(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 tW(e,t,r,n){let i=await i_(e,t,r,n);if(i.kind==="inconclusive")throw new Se.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new Se.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function rW(e,t,r,n){let i;try{i=await i_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Oi(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 HN(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,he.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function KN(e,t,r,n=kd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new Se.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function nW(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await oW(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Oi(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 (${Oi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Oi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,he.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:a_(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await s_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function iW(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function oW(e,t,r){var n,i,o;let a=Fd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function aW(e,t){var r;let n;try{n=await e.get(xd("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!Md(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 o_(e,t){var r;let n=(0,Ne.normalizeGuid)(t,"id"),i=b=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${j8}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await aW(e,n);if(b.kind!=="draft")return i(`reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.body)===null||r===void 0?void 0:r.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let u=l?{draft:!0}:{appEtag:(0,he.readEtag)(a)},c=await t_(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ne.normalizeGuid)(c,"sitemapId"),f=await $d(e,d),m=Fd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=nu(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Md(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function sW(e,t,r){let n=(0,Ne.normalizeGuid)(t,"id"),i=await o_(e,n);await r?.(i.sitemapXml),await u_(e,n,i)}Qn.deleteAppResolvingOnce=sW;async function lW(e,t){let r=await s_(e,t);if(r.kind!=="deleted")throw r.error}function a_(e,t){try{return(0,he.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return l_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function uW(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,e_.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,he.namesAppSearchIndexRace)(i.text))}async function s_(e,t){let r=`batch_${(0,Og.newId)()}`,n=`changeset_${(0,Og.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r-`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,ge.resendWhile)(m=>Zz(m,s),()=>e.postBatch(o,r),ge.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=FT(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,PT.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new _e.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new _e.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function vf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,ge.readEtag)(r)}catch{return null}}async function TT(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,ge.ensureSuccess)(n,e.apiUrl(r)),(0,ge.readEtag)(n)}async function C0(e,t,r,n){if(!n)return null;let i=await vf(e,t);if(!i)return null;try{let o=await e.get(Cf(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=_u(o);return!a||!Ef(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function UT(e){return e>=400&&e<500&&e!==408&&e!==429}function DT(e,t,r){if(!e)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function BT(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:DT(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await ej(e,n,i);return}if(!e.supportsAtomicBatch)throw new _e.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await Xz(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:DT(r.sitemapEtag,t,"sitemap")}])}async function ej(e,t,r){(0,ge.ensureSuccess)(await(0,ge.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function IT(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Rz.collectGenPageIds)(t))]}catch(i){throw new _e.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Gi(i)}).`)}if(r.length===0)return;let n=await(0,Lz.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new _e.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function tj(e){var t,r;if(e.status!==400)return!1;let n=e.body;return String((r=(t=n?.error)===null||t===void 0?void 0:t.message)!==null&&r!==void 0?r:"").includes("retrieval of version numbers failed")}async function OT(e,t,r){var n;let i=(0,Ae.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await TT(e,i):null,s=S0(A0,i),l=(0,ge.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=_u(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new _e.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await RT(e,u.uniquename),d=c?(0,Ae.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await vf(e,d));let p=Cf(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,ge.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=_u(h),b=w=>{throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new _e.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Ef(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await vf(e,d))}o||(a=await TT(e,i));let m=a??Fz(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ae.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}li.appApi={get(e,t){return OT(e,t,"tokens-first")},readContentThenToken(e,t){return OT(e,t,"content-first")},async list(e,t){let r=S0(A0);return(await(0,$s.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;await IT(e,n.sitemapxml);let i=await ST(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await Uz(e),a=n.iconWebResourceId||o?.id;if(!a)throw new _e.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||Mz(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,ge.ensureSuccess)(await(0,ge.resendDeadlockVictim)(()=>e.post(c,(0,ge.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,ge.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ae.normalizeGuid)(n.sitemapId,"sitemapId"):(0,E0.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let O="/sitemaps",L=(0,ge.echoWrite)("sitemapid"),I=await e.post(`${O}${L.query}`,{sitemapid:b,sitemapnameunique:l,...C},L.options);w=UT(I.status);let D=(0,ge.ensureSuccess)(I,e.apiUrl(O));p=(0,ge.readEtag)(D),m=p??await C0(e,b,C,l);let P=await ET(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await NT(e,f,x);let K=bf(e,f);await _T(e,f,P.tables,K),i&&await zz(e,f,i,K);let Le=await Bz(e,f);Le&&h.push(Le),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,kz.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,bT.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let L=await Hz(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,$z.failedAfterPrimaryWrite)(Kz(O,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let O=await e.get(`/appmodules(${f})?$select=appmoduleid`);O.status>=200&&O.status<300&&(S=(0,ge.readEtag)(O))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,f,m,p;let h=r,g=(0,Ae.normalizeGuid)(t,"id");if(await IT(e,h.sitemapxml),!h.sitemapId)throw new _e.ValidationError("app",g,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${g}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${g}'), clear the local copy with deleteArtifact('app', '${g}'), then author the app again and push.`}]);let b=(0,Ae.normalizeGuid)(h.sitemapId,"sitemapId");if(!(0,ge.isVersionToken)(n))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"no concurrency token is held for its sitemap row"}, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the app and re-apply the change.`);let w=await ST(e,h,g),C=await ET(e,h,w),S=`/appmodules(${g})`,O=(a=o?.[g])!==null&&a!==void 0?a:null,L=!0,I;try{let Bt=S0(A0,g),Ni=await e.get(Bt);if(Ni.status>=200&&Ni.status<300){let Ha=(s=_u(Ni))!==null&&s!==void 0?s:{};I=typeof Ha.uniquename=="string"&&Ha.uniquename?Ha.uniquename:void 0,L=String((l=Ha.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Ha.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((f=Ha.aiappdescription)!==null&&f!==void 0?f:"")!==String(h.appModuleAiDescription)}}catch{}let D=O;if(L){if(!(0,ge.isVersionToken)(O))throw new _e.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${O?`the concurrency token held for its appmodule header ('${O}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${g}', { overwrite: true })) and re-apply the change.`);let Bt=(0,ge.echoWrite)("appmoduleid",{"If-Match":O}),Ni=await e.patch(`${S}${Bt.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Bt.options);if(tj(Ni))throw new _e.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${g}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,ge.ensureSuccess)(Ni,e.apiUrl(S)),D=(0,ge.readEtag)(Ni)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},x=I||h.appModuleUniqueName||void 0,K=(0,ge.echoWrite)("sitemapid",{"If-Match":n}),Le=`/sitemaps(${b})`,lr;try{lr=(0,ge.ensureSuccess)(await e.patch(`${Le}${K.query}`,{...P},K.options),e.apiUrl(Le))}catch(Bt){throw(0,_e.withPartialTokens)(Bt,{siblingEtags:{[g]:D}})}let Ge=[...C.warnings],Ut=bf(e,g);try{await NT(e,g,C.components),await _T(e,g,C.tables,Ut)}catch(Bt){Ge.push(`App '${g}': one or more components were not pinned (${Bt.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Ge.push(...await jz(e,g,w,Ut));let de={kind:"notRequested"},Ke=D,ur=(m=(0,ge.readEtag)(lr))!==null&&m!==void 0?m:await C0(e,b,P,x);if(h.published===!0){try{await(0,bT.publishAppModule)(e,g),de={kind:"submitted"}}catch(Bt){de={kind:"failed",error:Bt},Ge.push(`App '${g}': saved, but publishing failed (${Bt.message}). The app remains unpublished; re-push to retry.`)}if(de.kind==="submitted"){Ke=null;try{let Bt=await e.get(`/appmodules(${g})?$select=appmoduleid`);Bt.status>=200&&Bt.status<300&&(Ke=(0,ge.readEtag)(Bt)),ur=(p=await C0(e,b,P,x))!==null&&p!==void 0?p:ur}catch{}}}return{id:g,etag:ur,siblingEtags:{[g]:Ke},publish:de,...Ge.length>0?{warnings:Ge}:{}}},async delete(e,t){let r=(0,Ae.normalizeGuid)(t,"id");await BT(e,r,await xT(e,r))}}});var T0=v(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.deleteAppCascade=xs.collectGenPageIds=void 0;var rj=Af(),nj=Q(),D0=oe(),ij=ys();function qT(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new ij.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new nj.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,D0.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}xs.collectGenPageIds=qT;async function oj(e,t,r){let n=(0,D0.normalizeGuid)(t,"appModuleId");(0,D0.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,rj.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...qT(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}xs.deleteAppCascade=oj});var VT={};nn(VT,{Guid:()=>U});var U,vt=k(()=>{"use strict";U=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var q,rr=k(()=>{"use strict";dt();q=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),r&&(n=n.replace(/"/g,""").replace(/'/g,"'"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!R.IsNullOrUndefined(r))for(let i of r.getKeys())n+=" "+this.ToSnakeCase(i)+'="'+r.getValue(i)+'"';return n+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return R.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,r){return t===r?!0:!t||!r?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(r).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(n=>(n.charAt(0)!=="{"&&(n="{"+n),n.charAt(n.length-1)!=="}"&&(n=n+"}"),n)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(n=>{let i;return n.charAt(0)==="{"&&(i=n.substr(1,n.length-1)),n.charAt(n.length-1)==="}"&&(i=i.substr(0,n.length-2)),i}):t}}});var GT={};nn(GT,{ScriptUtilities:()=>R});var R,dt=k(()=>{"use strict";vt();rr();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:q.IsTrue(n)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let r=new Set;return e.getAllUniqueTagNamesHelper(t,r),r}static getAllUniqueTagNamesHelper(t,r){if(t.nodeType===Node.ELEMENT_NODE&&(r.add(t.tagName),t.hasChildNodes()))for(let n=0;n<t.children.length;n++)this.getAllUniqueTagNamesHelper(t.children.item(n),r)}}});var Sf,Nf,ha,_f,I0,Tf,O0=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Sf||(Sf={}));Nf=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ha=class extends Nf{key;oldValue;newValue;constructor(t,r,n,i){super(Sf.FormElementNodeChange,t),this.key=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},_f=class extends Nf{property;oldValue;newValue;constructor(t,r,n,i){super(Sf.FormElementAttributeChange,t),this.property=r,this.oldValue=n,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},I0=class{changeSet;reversedChangeSet;constructor(t){this.changeSet=t,this.changeSet&&(this.reversedChangeSet=this.changeSet.slice().reverse())}length(){return this.changeSet?this.changeSet.length:0}apply(){this.changeSet&&this.changeSet.length>0&&this.changeSet.forEach(t=>{t.apply()})}revert(){this.reversedChangeSet&&this.reversedChangeSet.length>0&&this.reversedChangeSet.forEach(t=>{t.revert()})}},Tf=class{isTracking;_trackedChanges;_trackedChangeSets;constructor(t=!1){this.isTracking=t,this._trackedChanges=[],this._trackedChangeSets=[]}addChange(t){this.isTracking&&this._trackedChanges.push(t)}collectChanges(){let t=new I0(this._trackedChanges.slice());return this._trackedChanges=[],t}pushChangeSet(t){this._trackedChangeSets.push(t)}popChangeSet(){if(this._trackedChangeSets?.length>0)return this._trackedChangeSets.pop()}getChangeSets(){return this._trackedChangeSets}}});var WT={};nn(WT,{ChartGridMode:()=>hn,ColumnLayoutWidths:()=>cj,ComponentCategory:()=>If,ComponentType:()=>P0,ControlLayoutTypes:()=>M0,DisplayConditionsInfo:()=>lj,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>L0,EntityAttributeProperty:()=>k0,EventType:()=>Tu,FormActivationState:()=>F0,FormCanvasServiceScope:()=>Ej,FormDesignerSideBarTab:()=>R0,FormPresentation:()=>$0,FormState:()=>Df,FormType:()=>wt,HeaderDensityType:()=>Do,LookUpTable:()=>ui,MORE_TAB_PREFIX:()=>fj,NavBarChildElementType:()=>x0,PREVIEW_ID_HEADER_FLYOUT:()=>gj,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>bj,PREVIEW_ID_NAVIGATION_AREA:()=>mj,PREVIEW_ID_QUICKCREATE_ROOT:()=>wj,PREVIEW_ID_TAB:()=>vj,PREVIEW_ID_TAB_LIST:()=>yj,PREVIEW_ID_TAB_PANEL:()=>hj,PropertyModelKeys:()=>q0,PropertyModelSectionKeys:()=>dj,RELATED_TAB_ID:()=>V0,RELATED_TAB_PREFIX:()=>pj,SectionDefaultProperties:()=>uj,SectionLayoutTypes:()=>je,TabContentType:()=>U0,TabDefaultProperties:()=>Io,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>Cj,UnboundControlPropertyKeys:()=>B0,compositeAddressFields:()=>sj,compositeFieldNames:()=>Zr,compositeFields:()=>aj});var wt,P0,R0,E,y,L0,Zr,aj,sj,k0,ui,Df,Do,$0,lj,x0,F0,ze,uj,Io,je,M0,U0,cj,B0,q0,dj,Tu,hn,V0,fj,pj,mj,hj,gj,yj,bj,vj,wj,Cj,If,Ej,le=k(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(wt||(wt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(P0||(P0={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(R0||(R0={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(E||(E={}));y={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})(L0||(L0={}));Zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},aj=[Zr.fullname,Zr.yomifullname,Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto],sj=[Zr.address1_composite,Zr.address2_composite,Zr.address3_composite,Zr.billto,Zr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(k0||(k0={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(ui||(ui={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Df||(Df={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Do||(Do={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})($0||($0={}));lj={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(x0||(x0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(F0||(F0={}));(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN_EQUAL=1]="TWO_COLUMN_EQUAL",e[e.TWO_COLUMN_WIDER_LEFT=2]="TWO_COLUMN_WIDER_LEFT",e[e.TWO_COLUMN_WIDER_RIGHT=3]="TWO_COLUMN_WIDER_RIGHT",e[e.TWO_COLUMN_CUSTOM_LAYOUT=4]="TWO_COLUMN_CUSTOM_LAYOUT",e[e.THREE_COLUMN_EQUAL=5]="THREE_COLUMN_EQUAL",e[e.THREE_COLUMN_WIDER_MID=6]="THREE_COLUMN_WIDER_MID",e[e.THREE_COLUMN_CUSTOM_LAYOUT=7]="THREE_COLUMN_CUSTOM_LAYOUT"})(ze||(ze={}));uj={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},Io={namePrefix:"tab_",ShowLabel:"true",LockLevel:"0",IsUserDefined:"0"};(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN",e[e.TWO_COLUMN=1]="TWO_COLUMN",e[e.THREE_COLUMN=2]="THREE_COLUMN",e[e.FOUR_COLUMN=3]="FOUR_COLUMN",e[e.REFERENCE_PANEL=4]="REFERENCE_PANEL"})(je||(je={}));(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.NOTES=8]="NOTES",e[e.SOCIAL_INSIGHTS=9]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=10]="KB_SEARCH",e[e.INTERACTION_WALL=11]="INTERACTION_WALL",e[e.ACI_CONTROL=12]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=13]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=14]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=15]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=16]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=17]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=18]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=19]="PRED_LEAD_SCORING"})(M0||(M0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(U0||(U0={}));cj={ONE_COLUMN:"100",TWO_COLUMN:"50",THREE_COLUMN:"33.33",FOUR_COLUMN:"25"};(function(e){e.minValue="MinValue",e.maxValue="MaxValue",e.precision="Precision",e.maxLength="MaxLength",e.entityLogicalName="EntityLogicalName",e.defaultViewId="DefaultViewId",e.optionSetDefaultValue="DefaultValue",e.optionSetId="OptionSetId"})(B0||(B0={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(q0||(q0={}));dj={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})(Tu||(Tu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(hn||(hn={}));V0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",fj="more_tab_",pj="related_tab_",mj="preview_id_navigation_area",hj="tab-section",gj="headerFieldsFlyout",yj="tablist",bj="header_overflowButton",vj="tab",wj="quickCreateRoot",Cj={defaultVisibility:"Default visibility"};(function(e){e.input="input",e.layout="layout",e.grid="grid",e.relatedData="relatedData",e.display="display",e.powerbi="powerbi",e.artificialIntelligence="artificialIntelligence",e.media="media",e.collaboration="collaboration",e.more="more",e.test="test",e.popular="popular"})(If||(If={}));Ej="CellCanvasServiceScope"});var zT={};nn(zT,{Attribute:()=>Of,FormElementNode:()=>re});var Of,re,kt=k(()=>{"use strict";dt();rr();O0();le();vt();Of=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${U.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(E.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Of(t,r))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let r=this.properties.findIndex(n=>n.key===t);r>-1&&this.properties.splice(r,1)})}trackPropertyCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.properties.slice();t(),r.addChange(new ha(this,"properties",n,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.childrenNodes.slice();t(),r.addChange(new ha(this,"childrenNodes",n,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let r=this.changeTracker();if(r&&r.isTracking){let n=this.parentNode;if(t(),n===this.parentNode)return;r.addChange(new ha(this,"parentNode",n,this.parentNode))}else t()}trackAttributeValueChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=t.value;if(i===r)return;t.value=r,n.addChange(new _f(this,t,i,r))}else t.value=r}trackObjectPropertyChange(t,r){let n=this.changeTracker();if(n&&n.isTracking){let i=this[t];if(i===r)return;this[t]=r,n.addChange(new ha(this,t,i,r))}else this[t]=r}setProperty(t,r){if(!t)throw new Error("Invalid property key");let n=this.properties.find(i=>i.key===t);n?this.trackAttributeValueChange(n,r):this.addProperty(t,r)}addProperty(t,r){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,r)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,r){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.IsNullOrUndefined(t))return-1;for(let r=0;r<this.childrenNodes.length;r++)if(this.childrenNodes[r]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1)}),r;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:q.EmptyString}updateChild(t,r){let n=this.childrenNodes.indexOf(t);return n>-1?(r.trackParentNodeChange(()=>{r.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1,r)}),!0):!1}getAncestor(t){let r=this.getParent(),n=this.getParentType();for(;r;){if(n===t)return r;n=r.getParentType(),r=r.getParent()}return null}deleteFirstGrandChildOfName(t,r){return this.getChildren(t)[0].deleteChild(r)}deleteChildren(t,r){r=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case E.formCell:let t=this.getAncestor(E.formSection);return t||(t=this.getAncestor(E.formHeader),t)||(t=this.getAncestor(E.formFooter),t)?t:null;case E.formSection:return this.getAncestor(E.formTab);case E.formTab:return this.getAncestor(E.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(E.form);return t?t.changeTracker():null}}});var jT={};nn(jT,{ControlClassId:()=>N,ControlNamePrefixes:()=>Pf,getControlDisplayNames:()=>Aj});function Aj(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Pf,ga=k(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(N||(N={}));Pf={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ya=v((Ade,KT)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),HT=function(){return Du};Object.setPrototypeOf(HT,Du);KT.exports=HT});var hr,Wi,JT,YT,Fs=k(()=>{"use strict";hr="cds-designer-models",Wi="FormCustomControl",JT="FormCell",YT="Form"});var ba,G0=k(()=>{"use strict";su();le();ba=class e{static lockedFieldCount=new dr;static dependencyFieldCount=new dr;static getNecessaryLookUpTable(t){switch(t){case ui.DependencyFieldTable:return e.dependencyFieldCount;case ui.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case ui.DependencyFieldTable:e.dependencyFieldCount=new dr;case ui.LockedFieldTable:e.lockedFieldCount=new dr}}}});var Rf,QT=k(()=>{"use strict";vt();dt();le();kt();Rf=class extends re{constructor(t){super(E.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(E.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});function zi(){return ci||(ci=window._makerConfig,ci&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ci={...ci,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ci?.region==="prod"&&(ci={endpoints:{eu:{ch:{graphql:"https://graph-make.ch-cm001.gateway.prod.cm.powerapps.com/"},de:{graphql:"https://graph-make.de-cm001.gateway.prod.cm.powerapps.com/"},fr:{graphql:"https://graph-make.fr-cm001.gateway.prod.cm.powerapps.com/"},no:{graphql:"https://graph-make.no-cm001.gateway.prod.cm.powerapps.com/"},default:{graphql:"https://graph-make.eu-cm001.gateway.prod.cm.powerapps.com/"}}},...ci}),ci||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ci,Lf=k(()=>{"use strict";});function XT(e,t,r){if(!e)return kf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),kf.add("")),!1;if(e){if(e=e.toLowerCase(),kf.has(e))return!1;if(!(e in t))return window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoNonExistent",eventInfo:{missinggeo:e,parent:r}}),kf.add(e),!1}return!0}function Sj(e){return XT(e,W0,"Location dictionary")?W0[e.toLowerCase()]:"us"}function Nj(){let e=zi().location.toLowerCase();return XT(e,W0,"Current location dictionary")?e:"us"}var kf,W0,xde,ZT=k(()=>{"use strict";Lf();kf=new Set,W0={cae:"ae",nae:"ae",eas:"as",seas:"as",eau:"au",seau:"au",sbr:"br",cca:"ca",eca:"ca",nch:"ch",wch:"ch",nde:"de",wcde:"de",neu:"eu",weu:"eu",cfr:"fr",sfr:"fr",cin:"in",sin:"in",ejp:"jp",wjp:"jp",suk:"uk",wuk:"uk",eus:"us",wus:"us",cus:"us",ude:"us",udc:"us",ugtx:"us",ugva:"us",eus2:"us",wus2:"us",nza:"za",wza:"za",cne2:"cn",cnn2:"cn",skr:"kr",ckr:"kr",eno:"no",wno:"no",wrx:"us",erx:"us",wex:"us",eex:"us",unitedstates:"us",europe:"eu",asia:"as",australia:"au",japan:"jp",canada:"ca",india:"in",italy:"it",unitedstatesfirstrelease:"us",unitedkingdom:"uk",southamerica:"br",france:"fr",unitedarabemirates:"ae",germany:"de",sweden:"se",switzerland:"ch",korea:"kr",norway:"no",usgov:"us",usgovhigh:"us",usdod:"us",china:"cn",usnat:"us",ussec:"us",southafrica:"za",singapore:"sg",newzealand:"nz",poland:"pl",qatar:"qa",as:"as",au:"au",ca:"ca",in:"in",jp:"jp",kr:"kr",nz:"nz",ae:"ae",qa:"qa",us:"us",uk:"uk",eu:"eu",de:"de",ch:"ch",no:"no",fr:"fr",se:"se",it:"it",pl:"pl",be:"eu",bel:"eu",gr:"eu",grc:"eu",lt:"eu",ltu:"eu",pt:"eu",prt:"eu",bg:"eu",bgr:"eu",es:"eu",esp:"eu",lu:"eu",lux:"eu",ro:"eu",rou:"eu",cz:"eu",cze:"eu",hu:"eu",hun:"eu",si:"eu",svn:"eu",dk:"eu",dnk:"eu",hr:"eu",hrv:"eu",mt:"eu",mlt:"eu",sk:"eu",svk:"eu",nit:"it",nl:"eu",nld:"eu",fi:"eu",fin:"eu",ee:"eu",est:"eu",cy:"eu",cyp:"eu",at:"eu",aut:"eu",swe:"se",cse:"se",ie:"eu",irl:"eu",lv:"eu",lva:"eu",cpl:"pl",nnz:"nz",cqa:"qa",sg:"sg",br:"br",za:"za",sa:"za"};xde=Sj(Nj())});var Y,Mde,eD=k(()=>{"use strict";Y={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},Mde={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var tD=k(()=>{"use strict";Lf();});var Iu=k(()=>{"use strict";Lf();ZT();eD();tD();});function Ou(e,t){return rD?rD.isOverridden(e,t):{overridden:!1}}var rD,Pu=k(()=>{"use strict";});var z0=k(()=>{"use strict";Iu();Pu();});function _j(e,t){let{region:r}=zi();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Ou(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Tj(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function Tj(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function Dj(e){let t=e.packageName;if($f.has(t)){let r=`settings has already been created for this package ${t}`;throw console.error(r),new Error(r)}if(Object.keys(e.settings).some(r=>H0(t,r))){let r=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.settings).forEach(r=>{if(Object.keys(e.settings[r].values).filter(i=>i!=="default").some(i=>!Ff(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Ru(e){Dj(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:_j(e,r)}}),$f.set(e.packageName,e),Object.defineProperties({},t)}function j0(e,t){return $f.has(e)?!!$f.get(e).settings[t]:!1}var $f,xf=k(()=>{"use strict";Iu();Pu();K0();Lu();$f=new Map});function nD(e,t){let{region:r}=zi();return()=>{let n=Ou(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function Ij(e){let t=e.packageName;if(Mf.has(t)){let r="feature gates has already been created for this package";throw console.error(r),new Error(r)}if(Object.keys(e.features).some(r=>j0(t,r))){let r=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(r),new Error(r)}Object.keys(e.features).forEach(r=>{if(Object.keys(e.features[r].enabledFor).some(i=>!Ff(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function J0(e){Ij(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:nD(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:nD(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Mf.set(e.packageName,e),Object.defineProperties(r,t)}function H0(e,t){return Mf.has(e)?!!Mf.get(e).features[t]:!1}var Mf,K0=k(()=>{"use strict";Iu();Lu();Pu();xf();Mf=new Map});var oD=v((ufe,iD)=>{"use strict";iD.exports=function(t,r){if(r=r.split(":")[0],t=+t,!t)return!1;switch(r){case"http":case"ws":return t!==80;case"https":case"wss":return t!==443;case"ftp":return t!==21;case"gopher":return t!==70;case"file":return!1}return t!==0}});var lD=v(Y0=>{"use strict";var Oj=Object.prototype.hasOwnProperty,Pj;function aD(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function sD(e){try{return encodeURIComponent(e)}catch{return null}}function Rj(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=aD(n[1]),o=aD(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function Lj(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(Oj.call(e,i)){if(n=e[i],!n&&(n===null||n===Pj||isNaN(n))&&(n=""),i=sD(i),n=sD(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}Y0.stringify=Lj;Y0.parse=Rj});var Z0=v((dfe,mD)=>{"use strict";var cD=oD(),Uf=lD(),dD=/[\n\r\t]/g,kj=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,$j=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,xj=/^[a-zA-Z]:/,Fj=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function X0(e){return(e||"").toString().replace(Fj,"")}var Q0=[["#","hash"],["?","query"],function(t,r){return di(r.protocol)?t.replace(/\\/g,"/"):t},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],uD={hash:1,query:1};function fD(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var r=t.location||{};e=e||r;var n={},i=typeof e,o;if(e.protocol==="blob:")n=new fi(unescape(e.pathname),{});else if(i==="string"){n=new fi(e,{});for(o in uD)delete n[o]}else if(i==="object"){for(o in e)o in uD||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=kj.test(e.href))}return n}function di(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function pD(e,t){e=X0(e),e=e.replace(dD,""),t=t||{};var r=$j.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):di(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&di(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||di(n),slashesCount:a,rest:s}}function Mj(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function fi(e,t,r){if(e=X0(e),e=e.replace(dD,""),!(this instanceof fi))return new fi(e,t,r);var n,i,o,a,s,l,u=Q0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Uf.parse),t=fD(t),i=pD(e||"",t),n=!i.protocol&&!i.slashes,d.slashes=i.slashes||n&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||xj.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!di(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[4]&&(d[l]=d[l].toLowerCase())}r&&(d.query=r(d.query)),n&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=Mj(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&di(d.protocol)&&(d.pathname="/"+d.pathname),cD(d.port,d.protocol)||(d.host=d.hostname,d.port=""),d.username=d.password="",d.auth&&(s=d.auth.indexOf(":"),~s?(d.username=d.auth.slice(0,s),d.username=encodeURIComponent(decodeURIComponent(d.username)),d.password=d.auth.slice(s+1),d.password=encodeURIComponent(decodeURIComponent(d.password))):d.username=encodeURIComponent(decodeURIComponent(d.auth)),d.auth=d.password?d.username+":"+d.password:d.username),d.origin=d.protocol!=="file:"&&di(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function Uj(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Uf.parse)(t)),n[e]=t;break;case"port":n[e]=t,cD(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,/:\d+$/.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!r;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";n[e]=t.charAt(0)!==i?i+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<Q0.length;a++){var s=Q0[a];s[4]&&(n[s[1]]=n[s[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin=n.protocol!=="file:"&&di(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function Bj(e){(!e||typeof e!="function")&&(e=Uf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||di(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&di(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}fi.prototype={set:Uj,toString:Bj};fi.extractProtocol=pD;fi.location=fD;fi.trimLeft=X0;fi.qs=Uf;mD.exports=fi});var qj,hD=k(()=>{"use strict";qj=Ce(Z0());});function ey(e,t,r){let n=Object.keys(r).sort();if(n.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return n.length===1?`${i}.${n[0]}`:`${i}.{${n.join(";")}}`}var Bf=k(()=>{"use strict";});var ty,ry,ny=k(()=>{"use strict";Bf();ty=class{features=new Map;register(t,r){let n=ey(r,t.teamName,t.fallback),i={clientName:r,teamName:t.teamName,fullName:n,description:t.description,owners:t.owners,ecsURL:t.ecsURL,createdOn:t.createdOn,fallbackConfig:t.fallback,feature:t,displayTeam:t.displayTeam,tags:t.tags,category:t.category};this.features.set(n,i)}getAll(){return Array.from(this.features.values())}get(t){return this.features.get(t)}has(t){return this.features.has(t)}getByClient(t){return this.getAll().filter(r=>r.clientName===t)}getByTeam(t){return this.getAll().filter(r=>r.teamName===t)}search(t){let r=t.toLowerCase();return this.getAll().filter(n=>n.fullName.toLowerCase().includes(r)||n.description?.toLowerCase().includes(r)||n.teamName.toLowerCase().includes(r)||n.clientName.toLowerCase().includes(r))}getClientNames(){let t=new Set;return this.features.forEach(r=>t.add(r.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(r=>t.add(r.teamName)),Array.from(t)}clear(){this.features.clear()}},ry=new ty});var iy=k(()=>{"use strict";});function Ff(e){return Vj.has(e)}var Vj,Lu=k(()=>{"use strict";z0();K0();xf();Pu();z0();hD();ny();Bf();iy();Vj=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var Gj,gD=k(()=>{"use strict";Lu();Gj=Ru({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var wD,ay,Ms,va,oy,qf,Us,ji,qe,yD,bD,vD,kn=k(()=>{"use strict";wD={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},ay={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(Ms||(Ms={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(va||(va={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(oy||(oy={}));qf=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})(Us||(Us={}));ji=class{static StartTag="<"},qe={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:va.Left,labelPosition:Us.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(yD||(yD={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(bD||(bD={}));(function(e){e.IsHeader="IsHeader",e.IsFooter="IsFooter",e.ContainedInHeader="ContainedInHeader",e.ContainedInFooter="ContainedInFooter",e.NoElementFound="NoElementFound",e.NoTarget="NoTarget",e.CannotAddControlToHeader="CannotAddControlToHeader",e.CannotAddControlToFooter="CannotAddControlToFooter"})(vD||(vD={}))});var sy,CD=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(sy||(sy={}))});var SD,Wj,ED,ape,spe,ku,AD,lpe,upe,ND=k(()=>{"use strict";SD=Ce(ya());dt();Fs();gD();vs();kn();oa();le();Wj=Ce(lo());CD();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(ED||(ED={}));ape={Read:go.Read,Edit:go.Edit,Both:go.Both,Container:go.Container},spe={input:ia.Input,bound:ia.Bound,output:ia.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(ku||(ku={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(AD||(AD={}));lpe=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),upe={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var $n,Vf,_D=k(()=>{"use strict";$n=Ce(ya());vt();dt();rr();Fs();oa();ND();vs();le();kt();kn();Vf=class extends re{constructor(t){super(E.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(Xt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===Xt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Xt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Xt.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.formFactor,t)}async toJSON(t){if(this.id)return null;let r=await this.parametersToJSON(t),n=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(n)?-1:n,Name:this.name,Version:null,Parameters:r,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(ji.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let r=[];if(!this.name)return r;try{let n=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(n)if(n.configurations){let i=n.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:hg.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===ku.dataset?o.get(Xt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===ku.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,$n.trackInfoTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"Custom Control Manifest Property Info not available"}},new Error(`Custom Control Manifest Property Info not available for custom control : ${this.name}.`));else(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===Xt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!Od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Mi.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(mg.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableViewPicker))}}return{Name:t,Usage:l,Static:u,Primary:c,Value:this.getParameterValue(t)}}else{let l=new Error(`No lookup manifest info for ${t}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,$n.trackErrorTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,$n.trackWarningTrace)(hr,{eventName:`${Wi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return Od.includes(t)}isNumberTypeProperty(t,r){return Pd.includes(r)||t.ofTypeGroup.some(n=>Pd.includes(n))}isDataSet(t){return Xt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,ly=k(()=>{"use strict";ee=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var TD={};nn(TD,{CustomControlUniqueId:()=>wa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>ft,mapFieldTypeToControl:()=>zj});function zj(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,wa,ft,$u=k(()=>{"use strict";vt();su();dt();rr();vs();ga();ly();kn();G=class{static get TextBoxControl(){return"4273EDBD-AC1D-40d3-9FB2-095C621B552D"}static get TickerControl(){return"1E1FC551-F7A8-43af-AC34-A8DC35C7B6D4"}static get UrlControl(){return"71716B6C-711E-476c-8AB8-5D11542BFB47"}static get PhoneNumberControl(){return"8C10015A-B339-4982-9474-A95FE05631A5"}static get EmailAddressControl(){return"ADA2203E-B4CD-49be-9DDF-234642B43B52"}static get RadioControl(){return"67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED"}static get LookupControl(){return"270BD3DB-D9AF-4782-9025-509E298DEC0A"}static get DateTimeControl(){return"5B773807-9FB2-42db-97C3-7A91EFF8ADFF"}static get IntegerControl(){return"C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F"}static get MoneyControl(){return"533B9E00-756B-4312-95A0-DC888637AC78"}static get FloatControl(){return"0D2C745A-E5A8-4c8f-BA63-C6D3BB604660"}static get DecimalControl(){return"C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E"}static get TextAreaControl(){return"E0DECE4B-6FC8-4a8f-A065-082708572369"}static get PicklistControl(){return"3EF39988-22BB-4f0b-BBBE-64B5A3748AEE"}static get HiddenInputControl(){return"5546E6CD-394C-4BEE-94A8-4425E17EF6C6"}static get GridControl(){return"E7A81278-8635-4D9E-8D4D-59480B391C5B"}static get CheckBoxControl(){return"B0C6723A-8503-4fd7-BB28-C8A06AC933C2"}static get IframeControl(){return"FD2A7985-3187-444e-908D-6624B21F69C0"}static get SocialInsightControl(){return"86B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get OrgInsightsControl(){return"76B9E25E-695E-4FEF-AC69-F05CFA96739C"}static get DurationControl(){return"AA987274-CE4E-4271-A803-66164311A958"}static get RegardingControl(){return"F3015350-44A2-4aa0-97B5-00166532B5E9"}static get PartyListControl(){return"CBFB742C-14E7-4a17-96BB-1A13F7F64AA2"}static get TimeLineControl(){return"06375649-c143-495e-a496-c962e5b4488e"}static get TimeLineControlUC(){return"06375649-C143-495E-A496-C962E5B4488E"}static get TimeZonePicklistControl(){return"7C624A0B-F59E-493d-9583-638D34759266"}static get LanguagePickerControl(){return"671A9387-CA5A-4d1e-8AB7-06E39DDCF6B5"}static get AccessTeamTablePickerControl(){return"3F4E2A56-F102-4B4D-AB9C-F1574CA5BFDA"}static get KBViewerControl(){return"A62B6FA9-169E-406C-B1AA-EAB828CB6026"}static get PicklistStatusControl(){return"5D68B988-0661-4db2-BC3E-17598AD3BE6C"}static get EmailBodyControl(){return"6F3FB987-393B-4d2d-859F-9D0F0349B6AD"}static get PicklistLookupControl(){return"2305E33A-BAD3-4022-9E15-1856CF218333"}static get RelationshipRolePicklistControl(){return"5F986642-5961-4D9F-AB5E-643D71E231E9"}static get RelatedInformationControl(){return"163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8"}static get CoverPagePicklistControl(){return"4168A05C-D857-46AF-8457-5BB47EB04EA1"}static get MailMergeLanguagePickerControl(){return"B634828E-C390-444A-AFE6-E07315D9D970"}static get ConnectionControl(){return"3246F906-1F71-45F7-B11F-D7BE0F9D04C9"}static get ConnectionRoleObjectTypeListControl(){return"821ACF1A-7E46-4A0C-965D-FE14A57D78C7"}static get MapsControl(){return"62B0DF79-0464-470F-8AF7-4483CFEA0C7D"}static get MapLinkControl(){return"91DC0675-C8B9-4421-B1E0-261CEBF02BAC"}static get WebResourceHtmlControl(){return"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"}static get WebResourceImageControl(){return"587CDF98-C1D5-4BDE-8473-14A0BC7644A7"}static get WebResourceSilverlightControl(){return"080677DB-86EC-4544-AC42-F927E74B491F"}static get ReportControl(){return"A28F441B-916C-4865-87FD-0C5D53BD59C9"}static get ArticleContentControl(){return"F02EF977-2564-4B9A-B2F0-DF083D8A019B"}static get ProcessControl(){return"06E9F7AF-1F54-4681-8EEC-1E21A1CEB465"}static get ActivitiesWallControl(){return"6636847D-B74D-4994-B55A-A6FAF97ECEA2"}static get QuickFormControl(){return"69AF7DCA-2E3B-4EE7-9201-0DA731DD2413"}static get QuickFormCollectionControl(){return"5C5600E0-1D6E-4205-A272-BE80DA87FD42"}static get LinkControl(){return"DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"}static get CompositionLinkControl(){return"DB1284EF-9FFC-4E99-B382-0CC082FE2364"}static get ErrorStatusControl(){return"F4C16ECA-CA81-4E39-9448-834B8378721E"}static get ActivitiesContainerControl(){return"C72511AB-84E5-4FB7-A543-25B4FC01E83E"}static get AccessPrivilegeControl(){return"F93A31B2-99AC-4084-8EC2-D4027C31369A"}static get TimerControl(){return"9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E"}static get DynamicPropertyListControl(){return"6896F004-B17A-4202-861E-8B7EA2080E0B"}static get ButtonControl(){return"00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20"}static get SearchWidgetControl(){return"E616A57F-20E0-4534-8662-A101B5DDF4E0"}static get EmailRecipientActivityControl(){return"26E9760F-7454-40DE-BB07-F6DCCCB82040"}static get LabelControl(){return"39354E4A-5015-4D74-8031-EA9EB73A1322"}static get CustomControl(){return"F9A8A302-114E-466A-B582-6771B2AE0D92"}static get EditFilterControl(){return"1479835F-F852-4679-B864-C6892A2844C9"}static get RichEditorControl(){return"F94DB24F-263D-44A7-B38E-A35E9854812B"}static get PowerBIControl(){return"8C54228C-1B25-4909-A12A-F2B968BB0D62"}static get EmailEngagementActionsControl(){return"F454228D-1D25-4319-E12F-D27968BC0234"}static get ACIControl(){return"C8BFBBEF-6851-4401-A0CC-7450062FE085"}static get ChoicesControl(){return"4AA28AB7-9C13-4F57-A73D-AD894D048B5F"}static get ReferencePanelSubgridControl(){return"02D4264B-47E2-4B4C-AA95-F439F3F4D458"}static get ReferencePanelSearchWidget(){return"7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F"}static get ReferencePanelQuickFormCollectionControl(){return"B68B05F0-A46D-43F8-843B-917920AF806A"}static get SpacerControl(){return"E4BAB03A-A9A5-4C23-CC3B-54AA680150E2"}};wa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},ft=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new dr;static initializeFieldControls(){let t=new dr,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.Text);t.add(O,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Le=e.getControlName($.TwoOptions,"Radio");t.add(Le,new U(G.RadioControl));let lr=e.getControlName($.TwoOptions,"CheckBox");t.add(lr,new U(G.CheckBoxControl));let Ge=e.getControlName($.TwoOptions,"List");t.add(Ge,new U(G.PicklistControl));let Ut=e.getControlName($.State,W.None);t.add(Ut,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let Ke=e.getControlName($.OwnerType,W.None);t.add(Ke,new U(G.LookupControl));let ur=e.getControlName($.PartyListType,W.None);t.add(ur,new U(G.PartyListControl));let Bt=e.getControlName($.LookupType,W.Regarding);t.add(Bt,new U(G.RegardingControl));let Ni=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(Ni,new U(G.ChoicesControl)),t}static getControlName(t,r){return t+"_"+r}static getControlIdByTypeAndFormat(t,r){let n=e.getControlName(t.toString(),r.toString());return e.FieldControlIds.containsKey(n)?e.FieldControlIds.getValue(n):null}static getTypeAndFormatByControlOrUniqueId(t){for(let r in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[r]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[r]}static getControlDataTypeByControlOrUniqueId(t){if(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new dr;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(wa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new dr;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new bs;return t.add(Ms.IFRAME,!0),t.add(Ms.SPACER,!0),t.add(Ms.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(qe.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===wa.RelationshipAssistant||t.guidString===wa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===wa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Gf,DD=k(()=>{"use strict";Gf=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let r=this.listeners.indexOf(t);r>-1&&this.listeners.splice(r,1)}emit(t){this.listeners.forEach(r=>r(t)),this.listenersOncer.forEach(r=>r(t)),this.listenersOncer=[]}pipe(t){return this.on(r=>t.emit(r))}}});var Ca,Bs,ID,OD,Oo,PD,RD,uy=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Ca||(Ca={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Bs||(Bs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(ID||(ID={}));(function(e){e[e.None=0]="None",e[e.Create=1]="Create",e[e.Existing=2]="Existing",e[e.ReadOnly=3]="ReadOnly",e[e.Disabled=4]="Disabled",e[e.BulkEdit=6]="BulkEdit",e[e.Merge=7]="Merge",e[e.Print=8]="Print",e[e.FollowUp=9]="FollowUp"})(OD||(OD={}));(function(e){e[e.None=-1]="None",e[e.AppointmentBook=0]="AppointmentBook",e[e.Hardcoded=1]="Hardcoded",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.Dashboard=5]="Dashboard",e[e.Quick=6]="Quick",e[e.Mobile=7]="Mobile",e[e.Read=8]="Read",e[e.QuickCreate=9]="QuickCreate",e[e.Dialog=10]="Dialog",e[e.Card=11]="Card",e[e.TaskBasedForm=12]="TaskBasedForm",e[e.InteractionCentricDashboard=13]="InteractionCentricDashboard"})(Oo||(Oo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(PD||(PD={}));(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(RD||(RD={}))});var qs,LD=k(()=>{"use strict";Lu();qs=J0({packageName:"cds-designer-models",features:{showAllPCFControls:{owner:"anchoudh",description:"Do not only show the controls that exist on the whitelist",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},showTestControls:{owner:"lucorre",description:"Show advanced custom controls for testing (designated in Authoring Manifest with isTestOnly=true)",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1}},enablePrefetchGetMoreComponentsLocalization:{owner:"vajagarl",description:"Enables prefetching the localization files for controls displayed in custom control picker",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0}},showMapControl:{owner:"vayilavarapu",createdDate:"07/19/2022",description:"Show map control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableFallbackFormTemplate:{owner:"vajagarl",createdDate:"01/03/2023",description:"Enable default form template as fallback if unable to retrieve a form template from Dataverse",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},enableAutoInsertionOfCellInRow:{owner:"debeshd",createdDate:"09/01/2023",description:"Enable the auto insertion of cell in a row when a section is initialized",enabledFor:{test:!1,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableOneGridEvents:{owner:"aansu",createdDate:"08/21/2024",description:"Enable OneGrid events in form designer",enabledFor:{test:!0,preprod:!0,prod:!0,preview:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}},disablePBIComponents:{owner:"adekulkarni",createdDate:"02/13/2025",description:"Disables PBI components and cleans them up from the form",enabledFor:{test:!0,preprod:!1,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableAgentResponse:{owner:"jennietu",createdDate:"04/24/2025",description:"Enables agent response in form designer",enabledFor:{test:!0,preprod:!0,preview:!1,prod:!1,gov:!1,high:!1,dod:!1,mooncake:!1,ex:!1,rx:!1}},enableDelayedLocalizationForCustomControls:{owner:"aansu",createdDate:"06/08/2025",description:"Enables delayed localization of custom control",enabledFor:{test:!0,preprod:!0,preview:!0,prod:!0,gov:!0,high:!0,dod:!0,mooncake:!0,ex:!0,rx:!0}}}})});function kD(e){return{...e,extractConfig:t=>jj(t,Object.keys(e.fallback))}}function jj(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var cy=k(()=>{"use strict";});var dy=v((xpe,xD)=>{var xu=new Proxy(function(){return xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xu},apply:function(){return xu},construct:function(){return{}}}),$D=function(){return xu};Object.setPrototypeOf($D,xu);xD.exports=$D});var UD=v((Fpe,MD)=>{var Fu=new Proxy(function(){return Fu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fu},apply:function(){return Fu},construct:function(){return{}}}),FD=function(){return Fu};Object.setPrototypeOf(FD,Fu);MD.exports=FD});var fy=v((Mpe,qD)=>{var Mu=new Proxy(function(){return Mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Mu},apply:function(){return Mu},construct:function(){return{}}}),BD=function(){return Mu};Object.setPrototypeOf(BD,Mu);qD.exports=BD});var GD=v((Upe,VD)=>{function Hj(){this.__data__=[],this.size=0}VD.exports=Hj});var Vs=v((Bpe,WD)=>{function Kj(e,t){return e===t||e!==e&&t!==t}WD.exports=Kj});var Uu=v((qpe,zD)=>{var Jj=Vs();function Yj(e,t){for(var r=e.length;r--;)if(Jj(e[r][0],t))return r;return-1}zD.exports=Yj});var HD=v((Vpe,jD)=>{var Qj=Uu(),Xj=Array.prototype,Zj=Xj.splice;function e7(e){var t=this.__data__,r=Qj(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Zj.call(t,r,1),--this.size,!0}jD.exports=e7});var JD=v((Gpe,KD)=>{var t7=Uu();function r7(e){var t=this.__data__,r=t7(t,e);return r<0?void 0:t[r][1]}KD.exports=r7});var QD=v((Wpe,YD)=>{var n7=Uu();function i7(e){return n7(this.__data__,e)>-1}YD.exports=i7});var ZD=v((zpe,XD)=>{var o7=Uu();function a7(e,t){var r=this.__data__,n=o7(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}XD.exports=a7});var Bu=v((jpe,eI)=>{var s7=GD(),l7=HD(),u7=JD(),c7=QD(),d7=ZD();function Gs(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Gs.prototype.clear=s7;Gs.prototype.delete=l7;Gs.prototype.get=u7;Gs.prototype.has=c7;Gs.prototype.set=d7;eI.exports=Gs});var rI=v((Hpe,tI)=>{var f7=Bu();function p7(){this.__data__=new f7,this.size=0}tI.exports=p7});var iI=v((Kpe,nI)=>{function m7(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}nI.exports=m7});var aI=v((Jpe,oI)=>{function h7(e){return this.__data__.get(e)}oI.exports=h7});var lI=v((Ype,sI)=>{function g7(e){return this.__data__.has(e)}sI.exports=g7});var py=v((Qpe,uI)=>{var y7=typeof global=="object"&&global&&global.Object===Object&&global;uI.exports=y7});var xn=v((Xpe,cI)=>{var b7=py(),v7=typeof self=="object"&&self&&self.Object===Object&&self,w7=b7||v7||Function("return this")();cI.exports=w7});var qu=v((Zpe,dI)=>{var C7=xn(),E7=C7.Symbol;dI.exports=E7});var hI=v((eme,mI)=>{var fI=qu(),pI=Object.prototype,A7=pI.hasOwnProperty,S7=pI.toString,Vu=fI?fI.toStringTag:void 0;function N7(e){var t=A7.call(e,Vu),r=e[Vu];try{e[Vu]=void 0;var n=!0}catch{}var i=S7.call(e);return n&&(t?e[Vu]=r:delete e[Vu]),i}mI.exports=N7});var yI=v((tme,gI)=>{var _7=Object.prototype,T7=_7.toString;function D7(e){return T7.call(e)}gI.exports=D7});var Ea=v((rme,wI)=>{var bI=qu(),I7=hI(),O7=yI(),P7="[object Null]",R7="[object Undefined]",vI=bI?bI.toStringTag:void 0;function L7(e){return e==null?e===void 0?R7:P7:vI&&vI in Object(e)?I7(e):O7(e)}wI.exports=L7});var Hi=v((nme,CI)=>{function k7(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}CI.exports=k7});var Wf=v((ime,EI)=>{var $7=Ea(),x7=Hi(),F7="[object AsyncFunction]",M7="[object Function]",U7="[object GeneratorFunction]",B7="[object Proxy]";function q7(e){if(!x7(e))return!1;var t=$7(e);return t==M7||t==U7||t==F7||t==B7}EI.exports=q7});var SI=v((ome,AI)=>{var V7=xn(),G7=V7["__core-js_shared__"];AI.exports=G7});var TI=v((ame,_I)=>{var my=SI(),NI=(function(){var e=/[^.]+$/.exec(my&&my.keys&&my.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function W7(e){return!!NI&&NI in e}_I.exports=W7});var hy=v((sme,DI)=>{var z7=Function.prototype,j7=z7.toString;function H7(e){if(e!=null){try{return j7.call(e)}catch{}try{return e+""}catch{}}return""}DI.exports=H7});var OI=v((lme,II)=>{var K7=Wf(),J7=TI(),Y7=Hi(),Q7=hy(),X7=/[\\^$.*+?()[\]{}|]/g,Z7=/^\[object .+?Constructor\]$/,eH=Function.prototype,tH=Object.prototype,rH=eH.toString,nH=tH.hasOwnProperty,iH=RegExp("^"+rH.call(nH).replace(X7,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function oH(e){if(!Y7(e)||J7(e))return!1;var t=K7(e)?iH:Z7;return t.test(Q7(e))}II.exports=oH});var RI=v((ume,PI)=>{function aH(e,t){return e?.[t]}PI.exports=aH});var Po=v((cme,LI)=>{var sH=OI(),lH=RI();function uH(e,t){var r=lH(e,t);return sH(r)?r:void 0}LI.exports=uH});var zf=v((dme,kI)=>{var cH=Po(),dH=xn(),fH=cH(dH,"Map");kI.exports=fH});var Gu=v((fme,$I)=>{var pH=Po(),mH=pH(Object,"create");$I.exports=mH});var MI=v((pme,FI)=>{var xI=Gu();function hH(){this.__data__=xI?xI(null):{},this.size=0}FI.exports=hH});var BI=v((mme,UI)=>{function gH(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}UI.exports=gH});var VI=v((hme,qI)=>{var yH=Gu(),bH="__lodash_hash_undefined__",vH=Object.prototype,wH=vH.hasOwnProperty;function CH(e){var t=this.__data__;if(yH){var r=t[e];return r===bH?void 0:r}return wH.call(t,e)?t[e]:void 0}qI.exports=CH});var WI=v((gme,GI)=>{var EH=Gu(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e){var t=this.__data__;return EH?t[e]!==void 0:SH.call(t,e)}GI.exports=NH});var jI=v((yme,zI)=>{var _H=Gu(),TH="__lodash_hash_undefined__";function DH(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=_H&&t===void 0?TH:t,this}zI.exports=DH});var KI=v((bme,HI)=>{var IH=MI(),OH=BI(),PH=VI(),RH=WI(),LH=jI();function Ws(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Ws.prototype.clear=IH;Ws.prototype.delete=OH;Ws.prototype.get=PH;Ws.prototype.has=RH;Ws.prototype.set=LH;HI.exports=Ws});var QI=v((vme,YI)=>{var JI=KI(),kH=Bu(),$H=zf();function xH(){this.size=0,this.__data__={hash:new JI,map:new($H||kH),string:new JI}}YI.exports=xH});var ZI=v((wme,XI)=>{function FH(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}XI.exports=FH});var Wu=v((Cme,eO)=>{var MH=ZI();function UH(e,t){var r=e.__data__;return MH(t)?r[typeof t=="string"?"string":"hash"]:r.map}eO.exports=UH});var rO=v((Eme,tO)=>{var BH=Wu();function qH(e){var t=BH(this,e).delete(e);return this.size-=t?1:0,t}tO.exports=qH});var iO=v((Ame,nO)=>{var VH=Wu();function GH(e){return VH(this,e).get(e)}nO.exports=GH});var aO=v((Sme,oO)=>{var WH=Wu();function zH(e){return WH(this,e).has(e)}oO.exports=zH});var lO=v((Nme,sO)=>{var jH=Wu();function HH(e,t){var r=jH(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}sO.exports=HH});var jf=v((_me,uO)=>{var KH=QI(),JH=rO(),YH=iO(),QH=aO(),XH=lO();function zs(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}zs.prototype.clear=KH;zs.prototype.delete=JH;zs.prototype.get=YH;zs.prototype.has=QH;zs.prototype.set=XH;uO.exports=zs});var dO=v((Tme,cO)=>{var ZH=Bu(),eK=zf(),tK=jf(),rK=200;function nK(e,t){var r=this.__data__;if(r instanceof ZH){var n=r.__data__;if(!eK||n.length<rK-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new tK(n)}return r.set(e,t),this.size=r.size,this}cO.exports=nK});var gy=v((Dme,fO)=>{var iK=Bu(),oK=rI(),aK=iI(),sK=aI(),lK=lI(),uK=dO();function js(e){var t=this.__data__=new iK(e);this.size=t.size}js.prototype.clear=oK;js.prototype.delete=aK;js.prototype.get=sK;js.prototype.has=lK;js.prototype.set=uK;fO.exports=js});var mO=v((Ime,pO)=>{var cK="__lodash_hash_undefined__";function dK(e){return this.__data__.set(e,cK),this}pO.exports=dK});var gO=v((Ome,hO)=>{function fK(e){return this.__data__.has(e)}hO.exports=fK});var bO=v((Pme,yO)=>{var pK=jf(),mK=mO(),hK=gO();function Hf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new pK;++t<r;)this.add(e[t])}Hf.prototype.add=Hf.prototype.push=mK;Hf.prototype.has=hK;yO.exports=Hf});var wO=v((Rme,vO)=>{function gK(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}vO.exports=gK});var EO=v((Lme,CO)=>{function yK(e,t){return e.has(t)}CO.exports=yK});var yy=v((kme,AO)=>{var bK=bO(),vK=wO(),wK=EO(),CK=1,EK=2;function AK(e,t,r,n,i,o){var a=r&CK,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&EK?new bK:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!vK(t,function(b,w){if(!wK(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}AO.exports=AK});var by=v(($me,SO)=>{var SK=xn(),NK=SK.Uint8Array;SO.exports=NK});var _O=v((xme,NO)=>{function _K(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}NO.exports=_K});var DO=v((Fme,TO)=>{function TK(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}TO.exports=TK});var LO=v((Mme,RO)=>{var IO=qu(),OO=by(),DK=Vs(),IK=yy(),OK=_O(),PK=DO(),RK=1,LK=2,kK="[object Boolean]",$K="[object Date]",xK="[object Error]",FK="[object Map]",MK="[object Number]",UK="[object RegExp]",BK="[object Set]",qK="[object String]",VK="[object Symbol]",GK="[object ArrayBuffer]",WK="[object DataView]",PO=IO?IO.prototype:void 0,vy=PO?PO.valueOf:void 0;function zK(e,t,r,n,i,o,a){switch(r){case WK:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case GK:return!(e.byteLength!=t.byteLength||!o(new OO(e),new OO(t)));case kK:case $K:case MK:return DK(+e,+t);case xK:return e.name==t.name&&e.message==t.message;case UK:case qK:return e==t+"";case FK:var s=OK;case BK:var l=n&RK;if(s||(s=PK),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=LK,a.set(e,t);var c=IK(s(e),s(t),n,i,o,a);return a.delete(e),c;case VK:if(vy)return vy.call(e)==vy.call(t)}return!1}RO.exports=zK});var $O=v((Ume,kO)=>{function jK(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}kO.exports=jK});var Ro=v((Bme,xO)=>{var HK=Array.isArray;xO.exports=HK});var MO=v((qme,FO)=>{var KK=$O(),JK=Ro();function YK(e,t,r){var n=t(e);return JK(e)?n:KK(n,r(e))}FO.exports=YK});var BO=v((Vme,UO)=>{function QK(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}UO.exports=QK});var VO=v((Gme,qO)=>{function XK(){return[]}qO.exports=XK});var zO=v((Wme,WO)=>{var ZK=BO(),eJ=VO(),tJ=Object.prototype,rJ=tJ.propertyIsEnumerable,GO=Object.getOwnPropertySymbols,nJ=GO?function(e){return e==null?[]:(e=Object(e),ZK(GO(e),function(t){return rJ.call(e,t)}))}:eJ;WO.exports=nJ});var HO=v((zme,jO)=>{function iJ(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}jO.exports=iJ});var Lo=v((jme,KO)=>{function oJ(e){return e!=null&&typeof e=="object"}KO.exports=oJ});var YO=v((Hme,JO)=>{var aJ=Ea(),sJ=Lo(),lJ="[object Arguments]";function uJ(e){return sJ(e)&&aJ(e)==lJ}JO.exports=uJ});var wy=v((Kme,ZO)=>{var QO=YO(),cJ=Lo(),XO=Object.prototype,dJ=XO.hasOwnProperty,fJ=XO.propertyIsEnumerable,pJ=QO((function(){return arguments})())?QO:function(e){return cJ(e)&&dJ.call(e,"callee")&&!fJ.call(e,"callee")};ZO.exports=pJ});var tP=v((Jme,eP)=>{function mJ(){return!1}eP.exports=mJ});var Kf=v((zu,Hs)=>{var hJ=xn(),gJ=tP(),iP=typeof zu=="object"&&zu&&!zu.nodeType&&zu,rP=iP&&typeof Hs=="object"&&Hs&&!Hs.nodeType&&Hs,yJ=rP&&rP.exports===iP,nP=yJ?hJ.Buffer:void 0,bJ=nP?nP.isBuffer:void 0,vJ=bJ||gJ;Hs.exports=vJ});var Jf=v((Yme,oP)=>{var wJ=9007199254740991,CJ=/^(?:0|[1-9]\d*)$/;function EJ(e,t){var r=typeof e;return t=t??wJ,!!t&&(r=="number"||r!="symbol"&&CJ.test(e))&&e>-1&&e%1==0&&e<t}oP.exports=EJ});var Cy=v((Qme,aP)=>{var AJ=9007199254740991;function SJ(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=AJ}aP.exports=SJ});var lP=v((Xme,sP)=>{var NJ=Ea(),_J=Cy(),TJ=Lo(),DJ="[object Arguments]",IJ="[object Array]",OJ="[object Boolean]",PJ="[object Date]",RJ="[object Error]",LJ="[object Function]",kJ="[object Map]",$J="[object Number]",xJ="[object Object]",FJ="[object RegExp]",MJ="[object Set]",UJ="[object String]",BJ="[object WeakMap]",qJ="[object ArrayBuffer]",VJ="[object DataView]",GJ="[object Float32Array]",WJ="[object Float64Array]",zJ="[object Int8Array]",jJ="[object Int16Array]",HJ="[object Int32Array]",KJ="[object Uint8Array]",JJ="[object Uint8ClampedArray]",YJ="[object Uint16Array]",QJ="[object Uint32Array]",xe={};xe[GJ]=xe[WJ]=xe[zJ]=xe[jJ]=xe[HJ]=xe[KJ]=xe[JJ]=xe[YJ]=xe[QJ]=!0;xe[DJ]=xe[IJ]=xe[qJ]=xe[OJ]=xe[VJ]=xe[PJ]=xe[RJ]=xe[LJ]=xe[kJ]=xe[$J]=xe[xJ]=xe[FJ]=xe[MJ]=xe[UJ]=xe[BJ]=!1;function XJ(e){return TJ(e)&&_J(e.length)&&!!xe[NJ(e)]}sP.exports=XJ});var cP=v((Zme,uP)=>{function ZJ(e){return function(t){return e(t)}}uP.exports=ZJ});var fP=v((ju,Ks)=>{var eY=py(),dP=typeof ju=="object"&&ju&&!ju.nodeType&&ju,Hu=dP&&typeof Ks=="object"&&Ks&&!Ks.nodeType&&Ks,tY=Hu&&Hu.exports===dP,Ey=tY&&eY.process,rY=(function(){try{var e=Hu&&Hu.require&&Hu.require("util").types;return e||Ey&&Ey.binding&&Ey.binding("util")}catch{}})();Ks.exports=rY});var Yf=v((ehe,hP)=>{var nY=lP(),iY=cP(),pP=fP(),mP=pP&&pP.isTypedArray,oY=mP?iY(mP):nY;hP.exports=oY});var Ay=v((the,gP)=>{var aY=HO(),sY=wy(),lY=Ro(),uY=Kf(),cY=Jf(),dY=Yf(),fY=Object.prototype,pY=fY.hasOwnProperty;function mY(e,t){var r=lY(e),n=!r&&sY(e),i=!r&&!n&&uY(e),o=!r&&!n&&!i&&dY(e),a=r||n||i||o,s=a?aY(e.length,String):[],l=s.length;for(var u in e)(t||pY.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||cY(u,l)))&&s.push(u);return s}gP.exports=mY});var Qf=v((rhe,yP)=>{var hY=Object.prototype;function gY(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||hY;return e===r}yP.exports=gY});var Sy=v((nhe,bP)=>{function yY(e,t){return function(r){return e(t(r))}}bP.exports=yY});var wP=v((ihe,vP)=>{var bY=Sy(),vY=bY(Object.keys,Object);vP.exports=vY});var EP=v((ohe,CP)=>{var wY=Qf(),CY=wP(),EY=Object.prototype,AY=EY.hasOwnProperty;function SY(e){if(!wY(e))return CY(e);var t=[];for(var r in Object(e))AY.call(e,r)&&r!="constructor"&&t.push(r);return t}CP.exports=SY});var Ku=v((ahe,AP)=>{var NY=Wf(),_Y=Cy();function TY(e){return e!=null&&_Y(e.length)&&!NY(e)}AP.exports=TY});var NP=v((she,SP)=>{var DY=Ay(),IY=EP(),OY=Ku();function PY(e){return OY(e)?DY(e):IY(e)}SP.exports=PY});var TP=v((lhe,_P)=>{var RY=MO(),LY=zO(),kY=NP();function $Y(e){return RY(e,kY,LY)}_P.exports=$Y});var OP=v((uhe,IP)=>{var DP=TP(),xY=1,FY=Object.prototype,MY=FY.hasOwnProperty;function UY(e,t,r,n,i,o){var a=r&xY,s=DP(e),l=s.length,u=DP(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:MY.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var C=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(C===void 0?b===w||i(b,w,r,n,o):C)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,O=t.constructor;S!=O&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof O=="function"&&O instanceof O)&&(h=!1)}return o.delete(e),o.delete(t),h}IP.exports=UY});var RP=v((che,PP)=>{var BY=Po(),qY=xn(),VY=BY(qY,"DataView");PP.exports=VY});var kP=v((dhe,LP)=>{var GY=Po(),WY=xn(),zY=GY(WY,"Promise");LP.exports=zY});var xP=v((fhe,$P)=>{var jY=Po(),HY=xn(),KY=jY(HY,"Set");$P.exports=KY});var MP=v((phe,FP)=>{var JY=Po(),YY=xn(),QY=JY(YY,"WeakMap");FP.exports=QY});var jP=v((mhe,zP)=>{var Ny=RP(),_y=zf(),Ty=kP(),Dy=xP(),Iy=MP(),WP=Ea(),Js=hy(),UP="[object Map]",XY="[object Object]",BP="[object Promise]",qP="[object Set]",VP="[object WeakMap]",GP="[object DataView]",ZY=Js(Ny),eQ=Js(_y),tQ=Js(Ty),rQ=Js(Dy),nQ=Js(Iy),Aa=WP;(Ny&&Aa(new Ny(new ArrayBuffer(1)))!=GP||_y&&Aa(new _y)!=UP||Ty&&Aa(Ty.resolve())!=BP||Dy&&Aa(new Dy)!=qP||Iy&&Aa(new Iy)!=VP)&&(Aa=function(e){var t=WP(e),r=t==XY?e.constructor:void 0,n=r?Js(r):"";if(n)switch(n){case ZY:return GP;case eQ:return UP;case tQ:return BP;case rQ:return qP;case nQ:return VP}return t});zP.exports=Aa});var eR=v((hhe,ZP)=>{var Oy=gy(),iQ=yy(),oQ=LO(),aQ=OP(),HP=jP(),KP=Ro(),JP=Kf(),sQ=Yf(),lQ=1,YP="[object Arguments]",QP="[object Array]",Xf="[object Object]",uQ=Object.prototype,XP=uQ.hasOwnProperty;function cQ(e,t,r,n,i,o){var a=KP(e),s=KP(t),l=a?QP:HP(e),u=s?QP:HP(t);l=l==YP?Xf:l,u=u==YP?Xf:u;var c=l==Xf,d=u==Xf,f=l==u;if(f&&JP(e)){if(!JP(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new Oy),a||sQ(e)?iQ(e,t,r,n,i,o):oQ(e,t,l,r,n,i,o);if(!(r&lQ)){var m=c&&XP.call(e,"__wrapped__"),p=d&&XP.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new Oy),i(h,g,r,n,o)}}return f?(o||(o=new Oy),aQ(e,t,r,n,i,o)):!1}ZP.exports=cQ});var iR=v((ghe,nR)=>{var dQ=eR(),tR=Lo();function rR(e,t,r,n,i){return e===t?!0:e==null||t==null||!tR(e)&&!tR(t)?e!==e&&t!==t:dQ(e,t,r,n,rR,i)}nR.exports=rR});var aR=v((yhe,oR)=>{var fQ=iR();function pQ(e,t){return fQ(e,t)}oR.exports=pQ});var Py=v((bhe,sR)=>{var mQ=Po(),hQ=(function(){try{var e=mQ(Object,"defineProperty");return e({},"",{}),e}catch{}})();sR.exports=hQ});var Zf=v((vhe,uR)=>{var lR=Py();function gQ(e,t,r){t=="__proto__"&&lR?lR(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}uR.exports=gQ});var Ry=v((whe,cR)=>{var yQ=Zf(),bQ=Vs();function vQ(e,t,r){(r!==void 0&&!bQ(e[t],r)||r===void 0&&!(t in e))&&yQ(e,t,r)}cR.exports=vQ});var fR=v((Che,dR)=>{function wQ(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}dR.exports=wQ});var mR=v((Ehe,pR)=>{var CQ=fR(),EQ=CQ();pR.exports=EQ});var vR=v((Ju,Ys)=>{var AQ=xn(),bR=typeof Ju=="object"&&Ju&&!Ju.nodeType&&Ju,hR=bR&&typeof Ys=="object"&&Ys&&!Ys.nodeType&&Ys,SQ=hR&&hR.exports===bR,gR=SQ?AQ.Buffer:void 0,yR=gR?gR.allocUnsafe:void 0;function NQ(e,t){if(t)return e.slice();var r=e.length,n=yR?yR(r):new e.constructor(r);return e.copy(n),n}Ys.exports=NQ});var ER=v((Ahe,CR)=>{var wR=by();function _Q(e){var t=new e.constructor(e.byteLength);return new wR(t).set(new wR(e)),t}CR.exports=_Q});var SR=v((She,AR)=>{var TQ=ER();function DQ(e,t){var r=t?TQ(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}AR.exports=DQ});var _R=v((Nhe,NR)=>{function IQ(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}NR.exports=IQ});var IR=v((_he,DR)=>{var OQ=Hi(),TR=Object.create,PQ=(function(){function e(){}return function(t){if(!OQ(t))return{};if(TR)return TR(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();DR.exports=PQ});var Ly=v((The,OR)=>{var RQ=Sy(),LQ=RQ(Object.getPrototypeOf,Object);OR.exports=LQ});var RR=v((Dhe,PR)=>{var kQ=IR(),$Q=Ly(),xQ=Qf();function FQ(e){return typeof e.constructor=="function"&&!xQ(e)?kQ($Q(e)):{}}PR.exports=FQ});var kR=v((Ihe,LR)=>{var MQ=Ku(),UQ=Lo();function BQ(e){return UQ(e)&&MQ(e)}LR.exports=BQ});var FR=v((Ohe,xR)=>{var qQ=Ea(),VQ=Ly(),GQ=Lo(),WQ="[object Object]",zQ=Function.prototype,jQ=Object.prototype,$R=zQ.toString,HQ=jQ.hasOwnProperty,KQ=$R.call(Object);function JQ(e){if(!GQ(e)||qQ(e)!=WQ)return!1;var t=VQ(e);if(t===null)return!0;var r=HQ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&$R.call(r)==KQ}xR.exports=JQ});var ky=v((Phe,MR)=>{function YQ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}MR.exports=YQ});var $y=v((Rhe,UR)=>{var QQ=Zf(),XQ=Vs(),ZQ=Object.prototype,eX=ZQ.hasOwnProperty;function tX(e,t,r){var n=e[t];(!(eX.call(e,t)&&XQ(n,r))||r===void 0&&!(t in e))&&QQ(e,t,r)}UR.exports=tX});var qR=v((Lhe,BR)=>{var rX=$y(),nX=Zf();function iX(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?nX(r,s,l):rX(r,s,l)}return r}BR.exports=iX});var GR=v((khe,VR)=>{function oX(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}VR.exports=oX});var zR=v(($he,WR)=>{var aX=Hi(),sX=Qf(),lX=GR(),uX=Object.prototype,cX=uX.hasOwnProperty;function dX(e){if(!aX(e))return lX(e);var t=sX(e),r=[];for(var n in e)n=="constructor"&&(t||!cX.call(e,n))||r.push(n);return r}WR.exports=dX});var xy=v((xhe,jR)=>{var fX=Ay(),pX=zR(),mX=Ku();function hX(e){return mX(e)?fX(e,!0):pX(e)}jR.exports=hX});var KR=v((Fhe,HR)=>{var gX=qR(),yX=xy();function bX(e){return gX(e,yX(e))}HR.exports=bX});var e2=v((Mhe,ZR)=>{var JR=Ry(),vX=vR(),wX=SR(),CX=_R(),EX=RR(),YR=wy(),QR=Ro(),AX=kR(),SX=Kf(),NX=Wf(),_X=Hi(),TX=FR(),DX=Yf(),XR=ky(),IX=KR();function OX(e,t,r,n,i,o,a){var s=XR(e,r),l=XR(t,r),u=a.get(l);if(u){JR(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=QR(l),m=!f&&SX(l),p=!f&&!m&&DX(l);c=l,f||m||p?QR(s)?c=s:AX(s)?c=CX(s):m?(d=!1,c=vX(l,!0)):p?(d=!1,c=wX(l,!0)):c=[]:TX(l)||YR(l)?(c=s,YR(s)?c=IX(s):(!_X(s)||NX(s))&&(c=EX(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),JR(e,r,c)}ZR.exports=OX});var Fy=v((Uhe,r2)=>{var PX=gy(),RX=Ry(),LX=mR(),kX=e2(),$X=Hi(),xX=xy(),FX=ky();function t2(e,t,r,n,i){e!==t&&LX(t,function(o,a){if(i||(i=new PX),$X(o))kX(e,t,a,r,t2,n,i);else{var s=n?n(FX(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),RX(e,a,s)}},xX)}r2.exports=t2});var My=v((Bhe,n2)=>{function MX(e){return e}n2.exports=MX});var o2=v((qhe,i2)=>{function UX(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}i2.exports=UX});var l2=v((Vhe,s2)=>{var BX=o2(),a2=Math.max;function qX(e,t,r){return t=a2(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=a2(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),BX(e,this,s)}}s2.exports=qX});var c2=v((Ghe,u2)=>{function VX(e){return function(){return e}}u2.exports=VX});var p2=v((Whe,f2)=>{var GX=c2(),d2=Py(),WX=My(),zX=d2?function(e,t){return d2(e,"toString",{configurable:!0,enumerable:!1,value:GX(t),writable:!0})}:WX;f2.exports=zX});var h2=v((zhe,m2)=>{var jX=800,HX=16,KX=Date.now;function JX(e){var t=0,r=0;return function(){var n=KX(),i=HX-(n-r);if(r=n,i>0){if(++t>=jX)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}m2.exports=JX});var y2=v((jhe,g2)=>{var YX=p2(),QX=h2(),XX=QX(YX);g2.exports=XX});var v2=v((Hhe,b2)=>{var ZX=My(),eZ=l2(),tZ=y2();function rZ(e,t){return tZ(eZ(e,t,ZX),e+"")}b2.exports=rZ});var C2=v((Khe,w2)=>{var nZ=Vs(),iZ=Ku(),oZ=Jf(),aZ=Hi();function sZ(e,t,r){if(!aZ(r))return!1;var n=typeof t;return(n=="number"?iZ(r)&&oZ(t,r.length):n=="string"&&t in r)?nZ(r[t],e):!1}w2.exports=sZ});var Uy=v((Jhe,E2)=>{var lZ=v2(),uZ=C2();function cZ(e){return lZ(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&uZ(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}E2.exports=cZ});var S2=v((Yhe,A2)=>{var dZ=Fy(),fZ=Uy(),pZ=fZ(function(e,t,r,n){dZ(e,t,r,n)});A2.exports=pZ});var gn,Yu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(gn||(gn={}))});function _2(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${N2.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var N2,mZ,T2=k(()=>{"use strict";N2=Ce(fy()),mZ=Ce(dy());});var By,D2=k(()=>{"use strict";xf();By=Ru({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var O2,P2,R2,L2,qy,hZ,ep,I2,Vy=k(()=>{"use strict";O2=Ce(dy()),P2=Ce(UD()),R2=Ce(fy()),L2=Ce(aR()),qy=Ce(S2());Yu();T2();D2();hZ=60*1e3,ep=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=gn.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,r,n="PROD"){this.clientName=t,this.logger=r,this.endpointType=n,this.ecsEndpoint=n==="PROD"?By.prodEcsEndpoint:By.integrationEcsEndpoint}client=new P2.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=O2.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(async()=>{let s=await r();return this.logEvent("FeaturesClient/configRequested",{ecsClientName:this.clientName,filters:s}),s});try{await this.client.initialize({clientName:this.clientName,clientVersion:t??"1.0.0.0",configsToFetch:[R2.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:_2(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===gn.NotLoaded&&(this._status=gn.Initialized)}catch(s){this._status=gn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*hZ)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,qy.default)({},t.fallback,n,t.override,I2)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,r)=>{let n=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,L2.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,n]),clearTimeout(r)}else await this.loadingPromise};overrideClientConfig(t){this.logger.logEvent("FeaturesClient/overrideClientConfig",{clientConfigOverride:t}),this.clientConfigOverride=t}undoClientConfigOverride(){this.clientConfigOverride=void 0,this.logger.logEvent("FeaturesClient/undoClientConfigOverride")}getMergedClientConfig=()=>(0,qy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,I2);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=gn.ConfigsLoaded;let{ConfigIDs:r,Headers:n}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:r,ETag:n?.ETag})};logEvent=(t,r)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...r})}},I2=(e,t)=>{if(Array.isArray(t))return t}});var $2=v((oge,k2)=>{"use strict";var gZ=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};k2.exports=gZ});var Gy=v((age,F2)=>{var Qu=new Proxy(function(){return Qu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Qu},apply:function(){return Qu},construct:function(){return{}}}),x2=function(){return Qu};Object.setPrototypeOf(x2,Qu);F2.exports=x2});var B2=v((sge,U2)=>{var Xu=new Proxy(function(){return Xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Xu},apply:function(){return Xu},construct:function(){return{}}}),M2=function(){return Xu};Object.setPrototypeOf(M2,Xu);U2.exports=M2});var H2=v((lge,j2)=>{"use strict";var Wy=B2(),yZ={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},bZ={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},vZ={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},W2={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},zy={};zy[Wy.ForwardRef]=vZ;zy[Wy.Memo]=W2;function q2(e){return Wy.isMemo(e)?W2:zy[e.$$typeof]||yZ}var wZ=Object.defineProperty,CZ=Object.getOwnPropertyNames,V2=Object.getOwnPropertySymbols,EZ=Object.getOwnPropertyDescriptor,AZ=Object.getPrototypeOf,G2=Object.prototype;function z2(e,t,r){if(typeof t!="string"){if(G2){var n=AZ(t);n&&n!==G2&&z2(e,n,r)}var i=CZ(t);V2&&(i=i.concat(V2(t)));for(var o=q2(e),a=q2(t),s=0;s<i.length;++s){var l=i[s];if(!bZ[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=EZ(t,l);try{wZ(e,l,u)}catch{}}}}return e}j2.exports=z2});function J2(e,t,r){let[n,i]=(0,Qs.useState)(e.getConfig(t));return(0,Qs.useEffect)(()=>{if(!r?.subscribe&&e.status===gn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function Y2(e){return function(t,r){return J2(e,t,r)}}function Q2(e,t,r,n){let i=o=>{let a=J2(e,t,n),s={...o,...a};return Qs.default.createElement(r,{...s})};return(0,K2.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function X2(e,t,r,n){return t.reduce((i,o)=>Q2(e,o,i,n),r)}function Z2(e){return function(t,r,n){return Q2(e,t,r,n)}}var K2,Qs,jy=k(()=>{"use strict";K2=Ce(H2()),Qs=Ce(Gy());Yu();});var t1=v((dge,e1)=>{var SZ=Fy(),NZ=Uy(),_Z=NZ(function(e,t,r){SZ(e,t,r)});e1.exports=_Z});var tp=v((fge,r1)=>{var TZ=Ea(),DZ=Lo(),IZ="[object Symbol]";function OZ(e){return typeof e=="symbol"||DZ(e)&&TZ(e)==IZ}r1.exports=OZ});var i1=v((pge,n1)=>{var PZ=Ro(),RZ=tp(),LZ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,kZ=/^\w*$/;function $Z(e,t){if(PZ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||RZ(e)?!0:kZ.test(e)||!LZ.test(e)||t!=null&&e in Object(t)}n1.exports=$Z});var s1=v((mge,a1)=>{var o1=jf(),xZ="Expected a function";function Hy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(xZ);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Hy.Cache||o1),r}Hy.Cache=o1;a1.exports=Hy});var u1=v((hge,l1)=>{var FZ=s1(),MZ=500;function UZ(e){var t=FZ(e,function(n){return r.size===MZ&&r.clear(),n}),r=t.cache;return t}l1.exports=UZ});var d1=v((gge,c1)=>{var BZ=u1(),qZ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,VZ=/\\(\\)?/g,GZ=BZ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(qZ,function(r,n,i,o){t.push(i?o.replace(VZ,"$1"):n||r)}),t});c1.exports=GZ});var p1=v((yge,f1)=>{function WZ(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}f1.exports=WZ});var v1=v((bge,b1)=>{var m1=qu(),zZ=p1(),jZ=Ro(),HZ=tp(),KZ=1/0,h1=m1?m1.prototype:void 0,g1=h1?h1.toString:void 0;function y1(e){if(typeof e=="string")return e;if(jZ(e))return zZ(e,y1)+"";if(HZ(e))return g1?g1.call(e):"";var t=e+"";return t=="0"&&1/e==-KZ?"-0":t}b1.exports=y1});var C1=v((vge,w1)=>{var JZ=v1();function YZ(e){return e==null?"":JZ(e)}w1.exports=YZ});var A1=v((wge,E1)=>{var QZ=Ro(),XZ=i1(),ZZ=d1(),eee=C1();function tee(e,t){return QZ(e)?e:XZ(e,t)?[e]:ZZ(eee(e))}E1.exports=tee});var N1=v((Cge,S1)=>{var ree=tp(),nee=1/0;function iee(e){if(typeof e=="string"||ree(e))return e;var t=e+"";return t=="0"&&1/e==-nee?"-0":t}S1.exports=iee});var D1=v((Ege,T1)=>{var oee=$y(),aee=A1(),see=Jf(),_1=Hi(),lee=N1();function uee(e,t,r,n){if(!_1(e))return e;t=aee(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=lee(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=_1(c)?c:see(t[i+1])?[]:{})}oee(s,l,u),s=s[l]}return e}T1.exports=uee});var O1=v((Age,I1)=>{var cee=D1();function dee(e,t,r){return e==null?e:cee(e,t,r)}I1.exports=dee});function k1(e){let{query:t}=(0,L1.default)(window.location.href,!0);return pee(e,t),e}function pee(e,t){let r=fee+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+$1,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,R1.default)(u,c,s)}(0,P1.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var P1,R1,L1,$1,fee,x1=k(()=>{"use strict";P1=Ce(t1()),R1=Ce(O1()),L1=Ce(Z0());$1=".",fee="ecs"+$1});function np(e,t,r){let n=k1(new ep(e,t,r));function i(o){(0,rp.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:hee(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>X2(n,o,a,s)}}function hee(e){let t=Y2(e),r=Z2(e);return function(i){let o=kD(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===gn.ConfigsLoaded,ry.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var mee,rp,Ky=k(()=>{"use strict";mee=Ce($2()),rp=Ce(Gy());cy();Vy();Yu();jy();x1();ny();});var F1=k(()=>{"use strict";cy();Vy();Ky();Yu();jy();Bf();iy();});function ip(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Xs.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Xs.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Xs.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Xs,Jy=k(()=>{"use strict";Xs=Ce(ya());});var Gge,Wge,zge,M1=k(()=>{"use strict";F1();Jy();({featuresClient:Gge,createFeature:Wge,useFeaturesClientInitParams:zge}=np("PowerApps-Shell-Test",ip("shell-features")))});var q1=v((Hge,B1)=>{var Zu=new Proxy(function(){return Zu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Zu},apply:function(){return Zu},construct:function(){return{}}}),U1=function(){return Zu};Object.setPrototypeOf(U1,Zu);B1.exports=U1});var gee,yee,V1=k(()=>{"use strict";Iu();gee=Ce(q1()),yee=Ce(ya());});var G1=k(()=>{"use strict";M1();Jy();V1();});var r0e,Zs,n0e,W1=k(()=>{"use strict";G1();Ky();({featuresClient:r0e,createFeature:Zs,useFeaturesClientInitParams:n0e}=np("PowerApps-MakerPortal",ip("powerapps-features")))});var z1,j1,s0e,l0e,u0e,c0e,Yy=k(()=>{"use strict";LD();W1();({feature:z1}=Zs({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:qs.enableAutoInsertionOfCellInRow}})),{feature:j1}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:qs.enableOneGridEvents}}),{feature:s0e}=Zs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:qs.disablePBIComponents}}),{feature:l0e}=Zs({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:qs.enableAgentResponse}}),{feature:u0e,useFeature:c0e}=Zs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:qs.enableDelayedLocalizationForCustomControls}})});var J1=v((f0e,K1)=>{var ec=new Proxy(function(){return ec},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ec},apply:function(){return ec},construct:function(){return{}}}),H1=function(){return ec};Object.setPrototypeOf(H1,ec);K1.exports=H1});var nr,ko=k(()=>{"use strict";vt();dt();rr();$u();le();kt();nr=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(E.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(E.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(E.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(E.formControl);if(t&&t.ClassId){let r=ft.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&ft.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===E.formSection||this.NodeName===E.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(E.formControl);if(t){let n=ft.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(E.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(E.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var el,Qy=k(()=>{"use strict";rr();le();kt();el=class extends re{constructor(t,r){super(E.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var Y1,tl,Xy=k(()=>{"use strict";dt();Qy();le();kt();ko();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(Y1||(Y1={}));tl=class extends nr{constructor(t,r){super(E.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(E.EventHandlers);return t&&t.length?t[0].getChildren(E.handler):[]}getAllDependencies(){let t=this.getChildren(E.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(E.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(E.formDependencies,this)),r=this.getFirstChild(E.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new el(r,n.toString()))}}}});var Fn,tc=k(()=>{"use strict";vt();su();dt();ga();le();kt();kn();Fn=class extends re{previewVersion;constructor(t){super(E.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new dr,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(ji.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(E.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let r=this.parametersNode.findFirst(n=>n&&n.getNodeName()===t);if(r){let n=r.getAllChildren(),i=n&&n.length>0&&n[0];if(i){let o=i.getNodeName();return o.charAt(0)===ji.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new dr;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===wt.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:n,ControlLayout:0,RequiredLevel:0,Type:this.getAttributeTypeFromClassId(this.ClassId.guidString),IsUnbound:this.getIsUnbound(),IsRequired:this.isRequired,DataFieldName:this.dataFieldName,UniqueId:this.UniqueId&&this.UniqueId.guidString,Id:this.previewVersion?this.id+this.previewVersion:this.id,Label:r.getDisplayName(t.langCode),LabelId:r.labelId&&r.labelId.guidString,Name:null,ShowLabel:r.showlabel,PreviewId:r&&r.id.guidString,Visible:r.visible||t.formModelService.showHiddenElements}}}});var rl,Zy=k(()=>{"use strict";rr();oa();tc();le();kt();rl=class extends Fn{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case hn.Chart:return hn.Chart;case hn.Grid:return hn.Grid;default:return hn.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=hn.Chart:this.chartGridMode=this.enableChartPicker?hn.All:hn.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,n));break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.dataset)?n[i].getParameters().get(Xt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var nl,eb=k(()=>{"use strict";rr();oa();tc();le();nl=class extends Fn{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.AutoResolve:n.getAllChildren()[0].setNodeName("<"+r.autoResolve);break;default:break}}updateControlDescription(t){let r=t.getControlDescriptionByForControl(this.UniqueId);if(r){let n=r.customControls;for(let i=0;i<n.length;i++){let o=n[i].getParameters().get(Xt.value)?n[i].getParameters().get(Xt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Q1,tb,kr,rc=k(()=>{"use strict";Q1=Ce(J1());ko();le();dt();vt();Xy();tc();$u();ly();G0();kn();ga();Fs();Zy();eb();rb();vs();tb="_",kr=class e extends nr{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(E.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof Fn?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!ba.dependencyFieldCount.containsKey(this.control.id):!ba.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new tl(this,Tu.onLoad))}get dependencies(){let t=this.getChildren(E.formEvents);for(let r of t){let n=r.getChildren(E.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Pf[i])o=Pf[i].replace(/ /g,tb)+tb;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,Q1.trackErrorTrace)(hr,{eventName:`${JT}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===yn.Grid?(l=new rl(this),l.indicationOfSubgrid=!0):o===yn.Lookup?l=new nl(this):l=new Fn(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=ft.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(ft.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!ft.isUnboundFormControlByIdentifier(d)?o!==yn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=ft.GetRowSpan(l),(ft.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||ft.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(ft.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||ft.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||ft.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===E.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(E.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(ay.ONE_COLUMN),n=Number(ay.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(E.formRow)}getParentSection(){return this.getAncestor(E.formSection)}getParentTab(){return this.getAncestor(E.formTab)}getParentForm(){return this.getAncestor(E.form)}isInHeader(){let t=this.getAncestor(E.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(E.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(E.formHeader):this.isInFooter()?this.getAncestor(E.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.FOUR_COLUMN:r="1111";break;default:r="1"}return r}findRowIndexByCellId(t){let r=this.getParentRow().cells.indexOf(this);for(let n=0;n<t.rows.length;n++)if(!R.IsNullOrUndefined(t.rows[n].cells[r])&&this.id.ToString()===t.rows[n].cells[r].id.ToString())return n;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();R.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,r,n){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||r().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===yo.ApplicationRequired||a===yo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?yo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??yo.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===E.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===E.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===tb&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var il,nb=k(()=>{"use strict";rr();le();kt();il=class extends re{isInternal;constructor(t,r,n,i){super(E.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var Sa,ib=k(()=>{"use strict";dt();rc();le();kt();Sa=class extends re{isRowAddedOnDragOver;constructor(t){super(E.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(E.formSection)}insertPaddingCellAtIndex(t){let r=new kr(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(E.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function bee(e){switch(e){case va.Left:return Ca.Left;case va.Right:return Ca.Right;case va.Center:return Ca.Center;default:return Ca.Left}}function vee(e){switch(e){case Us.Left:return Bs.Left;case Us.Top:return Bs.Top;default:return Bs.Left}}function X1(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var wee,pi,nc=k(()=>{"use strict";uy();vt();dt();rr();Yy();rc();le();kn();ko();ib();wee=115,pi=class e extends nr{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=je.ONE_COLUMN;break;case 11:t=je.TWO_COLUMN;break;case 111:t=je.THREE_COLUMN;break;case 1111:t=je.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=qe.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+qe.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===je.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${qe.referencePanelNamePrefix}${U.NewGuid()}${qe.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,qe.IsUserDefined),this.addProperty(y.locklevel,qe.LockLevel),this.addProperty(y.showlabel,qe.ShowLabel),this.addProperty(y.showbar,qe.ShowBar),this.addProperty(y.layout,qe.Layout),this.addProperty(y.Fieldlabelalignment,qe.labelAlignment),this.addProperty(y.Fieldlabelposition,qe.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,qe.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,qe.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.FOUR_COLUMN:r="1111";break;default:r="1"}return r}getNumberOfColumns(){return e.getNumericColumnLayoutValue(this.columns)}static getNumericColumnLayoutValue(t){switch(t){case 1:return 1;case 11:return 2;case 111:return 3;case 1111:return 4;default:throw new Error("Unexpected Section Layout Value.")}}getColumnCountValue(){let t=0;return R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Sa(null);if(this.addGrandChild(E.formRows,r),z1.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new kr(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===je.REFERENCE_PANEL&&(n=je.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(E.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(E.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(E.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(E.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(E.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(E.formRows);return t.length===0?[]:t[0].getChildren(E.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return X1(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(E.formColumn)}getParentTab(){return this.getAncestor(E.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=qe.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?qe.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?wee:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.LabelWidth,t.toString())}async getRowsJSON(t){let r=[],n=[];if(this.rows){for(let i of this.rows)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this.id&&this.id.guidString,Rows:await this.getRowsJSON(t),CellLabel:{Width:this.labelwidth,Alignment:bee(this.fieldLabelAlignment),Position:vee(this.fieldLabelPosition)},Columns:X1(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===E.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(qe.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===E.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===E.formFooter||this.NodeName===E.formHeader}}});var $o,op=k(()=>{"use strict";le();kt();nc();$o=class e extends re{constructor(t){super(E.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new pi(E.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}initialize(t,r,n,i=je.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(E.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(E.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(E.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var ap,Z1=k(()=>{"use strict";vt();le();kn();nc();ap=class extends pi{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,qe.columns),this.setDisplayName(r,t)}}});var sp,eL=k(()=>{"use strict";op();le();Z1();sp=class extends $o{addAndIntializeNavBarSection(t,r,n,i){let o=new ap(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var Ki,lp=k(()=>{"use strict";vt();dt();rr();op();le();kt();ko();Ki=class extends nr{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(E.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(E.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=ze.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=ze.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=ze.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=ze.TWO_COLUMN_WIDER_RIGHT;break}t=ze.TWO_COLUMN_CUSTOM_LAYOUT;break;case 3:if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===33&&parseInt(this.columns[2].width,10)===33){t=ze.THREE_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===28&&parseInt(this.columns[1].width,10)===44&&parseInt(this.columns[2].width,10)===28){t=ze.THREE_COLUMN_WIDER_MID;break}t=ze.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,Io.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Io.IsUserDefined),this.addProperty(y.locklevel,Io.LockLevel),this.addProperty(y.showlabel,Io.ShowLabel),this.setDisplayName(n,r)}get TotalSectionsCount(){let t=0;for(let r of this.columns)t+=r.sections.length;return t}initializeColumns(t,r,n,i=je.ONE_COLUMN,o=!0,a){let s=this.getChildren(E.formColumns)[0],l=[];switch(t){case ze.ONE_COLUMN:l.push(100);break;case ze.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case ze.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case ze.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case ze.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case ze.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new $o(s);c.initialize(u,r,n,i),this.addGrandChild(E.formColumns,c)}}initialize(t,r,n,i,o,a=je.ONE_COLUMN,s=!0,l){this.addChild(new re(E.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(E.formColumns);return t.length!==1?[]:t[0].getChildren(E.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(E.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(E.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(E.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===E.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Na,ob=k(()=>{"use strict";vt();le();kt();kn();eL();lp();Na=class extends Ki{constructor(t,r,n){super(t,ze.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(E.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(E.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<qf.FIVE_COLUMN;t++){let r=new sp(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(wD.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function Eee(e){switch(e){case wt.Main:return Oo.Main;case wt.QuickCreate:return Oo.QuickCreate;case wt.QuickViewForm:return Oo.Quick;case wt.Dialog:return Oo.Dialog;default:return Oo.None}}function Aee(e,t){if(t===wt.Main){if(e)switch(e.toLowerCase()){case"low":return Do.Low;case"highreadonlyvalues":return Do.HighReadOnlyValues;default:return Do.HighWithControls}return Do.Low}}var cp,Cee,up,tL=k(()=>{"use strict";DD();cp=Ce(ya());uy();dt();rr();Fs();Yy();le();oa();O0();ga();rc();le();ko();nb();ob();lp();Cee="1920";up=class e extends nr{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(E.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Tf,this._metadataChangeEvent=new Gf}get FormLibraries(){let t=this.getFirstChild(E.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof kr).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let r=t.events;return r?r.filter(n=>!n.control&&!n.attribute):null}else if(t instanceof kr){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===E.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new il(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,cp.trackErrorTrace)(YT,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:n.attribute,EventName:n.eventName}}),i}}),r}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?Cee:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===wt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==wt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===wt.Main||this.formType===wt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(E.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(E.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(E.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(E.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new Ki(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new Ki(null,ze.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(ze.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(E.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===Io.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(E.formTabs);return t.length!==1?[]:t[0].getChildren(E.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Na)return t}return null}get NavigationNode(){let t=this.getChildren(E.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(E.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(E.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(E.formFooter).length>0}get displayCondition(){let t=this.getChildren(E.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(E.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(E.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(E.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(E.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof kr))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof kr&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Mi.EditableGridControl)||j1.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Mi.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Mi.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===E.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof Na)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let r=[];for(let n of this.ControlDescriptions){let i=await n.toJSON(t);i&&r.push(i)}return r}async toJSON(t){let r=[];r=await this.getControlDescriptionsToJSON(t);let n=this.NavigationNode&&await this.NavigationNode.toJSON(t);return{Id:this._formId.guidString,Name:this.formName,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible,LabelId:this.labelId&&this.labelId.guidString,PreviewId:this._formId.guidString,PreviewSessionId:(0,cp.getSessionId)(),EntityLogicalName:this._entityName,FormId:this._formId.guidString,TabAttributes:{},Tabs:await this.getTabsJSON(t),HiddenFields:[],Header:this.header&&await this.header.toJSON(t),Footer:this.footer&&await this.footer.toJSON(t),...this.formType===wt.Main?{HeaderDensity:Aee(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Eee(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:r,BusinessLogic:void 0,FormLibraries:[],Navigation:n,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var dp,ab,rL=k(()=>{"use strict";vt();dt();le();kt();ko();dp=class extends nr{constructor(t){super(E.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(E.formEveryOne)&&this.getChildren(E.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new ab(this))}},ab=class extends re{constructor(t){super(E.formEveryOne,t)}}});var fp,nL=k(()=>{"use strict";le();kt();fp=class extends re{constructor(t,r){super(E.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var ol,sb=k(()=>{"use strict";le();nc();ol=class extends pi{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(E.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var ic,iL=k(()=>{"use strict";le();sb();ic=class extends ol{_customFooter;constructor(t,r){super(E.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var oc,oL=k(()=>{"use strict";le();sb();oc=class extends ol{_customHeader;constructor(t,r){super(E.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var $r,_a=k(()=>{"use strict";vt();rr();le();ko();$r=class e extends nr{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(E.Titles);return t.length===0?[]:t[0].getChildren(E.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(E.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(E.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var ac,aL=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(ac||(ac={}))});var pp,sL=k(()=>{"use strict";dt();le();_a();aL();pp=class extends $r{constructor(t){super(E.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return R.IsNullOrUndefined(r)?ac.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):ac.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var Fe,See,lL,tve,al,lb=k(()=>{"use strict";vt();le();_a();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(Fe||(Fe={}));See=new Map([[Fe.Info,"Info"],[Fe.Sales,"Sales"],[Fe.Service,"Service"],[Fe.Marketing,"Marketing"],[Fe.ProcessCenter,"ProcessCenter"]]),lL=new Map([["Info",Fe.Info],["Sales",Fe.Sales],["Service",Fe.Service],["Marketing",Fe.Marketing],["ProcessCenter",Fe.ProcessCenter]]),tve=new Map([[Fe.Info,9e3],[Fe.Sales,9200],[Fe.Service,9400],[Fe.Marketing,9600],[Fe.ProcessCenter,9800],[Fe.InternetMarketing,1e4],[Fe.Async,10200]]),al=class extends $r{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=See.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var sl,ub=k(()=>{"use strict";le();_a();sl=class extends $r{constructor(t,r){super(E.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(E.formNavBarArea)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var mp,uL=k(()=>{"use strict";dt();le();_a();mp=class extends $r{RelationshipNameUCIRuntime;constructor(t){super(E.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.TitleResourceId)}async toJSON(t){return{Area:this.Area,Show:this.Show||t.formModelService.showHiddenElements,Id:this.Id,Titles:[{Name:t.langCode.toString(),Value:this.getTitle(t.langCode)}],Sequence:this.Sequence.toString(),Privileges:[],TooltipTitles:[],AvailableOffline:!0,PreviewId:this.Id,RelationshipName:this.RelationshipNameUCIRuntime??this.RelationshipName,Icon:null,ViewId:null,Client:null,TitleResourceId:null}}}});var hp,cL=k(()=>{"use strict";le();_a();hp=class extends $r{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var gp,dL=k(()=>{"use strict";vt();le();lb();ub();_a();gp=class extends $r{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(E.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Fe.Info,Fe.Sales,Fe.Service,Fe.Marketing,Fe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>lL.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new sl(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new al(E.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(E.formNavBar)}get id(){return new U(V0,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(E.formNavBarAreas,r),this.addGrandChildAtIndex(E.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var fL={};nn(fL,{ControlType:()=>yn,DeserializationService:()=>fb,DeserializationServiceScope:()=>db,DeserializedFormElementNode:()=>xr});var cb,xr,db,yn,fb,rb=k(()=>{"use strict";cb=Ce(ya());vt();dt();rr();Fs();G0();ga();QT();_D();$u();tL();rc();op();tc();Qy();le();le();rL();kt();kn();Xy();nL();iL();Zy();eb();oL();nb();ib();nc();lp();sL();lb();ub();uL();cL();dL();xr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},db="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(yn||(yn={}));fb=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let m="";throw d.length===0?m="FormXml has no form node.":m="FormXml has multiple form nodes.",(0,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==wt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=ba.getNecessaryLookUpTable(r),i=1;n.containsKey(t)&&(i+=n.getValue(t)),n.upsert(t,i)}appendDefaultDisplayCondition(t){let r='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new up(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===wt.Main&&(this.insertHeaderFooterElementProperties(E.formHeader,d,d.header),this.insertHeaderFooterElementProperties(E.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===E.formHeader?new oc(r,!0):new ic(r,!0);xr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),xr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),xr.prototype.insertProperty.call(i,y.columnName,qe.MarginalControlColumns),xr.prototype.insertProperty.call(i,y.LabelWidth,qe.LabelWidth),xr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new Sa(o);for(let s=0;s<i.maxColumns;s++){let l=new kr(a);xr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),xr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===E.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new xr(`<${t.nodeValue}`,r);if(t.nodeType===Node.COMMENT_NODE)return;let n=this.createModelNode(t,r);return this.populateElementProperties(n,t.attributes),this.populateElementChildren(n,t.childNodes),n}populateElementProperties(t,r){if(!r){let n="attributes is undefined for element: "+t.getNodeName();throw(0,cb.trackErrorTrace)(hr,{eventName:db,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(xr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===E.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&xr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case E.form:throw new Error("Form node shouldn't be created using this method");case E.formTab:return new Ki(r);case E.formColumn:return new $o(r);case E.formHeader:return new oc(r,!1);case E.formFooter:return new ic(r,!1);case E.formSection:return new pi(E.formSection,r);case E.formRow:return new Sa(r);case E.formCell:return new kr(r);case E.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=yn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=yn.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=yn.Lookup)}return o===yn.Grid?new rl(r):o===yn.Lookup?new nl(r):new Fn(r);case E.formEvent:return new tl(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new el(r,q.EmptyString);case E.Handler:let a=[];return new fp(a,r);case E.formNavigation:return new gp(t.nodeName,r);case E.formNavBarArea:return new al(t.nodeName,r);case E.formNavBarAreas:return new sl(t.nodeName,r);case E.formNavBar:return new pp(r);case E.formNavBarByRelationshipItem:return new mp(r);case E.formNavBarItem:return new hp(r);case E.formDisplayConditions:return new dp(r);case E.library:return new il(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new Rf(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new Vf(r);default:return new xr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,ui.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);ft.CustomControlIdMap.upsert(l,o);break}}break}}}}});var pL={};nn(pL,{SerializationService:()=>pb,SerializationServiceScope:()=>Nee,SerializedFormElementNode:()=>ll});var Nee,ll,pb,mL=k(()=>{"use strict";rr();kt();kn();ob();Nee="SerializationService",ll=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},pb=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=ll.prototype.fetchNodeName.call(t);if(r.charAt(0)===ji.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=ll.prototype.enumerateProperties.call(t),i=ll.prototype.enumerateChildren.call(t);if(!(t instanceof Na)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var yb=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.completeRecordAsStored=ul.completeLabelsAsStored=void 0;var mb=Eo(),_ee="E7A81278-8635-4D9E-8D4D-59480B391C5B",Tee=new Set(["tab","section","cell"]);function Mn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function xo(e,t){return Mn(e).find(r=>r.tagName===t)}function gL(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function hb(e){let t=xo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===_ee:!1}function gb(e,t){var r,n;let i=((r=xo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=xo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function Dee(e,t){if(xo(e,"labels"))return;let r=Mn(e),n=Mn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!gL(r,n.slice(1)))return;let o=Mn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&hb(e)&&gb(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function Iee(e,t){let r=Oee(e.ownerDocument,t),n=Mn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function Oee(e,t){let r=e.createElement("labels");for(let n of Mn(t))r.appendChild(yL(e,n));return r}function yL(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function hL(e,t){let r=xo(e,"labels");return r?Mn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function Pee(e,t,r){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return!1;let n=hL(e,r),i=hL(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function Ree(e,t){if(e.tagName!=="cell"||!hb(e)||!gb(e,t))return;let r=xo(e,"labels"),n=xo(t,"labels");if(!r||!n)return;let i=Mn(r),o=Mn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function bL(e,t,r,n){if(e.tagName!==t.tagName)return;if(Tee.has(e.tagName)){let a=Dee(e,t);a&&(Iee(e,a),n.changed=!0),Pee(e,t,r)&&(n.changed=!0);let s=Ree(e,t),l=xo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=yL(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Mn(e),o=Mn(t);gL(i,o)&&i.forEach((a,s)=>bL(a,o[s],r,n))}function vL(e,t,r){if(e===t)return e;let n,i;try{n=(0,mb.parseXmlRoot)(e,""),i=(0,mb.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return bL(n,i,r,o),o.changed?(0,mb.serializeNode)(n):e}ul.completeLabelsAsStored=vL;function Lee(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=vL(n,i,r);return o===n?e:{...e,formxml:o}}ul.completeRecordAsStored=Lee});var UL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var kee=($u(),zr(TD)),$ee=Q(),wL=ct(),V=zd(),xee=cu(),we=cn(),Qi=["web","phone","tablet"],sc={web:"2",phone:"0",tablet:"1"},NL=new Map([["2","web"],["0","phone"],["1","tablet"]]),Fee=["phone","web","tablet"];function bp(e){let t=new Set(e),r=Fee.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Qi.filter(n=>t.has(n))}}ue.pcfEntryLayout=bp;function gr(e){return Array.isArray(e)?e:[]}function pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function lc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vb(e){return{n:`<${e}`,a:[],c:[]}}function _L(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function CL(e){let t=gr(e.c);return t.length===1&&_L(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function vn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function TL(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function wb(e){try{let t=(0,kee.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?TL(String(t)):void 0}catch{return}}ue.nativeClassFor=wb;var Cb=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),DL=new Set(["TwoOptions","Boolean"]),IL=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),Mee=new Map([...[...IL].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),Uee=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function OL(e){return Uee.test(e)&&e!=="__proto__"}function Eb(e){return e!==void 0&&(e==="Enum"||Cb.has(e)||DL.has(e)||IL.has(e))}function PL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function uc(e,t){let r=e!==void 0?Cb.get(e):void 0;if(r&&typeof t!="boolean"){let n=PL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=uc;function Bee(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&lc(r,a)?s=uc(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[vb(s)]})}return i}function RL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Qi.filter(d=>Ab(i).has(d)),l=bp(s),u=Bee(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[vb(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",sc[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=RL;function Ab(e){return new Set(Qi.filter(t=>e.availableOn[t]))}function yp(e){var t;let r=gr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||gr(r[0].a).length>0)return;let n=gr(r[0].c);return n.every(i=>pt(i)&&!_L(i))?n:void 0}function Ta(e){let t=gr(e?.c);if(t.length===0||!t.every(p=>pt(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=gr(p.a),g=h.length===2?NL.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=bp(o);if(!vn(a.named,o)||i==="")return;let s=yp(n[0]);if(!s||!n.every(p=>vn(yp(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",sc[h]]],b=yp(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&gr(b[0].a).length===0?CL(b[0]):void 0;if(!u||!vn(gr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=gr(p.a),g=CL(p),b=h.map(w=>w[0]);if(g===void 0||!OL(p.n)||lc(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||vn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(vn(b,["static"])||vn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Qi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=Ta;function LL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===uc(r,e))}function kL(e){let t=e.formFactors;return t===void 0?[...Qi]:Array.isArray(t)?Qi.filter(r=>t.includes(r)):[]}function bb(e,t){var r,n,i;if(e.name!==t.binding.name||!vn(kL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Qi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>lc(a,l)&&LL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=bb;function Ct(e){return pt(e)&&e.customControl!==void 0}ue.hasCustomControl=Ct;function Yi(e,t){var r;return t?gr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Sb(e,t){let r=Yi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?Ta(r[0]):void 0}ue.storedBindingOf=Sb;function Nb(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Nb;function qee(e){if(!Nb(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!pt(n)||!n.fieldName||!Ji(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Sb(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=qee;function Ji(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var bn=(e,t)=>({kind:"refused",rule:e,message:t});function Vee(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!Ji(e)}function EL(e,t,r){var n,i;let o=Ta(r);if(!o)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return bn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=pt(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!vn(l,Object.keys(s).sort()))return bn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!LL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>uc(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return bn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=kL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Qi],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!Eb(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return bn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!Vee(o.nativeClass)?bn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function Gee(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>Ct(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Yi(e.bag,t)}:void 0}function $L(e,t){let r=new Map,n=Wee(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:Hee(u),uid:(0,V.controlUniqueId)(c),bound:Ct(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;pt(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!pt(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let P=m.findIndex(D);return P<0?void 0:m.splice(P,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(P=>P.bound&&P.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let P=D.cell?l(c,D.cell):void 0;return!P||!l(d,D.cell)||!m.includes(P)?!0:(m.splice(m.indexOf(P),1),f.includes(P)&&D.uid!==P.uid&&AL(D.control)&&r.set(D.control,SL(P.uid)),!1)}),b=[],w=(D,P)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!P||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&AL(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let L=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?SL(O[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function Wee(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=pt(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||Ct(a)||o>1)&&n.add(i)}return n}function AL(e){return Ct(e)||e.genPage===void 0&&Ji((0,V.effectiveClassId)(e))}function zee(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!pt(l)||Ct(l)||l.genPage!==void 0||!Ji((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Yi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var jee="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function SL(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function Hee(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function cc(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Yi(e.bag,o),s=r?$L(e,r).get(t):void 0;if(s!==void 0)return bn("pcf-binding-unique-id",s);let l=r?Gee(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?Ta(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return bn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&vn(c[0],a[0]))return EL(t,i,a[0]);let f=a.length===1?Ta(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&bb(i,d)&&bb(i,f)?{kind:"unchanged"}:bn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return bn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=EL(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:bn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=cc;function xL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function Kee(e){let t=n=>Ct(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,wL.newId)()),n.id||(n.id=(0,wL.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=Kee;function Jee(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!Ct(o)||!pt(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=cc(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):xL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=Jee;function Yee(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!Ct(p)||!pt(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Yi(u,h).length>0&&c.set(p,{plan:cc(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=pt(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!Ct(g))continue;let b=(0,V.controlUniqueId)(g),w=Yi(t.bag,b),C=Yi(u,b);if(w.length!==1||C.length!==1||!vn(w[0],C[0])||!Ta(C[0]))continue;let S=p.get(b);if(S&&!Ct(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=Ta(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),Qee(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=gr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!Ct(m)||!pt(m.customControl))continue;Ji(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new $ee.ValidationError("form",e.id,[(0,we.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&Xee(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?wb(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let C=((l=(s=gr((a=m.bag)===null||a===void 0?void 0:a.a).find(O=>O[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=C.startsWith("{")?C:`{${p}}`;d.node.c.push(RL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=Yee;function Qee(e,t){pt(e.bag)&&(e.bag.a=gr(e.bag.a).filter(r=>r[0]!==t))}function Xee(e,t){var r,n;let i=gr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=yp(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[vb(uc(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=NL.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=bp(e.factors),p=m.defaults.map(g=>{let b=a.find(C=>c(C)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",sc[g]]],w}),h=m.named.map(g=>{let b=s.find(C=>c(C)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",sc[g]]],w});e.description.c=[...p,...h]}function Zee(e){return(0,V.typedCellSites)(e).some(({cell:t})=>Ct(t.control))}ue.mayCommitPcfState=Zee;function ete(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!Ct(a))continue;let s=Sb(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=gr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Ji(a.classId)||a.type!==l||u!==void 0&&!Ji(u[1])||!vn(a.customControl,s.binding))&&(Ji(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Ji(u[1])&&(u[1]=TL(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=ete;var tte=new Set(["name","parameters","formFactors"]);function rte(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;Ct(s)&&ite(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&ote(e,t,n),n}ue.pcfBindingIssues=rte;function nte(e,t,r){let n=r.length;if(!pt(e))return r.push((0,we.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))tte.has(i)||r.push((0,we.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,we.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!pt(e.parameters))r.push((0,we.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,we.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Qi.includes(a))&&new Set(i).size===i.length||r.push((0,we.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function ite(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=nte(t.customControl,l,i);t.fieldName||i.push((0,we.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,we.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Nb(e)||i.push((0,we.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,we.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,we.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=cc(e,t,o,a);f.kind==="refused"&&i.push((0,we.issue)(l,f.rule,f.message))}function ote(e,t,r){var n;let i=new Map,o=$L(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=pt(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),pt(l.control)&&!Ct(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,we.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!Ct(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||Ct(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,we.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):vn(Yi(t.bag,u),Yi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,we.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,we.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of zee(e,t))s.has(l)||r.push((0,we.issue)(l,"pcf-binding-unique-id",jee))}var ate=new Set(["Form.Card"]),ste="MscrmControls.ModelForm.ModelFormControl";function FL(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!OL(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===ste||n.some(s=>s.defaultType!==void 0&&ate.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Eb(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function lte(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function ML(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Cb.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:PL(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&DL.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?Mee.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function ute(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!Ct(d)||!d.fieldName)continue;let f=d.customControl;if(!pt(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=cc(e,d,r,!0);if(p.kind==="edit"){xL(p)&&fte(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,we.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=FL(h.value,f.name);if(b){l.push((0,we.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),C=g.kind==="found"?g.value:void 0,S=C?(a=(0,xee.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&wb(C)!==void 0&<e(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,we.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,we.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=pt(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Le=L.get(x);if(!Le){l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let lr=ML(Le,K);lr&&l.push((0,we.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${lr}`))}for(let x of L.values())x.required&&!lc(I,x.name)&&!x.defaultValue&&l.push((0,we.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Ab(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,we.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=ute;function cte(e,t){return t===void 0||!Eb(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function dte(e,t,r){var n,i;let o=FL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!lc(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function fte(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,we.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=dte(u.value,t.name,e.stored);if(c){l.push((0,we.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];cte(d.get(h),g)||l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=ML(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,we.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Ab(u.value);e.added.some(h=>!p.has(h))&&l.push((0,we.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var tk=v(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.classIdForAttributeType=Mr.QUICK_VIEW_CLASS_ID=Mr.NOTES_CLASS_ID=Mr.SUBGRID_CLASS_ID=Mr.formRegistration=Mr.FormAdapter=void 0;var Xi=(vt(),zr(VT)),BL=(dt(),zr(GT)),pte=(kt(),zr(zT)),Et=(le(),zr(WT)),ot=(ga(),zr(jT)),mte=(rb(),zr(fL)),hte=(mL(),zr(pL)),At=wo(),qL=jr(),Fr=cn(),gte=e0(),dl=ct(),yte=yb(),ir=zd(),mi=UL(),cl=Q(),Pb=oe(),_b=Co(),HL=sa(),bte={[Et.FormType.Main]:"Main",[Et.FormType.QuickCreate]:"QuickCreate",[Et.FormType.QuickViewForm]:"QuickView",[Et.FormType.Card]:"Card"},vp={Main:Et.FormType.Main,QuickCreate:Et.FormType.QuickCreate,QuickView:Et.FormType.QuickViewForm,Card:Et.FormType.Card},vte=new Map(Object.entries(ot.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Rb(e){var t;return e&&(t=vte.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function dc(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Da(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function KL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Lb(e,t){var r,n;let i=KL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>Da(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=Da(a).get("description"))!==null&&n!==void 0?n:""}function wte(e){let t=KL(e,"parameters"),r={};if(!t)return r;for(let n of t.getAllChildren()){let i=n.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function JL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Tb(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function fc(e){return String(e??"").replace(/[{}]/g,"")}function Db(e){return`{${fc(e)}}`}function Ib(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Cp(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,At.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:dc(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,At.rawFromNode)(u)})}),{modeled:s,bag:{a:dc(e),c:o,w:{n:a.getNodeName(),a:dc(a),c:l}}}}function YL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,At.rawFromNode)(o)})}),{modeled:n,bag:{a:dc(e),c:i}}}function VL(e,t){let{modeled:r,bag:n}=Cp(e,"tabs","tab");return{tabs:r.map(i=>Cte(i,t)),bag:n}}function Cte(e,t){var r,n;let i=Da(e),{modeled:o,bag:a}=Cp(e,"columns","column");return{id:(r=i.get("id"))!==null&&r!==void 0?r:"",name:(n=i.get("name"))!==null&&n!==void 0?n:"",label:Lb(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>Ete(s,t)),bag:a}}function Ete(e,t){let r=Da(e),{modeled:n,bag:i}=Cp(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>Ate(o,t)),bag:i}}function Ate(e,t){var r,n,i;let o=Da(e),{modeled:a,bag:s}=Cp(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:Lb(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:JL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>Ste(l,t)),bag:s}}function Ste(e,t){let{modeled:r,bag:n}=YL(e,"cell",!1);return{cells:r.map(i=>Nte(i,t)),bag:n}}function Nte(e,t){var r;let n=Da(e),{modeled:i,bag:o}=YL(e,"control",!0),a=Lb(e,t),s=n.get("showlabel")==="true",l=i[0]?_te(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Ib(n.get("colspan"),1),rowspan:Ib(n.get("rowspan"),1),control:l,bag:o}}function _te(e,t,r){var n,i;let o=Da(e),a=fc((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Rb(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:wte(e),bag:{a:dc(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,At.rawFromNode)(l)}))}}}function Uo(e){return e.a.length===0&&e.c.length===0&&!e.w}function QL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Ia(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=Uo(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=QL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,At.mergeAttrs)(e.a,o)}var Fo=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Mo=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),GL=(e,t,r=1)=>({key:e,matches:n=>Ib(n,r)===t,render:()=>String(t),absentDefault:String(r)});function kb(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Ob(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Pb.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function Tte(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function Dte(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return n||i.push({n:"label",a:[["description",t],["languagecode",String(r)]],c:[]}),{...e,c:i}}function $b(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||Uo(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:kb(t,r)},...a]}}if(Tte(e.c[n].node,r)===t)return e;let i=Dte(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function Ite(e){let t={};for(let r of e.c){let n=r.n;if(n.charAt(0)==="<"||n.charAt(0)==="#")continue;let i=r.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function Ote(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function Pte(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function Rte(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||Uo(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Ob(t)}]}}if(Ote(Ite(e.c[r].node),t))return e;let n=Ob(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Ep(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,At.spliceChildren)(e.w.c,r)};return(0,At.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,At.spliceChildren)(e.c,[...i,o])}function Lte(e,t){let r=e.tabs.map(n=>kte(n,t));return{n:"form",a:Ia(e.bag,[]),c:e.tabs.length===0&&Uo(e.bag)?[]:Ep(e.bag,"tabs",r,()=>[])}}function XL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[kb(t,r)]:[]}function kte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("expanded",e.expanded),Mo("visible",e.visible,!0)],n=e.columns.map(o=>$te(o,t)),i=$b(e.bag,e.label,t);return{n:"tab",a:Ia(i,r),c:Ep(i,"columns",n,()=>XL(i,e.label,t))}}function $te(e,t){let r=e.width!==void 0?[Fo("width",e.width)]:[],n=e.sections.map(i=>xte(i,t));return{n:"column",a:Ia(e.bag,r),c:Ep(e.bag,"sections",n,()=>[])}}function xte(e,t){let r=[Fo("id",e.id),Fo("name",e.name),Mo("showlabel",e.showLabel),Mo("visible",e.visible,!0),{key:"columns",matches:o=>JL(o)===e.columns,render:()=>Tb(e.columns),absentDefault:Tb(1)}],n=e.rows.map(o=>Fte(o,t)),i=$b(e.bag,e.label,t);return{n:"section",a:Ia(i,r),c:Ep(i,"rows",n,()=>XL(i,e.label,t))}}function Fte(e,t){let r=e.cells.map(n=>Mte(n,t));return{n:"row",a:Ia(e.bag,[]),c:Uo(e.bag)?r:(0,At.assembleChildren)(e.bag,r)}}function Mte(e,t){let r=e.control?e.control.showLabel:QL(e.bag,"showlabel")==="true",n=[Fo("id",e.id),Mo("showlabel",r),Mo("visible",e.visible,!0),GL("colspan",e.colspan),GL("rowspan",e.rowspan)],i=e.control?[Ute(e.control)]:[],o;if(Uo(e.bag))o=[...e.control&&e.control.label?[kb(e.control.label,t)]:[],...i];else{let a=e.control?$b(e.bag,e.control.label,t):e.bag;o=(0,At.assembleChildren)(a,i)}return{n:"cell",a:Ia(e.bag,n),c:o}}function Ute(e){let t=[Fo("id",e.id),{key:"classid",matches:i=>fc(i)===e.classId,render:()=>Db(e.classId||String(ot.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Fo("datafieldname",e.fieldName)),t.push(Mo("disabled",e.isReadOnly)),t.push(Mo("isrequired",e.isRequired));let r=e.fieldName===null?Pte(e.bag,"datafieldname"):e.bag,n;return Uo(r)?n=Object.keys(e.parameters).length>0?[Ob(e.parameters)]:[]:n=(0,At.assembleChildren)(Rte(r,e.parameters),[]),{n:"control",a:Ia(r,t),c:n}}var Bte={make:(e,t)=>new pte.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function WL(e,t,r,n){(0,_b.installDomShim)();let i=Vte(e,r);(0,ir.reconcileEmbedDescriptions)(i,n),(0,mi.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,At.rebuildRaw)(Lte(i,t),Bte,null);return new hte.SerializationService(t).serializeFormXmlNode(o)}function qte(e){return JSON.parse(JSON.stringify(e))}function Vte(e,t){let r=qte(e);r.bag||(r.bag=(0,At.emptyBag)()),r.tabs||(r.tabs=[]),Yte(r.bag),t&&Gte(r,t);for(let n of r.tabs)Wte(n);return r}function Gte(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";xb(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=ek(s.attributeType)))})}function zL(e){let t=[];return xb(e,r=>t.push(r)),t}function xb(e,t){var r,n,i,o,a;for(let s of(r=e.tabs)!==null&&r!==void 0?r:[])for(let l of(n=s.columns)!==null&&n!==void 0?n:[])for(let u of(i=l.sections)!==null&&i!==void 0?i:[])for(let c of(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function Wte(e){e.id||(e.id=Xi.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.expanded===void 0&&(e.expanded=!0),e.visible===void 0&&(e.visible=!0),e.columns||(e.columns=[]);for(let t of e.columns)zte(t);e.bag||(e.bag=(0,At.emptyBag)())}function zte(e){e.sections||(e.sections=[]);for(let t of e.sections)jte(t);e.bag||(e.bag=(0,At.emptyBag)()),e.width===void 0&&Uo(e.bag)&&(e.width="100%")}function jte(e){e.id||(e.id=Xi.Guid.NewGuid()),e.name===void 0&&(e.name=""),e.label===void 0&&(e.label=""),e.showLabel===void 0&&(e.showLabel=!1),e.visible===void 0&&(e.visible=!0),e.columns===void 0&&(e.columns=1),e.rows||(e.rows=[]);for(let t of e.rows)Hte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Hte(e){e.cells||(e.cells=[]);for(let t of e.cells)Kte(t);e.bag||(e.bag=(0,At.emptyBag)())}function Kte(e){(0,ir.hasGenPage)(e.control)&&(0,ir.applyEmbedCellDefaults)(e),e.id||(e.id=Xi.Guid.NewGuid()),e.visible===void 0&&(e.visible=!0),e.colspan===void 0&&(e.colspan=1),e.rowspan===void 0&&(e.rowspan=1),e.control===void 0&&(e.control=null),e.control&&Jte(e.control),e.bag||(e.bag=(0,At.emptyBag)())}function Jte(e){var t;(0,ir.hasGenPage)(e)&&(0,ir.applyEmbedControlDefaults)(e),e.id||(e.id=Xi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(ot.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Rb(String(e.classId))),e.isRequired===void 0&&(e.isRequired=!1),e.isReadOnly===void 0&&(e.isReadOnly=!1),e.label===void 0&&(e.label=(t=e.fieldName)!==null&&t!==void 0?t:""),e.showLabel===void 0&&(e.showLabel=!0),(e.parameters===void 0||e.parameters===null)&&(e.parameters={});for(let r of Object.keys(e.parameters))(0,Pb.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,At.emptyBag)())}function Yte(e){for(let t of e.c){let r=t.node;if(r.n==="events"){for(let n of r.c)if(n.n==="event"){for(let i of n.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!jL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Db(Xi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!jL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Db(Xi.Guid.NewGuid())])}}var wp=class{constructor(t=HL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=VL(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=bte[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,ir.projectGenPageEmbeds)(l),(0,mi.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:WL(t,this.lcid),formid:t.id||(0,dl.newId)(),objecttypecode:t.entityLogicalName,type:vp[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:t.status==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,dl.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,_b.installDomShim)();let f=BL.ScriptUtilities.ParseXml(c),m=Qte(f),p=this.deserializeDocument(d,f);return Xte(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,ir.genPageEmbedIssues)(t);if(i.length>0)throw new cl.ValidationError("form",t.id,i);let o=(0,mi.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new cl.ValidationError("form",t.id,o);let a=(0,mi.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,cl.attachCause)(new cl.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new cl.ValidationError("form",t.id,a.issues);return{formxml:WL(t,this.lcid,n,r),name:t.name,type:vp[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return xb(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,mi.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,ir.genPageEmbedIssues)(t),...(0,mi.pcfBindingIssues)(t)];if(p.length>0)throw new cl.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:lre(this.lcid),g=h!==void 0?h:t.tabs.map(C=>Zte(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,dl.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:vp[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?Et.FormActivationState.Active:Et.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(Et.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=zL(t);zL(w).forEach((S,O)=>{C[O]&&C[O].label===void 0&&delete S.label,C[O]&&C[O].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(C[O].genPage))),C[O]&&C[O].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(C[O].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,dl.assignMissingIds)(t)}completeAsStored(t,r){return(0,yte.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,mi.mintPcfIdentity)((0,ir.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,ir.mayCommitEmbedState)(t)||(0,mi.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,dl.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:vp[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:Et.FormPresentation.AirForm,formactivationstate:Et.FormActivationState.Active}),{bag:d}=VL(c,this.lcid),f=(0,mi.commitPcfState)((0,ir.commitEmbedState)(t,(l=(0,ir.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Rb);return{artifact:f,baseline:f}}validate(t){return yre(t)}deserialize(t){return(0,_b.installDomShim)(),this.deserializeDocument(t,BL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new mte.DeserializationService(this.lcid).deSerializeFormXml(r,new Xi.Guid(t.formid),t.objecttypecode,Et.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!n)throw new Error("FormXml could not be deserialized into a Form model.");return n}readActivationStatus(t){return t.formactivationstate===Et.FormActivationState.InActive?"Inactive":"Active"}};Mr.FormAdapter=wp;var ZL=["header","footer","DisplayConditions"];function Qte(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&ZL.includes(i.nodeName)&&n.add(i.nodeName);return n}function Xte(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=ZL.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Un(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Fb(e,t){return e?`<labels><label description="${Un(e)}" languagecode="${t}" /></labels>`:""}function Mb(e){return e&&e.length>0?fc(e):(0,dl.newId)()}function Zte(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[sre()]).map(l=>ere(l,t)).join("");return`<tab id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${Fb(e.label,t)}<columns>${s}</columns></tab>`}function ere(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>tre(o,t)).join("");return`<column width="${Un((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function tre(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>rre(l,t)).join("");return`<section id="{${Un(Mb(e.id))}}" name="${Un((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${Tb((a=e.columns)!==null&&a!==void 0?a:1)}">${Fb(e.label,t)}<rows>${s}</rows></section>`}function rre(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>nre(n,t)).join("")}</row>`}function nre(e,t){var r,n,i,o,a;let s=ire(e),l=s.control,u=l?Fb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?ore(l):"";return`<cell id="{${Un(Mb(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function ire(e){if(!(0,ir.hasGenPage)(e.control))return e;let t={...e.control};(0,ir.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,ir.applyEmbedCellDefaults)(r),r}function ore(e){var t,r,n;let i=e.fieldName?` datafieldname="${Un(e.fieldName)}"`:"",o=are(e.parameters),a=e.classId?fc(e.classId):String(ot.ControlClassId.TextboxControl);return`<control id="${Un((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Un(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function are(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Pb.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Un(e[n])}</${n}>`).join("")}</parameters>`)}function sre(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function lre(e){return`<tab id="{${Xi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Xi.Guid.NewGuid()}}" name="section_general" showlabel="false" visible="true" columns="1"><labels><label description="General" languagecode="${e}" /></labels><rows></rows></section></sections></column></columns></tab>`}function ure(e=HL.DEFAULT_LCID){return{adapter:new wp(e),api:gte.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,qL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,qL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Mr.formRegistration=ure;var cre=new Set(["id","name","label","expanded","visible","columns","bag"]),dre=new Set(["id","width","sections","bag"]),fre=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),pre=new Set(["id","cells","bag"]),mre=new Set(["id","visible","colspan","rowspan","control","bag"]),hre=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),gre={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function yre(e){let t=[];return(0,Fr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Fr.rejectUnknownKeys)(n,cre,o,"tab",t),(0,Fr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Fr.rejectUnknownKeys)(s,dre,u,"column",t),(0,Fr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Fr.rejectUnknownKeys)(d,fre,m,"section",t),(0,Fr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Fr.rejectUnknownKeys)(h,pre,b,"row",t),(0,Fr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Fr.rejectUnknownKeys)(C,mre,O,"cell",t,gre);let L=C.control;L!=null&&!(0,Fr.isJsonObject)(L)?t.push((0,Fr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Fr.isJsonObject)(L)&&(0,Fr.rejectUnknownKeys)(L,hre,`${O}/control`,"control",t)})})})})}),t.push(...(0,ir.genPageEmbedIssues)(e)),t.push(...(0,mi.pcfBindingIssues)(e)),t}Mr.SUBGRID_CLASS_ID=ot.ControlClassId.SubgridControl;Mr.NOTES_CLASS_ID=ot.ControlClassId.TimelineControl;Mr.QUICK_VIEW_CLASS_ID=ot.ControlClassId.QuickViewControl;var bre={Lookup:String(ot.ControlClassId.LookupControl),Customer:String(ot.ControlClassId.LookupControl),Owner:String(ot.ControlClassId.LookupControl),PartyList:String(ot.ControlClassId.PartyListControl),Boolean:String(ot.ControlClassId.BooleanControl),DateTime:String(ot.ControlClassId.DateTimeControl),Decimal:String(ot.ControlClassId.DecimalControl),Double:String(ot.ControlClassId.FloatingNumberControl),Money:String(ot.ControlClassId.CurrencyControl),Integer:String(ot.ControlClassId.IntegerControl),BigInt:String(ot.ControlClassId.IntegerControl),Memo:String(ot.ControlClassId.TextAreaControl),String:String(ot.ControlClassId.TextboxControl)},vre="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function ek(e){return e==="Picklist"||e==="State"||e==="Status"?vre:e&&bre[e]||String(ot.ControlClassId.TextboxControl)}Mr.classIdForAttributeType=ek;function jL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Ub=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.viewApi=fl.findDefaultViews=void 0;var ok=Tt(),yr=fe(),Bn=oe(),wre=ys(),rk="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",Cre="savedqueryid,name,returnedtypecode,querytype,isdefault",Ere=60*1e3;function Ap(e){return(e.localName||e.nodeName).toLowerCase()}function pc(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function Are(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new wre.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Ap(n)==="fetch"?n:void 0}function Sre(e){for(let t=e.parentNode;t;t=t.parentNode)if(Ap(t)==="link-entity")return!0;return!1}function nk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=Are(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Ap(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Ap(u)==="link-entity").every(u=>{var c;return((c=pc(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!Sre(l)&&pc(l,"entityname")===void 0&&((n=pc(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=pc(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&pc(l,"value")===String(t)}function Nre(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function _re(e){var t,r;let n=e.filter(a=>nk(a,0)),i=e.filter(a=>nk(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=Ere&&Nre(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function Tre(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Bn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Bn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,ok.collectPages)(e,a,`findDefaultViews('${t}')`),l=_re(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}fl.findDefaultViews=Tre;async function Dre(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Bn.odataPathLiteral)(t)}')${(0,Bn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function ik(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await Dre(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}fl.viewApi={async get(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]);return{raw:(0,yr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Bn.odataQuery)([["$select",rk]]),i=(0,yr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,yr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Bn.odataQuery)([["$select",Cre],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Bn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,ok.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,yr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await ik(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,yr.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,yr.ensureSuccess)(await(0,yr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,yr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,yr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Bn.normalizeGuid)(t,"id"),a=(0,yr.echoWrite)("savedqueryid",{"If-Match":(0,yr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await ik(e,i.layoutxml,i.returnedtypecode),u=(0,yr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,yr.readEtag)(u)}},delete(e,t){return(0,yr.deleteRecord)(e,"savedqueries",t)}}});var Ck=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.viewRegistration=pl.ViewAdapter=void 0;var fk=Q(),en=cn(),Bb=wo(),Oa=Eo(),ak=jr(),Ire=Ub(),qb=Co(),Ore=ct(),pk=100,Np=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,qb.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,Oa.parseXmlRoot)(c,"<fetch/>"),m=(0,Oa.parseXmlRoot)(d,"<grid/>"),p=hk(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:Rre(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:mk(m,f),filters:yk(f),sort:gk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,Oa.projectElementBag)(f):void 0,layoutBag:d?(0,Oa.projectElementBag)(m):void 0}}fromArtifact(t){(0,qb.installDomShim)();let{fetchxml:r,layoutxml:n}=sk(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:r,layoutxml:n}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a;(0,qb.installDomShim)();let{fetchxml:s,layoutxml:l}=sk(t);return{name:(r=t.name)!==null&&r!==void 0?r:"",description:(n=t.description)!==null&&n!==void 0?n:"",fetchxml:s,layoutxml:l,returnedtypecode:(i=t.entityLogicalName)!==null&&i!==void 0?i:"",querytype:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,Ore.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,en.childObjects)(n,"columns","","column",r),(0,en.childObjects)(n,"sort","","sort",r),(0,en.childObjects)(n,"linkEntities","","linkEntity",r),Pre(n.linkEntities,r);let i=n.filters;return i!=null&&((0,en.isJsonObject)(i)?Vb(i,"/filters",r):r.push((0,en.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};pl.ViewAdapter=Np;function Pre(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,en.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,en.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,en.isJsonObject)(i)?Vb(i,`/linkEntities/${n}/filters`,t):t.push((0,en.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Vb(e,t,r){(0,en.childObjects)(e,"conditions",t,"condition",r),(0,en.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Vb(i,`${t}/groups/${o}`,r))}function Rre(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function mk(e,t){var r;let n=_p(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let l=i[s];if(l.getAttribute("ishidden")==="1")continue;let u=l.getAttribute("name");if(!u)continue;let c=parseInt((r=l.getAttribute("width"))!==null&&r!==void 0?r:"",10),d={name:u,width:Number.isNaN(c)?pk:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function _p(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function hk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Wt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Wt(n,"filter").find(c=>!Tp(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Gb(u)}:{}})}return r}function gk(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function yk(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Wt(t,"filter").filter(i=>!Tp(i)).map(Gb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Tp(e){if(e.getAttribute("isquickfindfields")==="1"||bk(e))return!0;if(Wt(e,"filter").length>0)return!1;let t=Wt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Wt(r,"value").length>0||kre(r))}function bk(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?bk(n):n.tagName!=="condition"))return!0}return!1}var Lre=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function kre(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!Lre.has(i))return!0}return!1}function Gb(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(Gb(l))}return{type:n,conditions:i,groups:o}}function Wt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var Wb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function $re(e,t){let r=_p(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Wb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function xre(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Wb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new fk.ValidationError("view",e.id,a.map(s=>(0,en.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function sk(e){var t,r;let n=Fre(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!lk(e.fetchBag)||!lk(e.layoutBag))return{fetchxml:Yre({...e,columns:n,sort:i,filters:o}),layoutxml:Qre({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=uk(e.fetchBag,"fetch",a),l=uk(e.layoutBag,"grid",a),u=mk(l,s),c=!Sp(n,u),d=!Sp(i,gk(s)),f=!Sp(o,yk(s)),m=e.linkEntities,p=m!==void 0&&!Sp(m,hk(s)),h=p?$re(s,u):void 0;return p&&Hre(a,s,m),p&&(Jre(e,s,n,h),xre(e,s,n,h)),c?(ck(a,s,n,u),Vre(a,l,n)):p&&ck(a,s,n,u),d&&zre(a,s,i),f&&jre(a,s,o),{fetchxml:(0,Oa.serializeNode)(s),layoutxml:(0,Oa.serializeNode)(l)}}function Fre(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:pk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function lk(e){return!!e&&(e.c.length>0||e.a.length>0)}function uk(e,t,r){let n={n:t,a:(0,Bb.mergeAttrs)(e.a,[]),c:(0,Bb.spliceChildren)(e.c,[])};return(0,Bb.rebuildRaw)(n,(0,Oa.domEngine)(r),null)}function ck(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=_p(t);for(let p of n)u.has(l(p))||(Ure(s,p),p.relatedEntity&&c.has(p.name)&&Mre((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=_p(t),m=new Set(Wt(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!wk(s,p.relatedEntity)))continue;let g=Bre(e,s,p.relatedEntity),b=e.createElement("attribute");vk(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),qre(s,h),m.add(p.name)}}function vk(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function Mre(e,t){if(e){for(let r of Wt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function Ure(e,t){if(t.relatedEntity){for(let r of Wt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Wt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Wt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function wk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Wt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function Bre(e,t,r){let n=wk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function qre(e,t){let r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function Vre(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=Gre(n);if(Wre(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function Gre(e){return Wt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Wre(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].getAttribute("name")!==t[r].name)return!1;return!0}function zre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Wt(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function jre(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Wt(n,"filter"))Tp(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(mc(e,r))}}function Sp(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Hre(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Wt(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,O)=>O!==g&&!s[O]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){dk(e,g,p);return}let b=e.createElement("link-entity");dk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var Kre=new Set(["inner","outer"]);function Jre(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Wb(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new fk.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,en.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function dk(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):Kre.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Wt(t,"filter").find(o=>!Tp(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?mc(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function Yre(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(mc(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){vk(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(mc(r,e.filters)),new XMLSerializer().serializeToString(r)}function mc(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(mc(e,n));return r}function Qre(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[0])===null||r===void 0?void 0:r.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function Xre(){return{adapter:new Np,api:Ire.viewApi,publish:(e,t,r)=>(0,ak.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,ak.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}pl.viewRegistration=Xre});function Dp(e,t){return e==="SetFieldValue"&&t!==void 0&&Zre.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Zre,zb=k(()=>{"use strict";Zre=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function Ek(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function jb(e){return e==="AllForms"||Ek(e)?1:2}function Hb(e){return Ek(e)?e:null}function Ak(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:ml.WorkflowCategory.BusinessRule,type:ml.WorkflowTypeCode.Definition,mode:1,scope:ml.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:jb(e.scope),processtriggerformid:Hb(e.scope)}}var ml,Sk=k(()=>{"use strict";ml=Ce(lo());});function Nk(e,t=0){return(zt[e[t+0]]+zt[e[t+1]]+zt[e[t+2]]+zt[e[t+3]]+"-"+zt[e[t+4]]+zt[e[t+5]]+"-"+zt[e[t+6]]+zt[e[t+7]]+"-"+zt[e[t+8]]+zt[e[t+9]]+"-"+zt[e[t+10]]+zt[e[t+11]]+zt[e[t+12]]+zt[e[t+13]]+zt[e[t+14]]+zt[e[t+15]]).toLowerCase()}var zt,_k=k(()=>{zt=[];for(let e=0;e<256;++e)zt.push((e+256).toString(16).slice(1))});function Kb(){return Ip>Op.length-16&&((0,Tk.randomFillSync)(Op),Ip=0),Op.slice(Ip,Ip+=16)}var Tk,Op,Ip,Dk=k(()=>{Tk=require("crypto"),Op=new Uint8Array(256),Ip=Op.length});var Ik,Jb,Ok=k(()=>{Ik=require("crypto"),Jb={randomUUID:Ik.randomUUID}});function ene(e,t,r){if(Jb.randomUUID&&!t&&!e)return Jb.randomUUID();e=e||{};let n=e.random??e.rng?.()??Kb();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Nk(n)}var br,Pk=k(()=>{Ok();Dk();_k();br=ene});var Yb=k(()=>{Pk()});var Rk=k(()=>{"use strict";});function Lk(e){return e!=null&&tne.has(e)}function Pp(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var tne,Qb=k(()=>{"use strict";tne=new Set(["Picklist","State","Status"])});var Rp=v(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.WorkflowConditionOperator=wn.WorkflowAttributeType=wn.SystemStep=wn.FieldRequiredLevelTypes=wn.AttributeDateTimeBehavior=void 0;wn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};wn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};wn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};wn.WorkflowAttributeType={Boolean:"0",Customer:"1",DateTime:"2",Decimal:"3",Float:"4",Integer:"5",Lookup:"6",Money:"7",Owner:"8",PartyList:"9",Picklist:"10",Key:"11",State:"12",Status:"13",String:"14",UniqueIdentifier:"15",EntityNameReference:"16",Entity:"17",EntityCollection:"18",BpfProcess:"19",BpfStageCategory:"20",BpfStage:"21",EntityReferenceCollection:"22",MultiSelectPicklist:"23",BigType:"24"};wn.WorkflowConditionOperator={IsNull:"0",NotNull:"1",LogicalAnd:"2",LogicalOr:"3",IN:"4",NotIn:"5",NotInNull:"51",Equal:"6",NotEqual:"7",Contains:"8",DoesNotContain:"9",BeginsWith:"10",DoesNotBeginWith:"11",EndsWith:"12",DoesNotEndWith:"13",GreaterThan:"14",GreaterThanOrEqual:"15",LessThan:"16",LessThanOrEqual:"17",EqualUserId:"18",NotEqualUserId:"19",On:"20",NotOn:"21",OnOrAfter:"22",OnOrBefore:"23",Yesterday:"24",Today:"25",Tomorrow:"26",NextSevenDays:"27",LastSevenDays:"28",NextWeek:"29",LastWeek:"30",ThisWeek:"31",NextMonth:"32",LastMonth:"33",ThisMonth:"34",NextYear:"35",LastYear:"36",ThisYear:"37",Anytime:"38",LastXHours:"39",NextXHours:"40",LastXDays:"41",NextXDays:"42",LastXWeeks:"43",NextXWeeks:"44",LastXMonths:"45",NextXMonths:"46",LastXYears:"47",NextXYears:"48",Under:"49",NotUnder:"50"}});function Lp(e){return e!=null&&$k.includes(e)}function Xb(e){return e===ae.WorkflowAttributeType.Integer}function Zb(e,t){return t===ae.WorkflowConditionOperator.Equal||t===ae.WorkflowConditionOperator.NotEqual?e:rne.includes(t)?$k.includes(e)||e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:t===ae.WorkflowConditionOperator.On||t===ae.WorkflowConditionOperator.NotOn?e===ae.WorkflowAttributeType.DateTime?e:ae.WorkflowAttributeType.String:ae.WorkflowAttributeType.String}function xk(e){let t=e.leftWorkflowType??e.valueWorkflowType??ae.WorkflowAttributeType.String,r=hc[e.operator]??ae.WorkflowConditionOperator.Equal;return Zb(t,r)}function Fk(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!kk.test(o)||!kk.test(a)||o.length>1&&o.startsWith("0")||o.length>nne?!1:t!==ae.WorkflowAttributeType.Integer||i.length===1}var ae,hc,$k,rne,kk,nne,ev=k(()=>{"use strict";ae=Ce(Rp());hc={Equals:ae.WorkflowConditionOperator.Equal,DoesNotEqual:ae.WorkflowConditionOperator.NotEqual,IsGreaterThan:ae.WorkflowConditionOperator.GreaterThan,IsLessThan:ae.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:ae.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:ae.WorkflowConditionOperator.LessThanOrEqual,Contains:ae.WorkflowConditionOperator.Contains,DoesNotContain:ae.WorkflowConditionOperator.DoesNotContain,BeginsWith:ae.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:ae.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:ae.WorkflowConditionOperator.EndsWith,DoesNotEndWith:ae.WorkflowConditionOperator.DoesNotEndWith,On:ae.WorkflowConditionOperator.On,NotOn:ae.WorkflowConditionOperator.NotOn,ContainsData:ae.WorkflowConditionOperator.NotNull,DoesNotContainData:ae.WorkflowConditionOperator.IsNull},$k=[ae.WorkflowAttributeType.Decimal,ae.WorkflowAttributeType.Float,ae.WorkflowAttributeType.Integer,ae.WorkflowAttributeType.Money],rne=[ae.WorkflowConditionOperator.GreaterThan,ae.WorkflowConditionOperator.GreaterThanOrEqual,ae.WorkflowConditionOperator.LessThan,ae.WorkflowConditionOperator.LessThanOrEqual];kk=/^\d*$/,nne=28});var Mk=k(()=>{"use strict";});function qn(e){return!ine.has(e)}function tv(e){return e==="Equals"||e==="DoesNotEqual"}function kp(e){return Bk.has(e)?one:cne.has(e)?ane:qk.has(e)?sne:fne.has(e)?une:lne}function Vk(e){return kp(e)[0]}function Gk(e,t){return kp(t).includes(e)}function Uk(e){return Bk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":qk.has(e)?"date":dne.has(e)?"boolean":"other"}function $p(e,t){let r=Uk(e),n=Uk(t);return r==="other"||n==="other"?e===t:r===n}var ine,one,ane,sne,lne,une,Bk,cne,qk,dne,fne,xp=k(()=>{"use strict";Mk();ine=new Set(["ContainsData","DoesNotContainData"]);one=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],ane=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],sne=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],lne=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],une=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Bk=new Set(["String","Memo","EntityName"]),cne=new Set(["Integer","BigInt","Money","Decimal","Double"]),qk=new Set(["DateTime"]),dne=new Set(["Boolean"]),fne=new Set(["Lookup","Owner","Customer"])});function Hk(e){switch(e){case"Boolean":return Me.WorkflowAttributeType.Boolean;case"Customer":return Me.WorkflowAttributeType.Customer;case"DateTime":return Me.WorkflowAttributeType.DateTime;case"Decimal":return Me.WorkflowAttributeType.Decimal;case"Double":return Me.WorkflowAttributeType.Float;case"Integer":return Me.WorkflowAttributeType.Integer;case"Lookup":return Me.WorkflowAttributeType.Lookup;case"Money":return Me.WorkflowAttributeType.Money;case"Owner":return Me.WorkflowAttributeType.Owner;case"Picklist":return Me.WorkflowAttributeType.Picklist;case"State":return Me.WorkflowAttributeType.State;case"Status":return Me.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Me.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Me.WorkflowAttributeType.BigType;default:return Me.WorkflowAttributeType.String}}function e$(e){return e&&e!==Me.WorkflowAttributeType.String?e:void 0}function hne(e){return{__class:Zk,parameterName:"primaryEntity",entityName:e}}function Wk(e){return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Kk,parameters:[e]}}function zk(e,t,r=Me.WorkflowAttributeType.String){return{__class:Yk,type:r,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,entity:hne(t),attributeName:e}}function gne(e,t=Me.WorkflowAttributeType.String){return{__class:Qk,type:t,behavior:Me.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function yne(e){return{__class:Xk,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function t$(e,t){let r=pne[e.operator],n=Wk(zk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=yne(e.right.value??"0"):e.right.kind==="field"?i=zk(e.right.field??"",t,e.right.workflowType):i=gne(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=Wk(i);return{__class:nv,type:rv,typeSet:!1,behavior:Me.AttributeDateTimeBehavior.None,method:Jk,parameters:[r,n,o]}}function r$(e){return typeof e=="object"&&e.__class===nv}function bne(e){return typeof e=="object"&&e.__class===Xk}function Fp(e){return r$(e)&&e.method===Kk&&e.parameters.length>0?Fp(e.parameters[0]):e}function jk(e){if(typeof e!="object"||e.__class!==Yk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Zk)return null;let r=e.attributeName;return r?{field:r,workflowType:e$(e.type)}:null}function n$(e){if(!e)return null;let t=Fp(e);if(!r$(t)||t.method!==Jk||t.parameters.length!==3)return null;let r=t.parameters[0],n=mne[String(r)];if(!n)return null;let i=jk(Fp(t.parameters[1]));if(!i)return null;let o=Fp(t.parameters[2]);if(bne(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=jk(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===Qk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:e$(o.type)}}}return null}function ov(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=iv&&r<=hl}function Pa(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!ov(t)?"invalidDayCount":null}function gl(e){return Pa(e)===null}var Me,Kk,Jk,rv,Yk,Qk,nv,Xk,Zk,pne,mne,iv,hl,gc=k(()=>{"use strict";Me=Ce(Rp());xp();Kk="0",Jk="3",rv="0",Yk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",Qk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",nv="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Xk="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Zk="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";pne={"+":0,"-":1,"*":2,"/":3},mne={0:"+",1:"-",2:"*",3:"/"};iv=0,hl=2147483647});function wne(e){return e.startsWith("__")&&!vne.has(e)}function Cne(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{wne(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function y$(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function La(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Mp(e){return y$(e)||La(e)}function Ene(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function yc(){return{list:[]}}function av(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:br(),languageCode:r,description:t}]}}function lv(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function Vp(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:lv(t),attributeName:e}}function Ra(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Nne(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?w$:v$:b$}function C$(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function _ne(e,t){let r=C$(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${o$}_${i$}`,entityName:i$,relatedAttributeName:o$},attributeName:Sne}:Vp(Ane,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:dv,parameters:[Nne(e),n]}}function E$(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==dv)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===v$?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===w$?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===b$?{bpfField:"ProcessName"}:null}function Up(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===dv){let r=(t.parameters??[])[0];if(typeof r=="string"&&Tne.has(r.replace(/^"+|"+$/g,"")))return!0}return La(e)?Up(e.operand):y$(e)?Up(e.left)||(e.right??[]).some(Up):!1}function A$(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Dne(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function a$(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return A$(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Ine(e){let t=cv[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(La(e))return r&&s$(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:s$(e.left,r,n[0])}function s$(e,t,r){return E$(e)||A$(e)?t||a$(r):!1}function uv(e){if(!e||!Mp(e))return!1;let t=e.conditionOperatoroperator;if(!La(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&uv(e.left)&&r.every(uv)}return Ine(e)}function l$(e){return!e||Dne(e)?!1:Up(e)||!uv(e)}function S$(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??z.WorkflowAttributeType.Lookup,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ra(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Pne(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Rne(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Pne(t)}function Lne(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function $ne(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function Gne(e){let t=Vne.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=qne.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Bne.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function Wne(e){let t=Gne(e.trim());return t!==void 0&&N$(t)?t:e}function N$(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!xne.test(i)||o.length>0&&!Fne.test(o)&&!Mne.test(o)&&!Une.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function zne(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||kne.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=$ne(e);return n==null?r:{value:n,type:t}}return One.includes(t)?Pp(e)?{value:e.trim(),type:t}:r:Lp(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&N$(e)?{value:e.trim(),type:t}:r}function u$(e){return e==="ContainsData"||e==="DoesNotContainData"}function c$(e){return jne.has(e)}function d$(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function f$(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=hc[e.operator]??z.WorkflowConditionOperator.Equal,i=Rne(e,r),o=Zb(r,n);if(e.source==="BusinessProcess"){let l=_ne(e,t);if(u$(e.operator))return d$(l,n);let u=C$(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ra(e.value??"",u)]}}let a=Vp(e.field,t,r,i);if(u$(e.operator))return d$(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=c$(o)&&c$(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[Vp(e.valueField,t,l,Lne(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[S$(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ra(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[qp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=zne(e.value??"",o);s=[Ra(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function Hne(){return Ra(!0,z.WorkflowAttributeType.Boolean)}function Kne(e,t,r){if(e.length===0)return null;let n=f$(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[f$(e[i],r)]}}return n}function Bp(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:Wne(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=n$(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function Jne(e){let t=cv[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=La(e)?e.operand:e.left,i=La(e)?[]:e.right??[],o=E$(n);if(o){let g=i[0];return{id:br(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:Bp(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:br(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function p$(e){if(!e||!Mp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(La(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...Jne(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Mp(o.left)&&r(o.left,a),(o.right??[]).filter(Mp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function qp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return Vp(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return t$(i,n);if(o!=null)return o}return e==="Lookup"&&a?S$(a):e==="Clear"?Ra(null,s??z.WorkflowAttributeType.String):Ra(t??"",z.WorkflowAttributeType.String)}function sv(e,t){return{propertyName:e,propertyValueExpr:t}}function yl(e){return`Step_${e.value++}`}function Cn(e,t){let r=(t.counts[e]??0)+1,n=`${e}${r}`;for(;t.used.has(n);)r+=1,n=`${e}${r}`;return t.counts[e]=r,t.used.add(n),n}function m$(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Cn(t,r)}function Yne(e){return e===g$.StateCode.Activated?"Active":"Draft"}function Qne(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function Xne(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function _$(e,t=1033){return new bl({languageCode:t}).serialize(e)}function T$(e){return new bl().deserialize(e)}var g$,z,vne,cv,dv,b$,v$,w$,Ane,Sne,i$,o$,Tne,One,kne,xne,Fne,Mne,Une,Bne,qne,Vne,jne,fv,bl,pv=k(()=>{"use strict";Yb();g$=Ce(lo());Rk();Qb();ev();gc();z=Ce(Rp());vne=new Set(["__class"]);cv={};for(let e of Object.keys(hc))cv[hc[e]]=e;dv="23",b$="BpfProcess",v$="ActiveStageCategory",w$="SelectedStageCategory",Ane="processid",Sne="stagecategory",i$="processstage",o$="stageid";Tne=new Set(["ActiveStage","SelectedStage","Stage"]);One=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];kne=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];xne=/^\d{4}-\d{2}-\d{2}$/,Fne=/^\d{2}:\d{2}$/,Mne=/^\d{2}:\d{2}:\d{2}$/,Une=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Bne=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],qne=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Vne=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;jne=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);fv={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};bl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>fv[r]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let r=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:r?Number(r.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let n=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??br(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:yc(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??yl(this.stepCounter),stepLabels:{list:[]},specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:lv(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=av(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:m$(n?.id,"ActionStep",this.idCounter),name:n?.name??yl(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??br(),uniqueName:n?.uniqueName??`id_${br().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=lv(this.entityName),n=t.stepName??yl(this.stepCounter),i=t.stepLabels??yc(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:Cn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:Cn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:sv(t.field,qp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:Cn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:Cn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:Cn("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:r};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,l=av(t.stepLabels,s,this.languageCode);return{...o,id:Cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,name:s,controlId:t.field,entity:r,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,l=av(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:Cn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??yl(this.stepCounter),n=Cn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Kne(o.clauses,o.logic,this.entityName),l=a?o.branchName??yl(this.stepCounter):yl(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?m$(o.branchId,"ConditionBranchStep",this.idCounter):Cn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:yc(),conditionExpression:s??(a?Hne():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:yc(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Cn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:yc(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??br():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:Cne(o)};let s=(o.steps?.list??[]).find(l=>l.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(n=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:Xne(r,i?.formId),status:Yne(t.statecode),rootCondition:n,wfomRoot:i,...Qne(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Ene);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=p$(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??br(),displayName:c,clauses:a,logic:s,trueBranch:l,falseBranch:u,isCollapsed:!1,stepName:n?r.name:void 0,branchId:n?i?.id:void 0,branchName:n?i?.name:void 0,...l$(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=p$(n.conditionExpression);return i.length===0&&!l$(n.conditionExpression)?this.deserializeBranch(n.steps?.list??[]):[this.buildConditionNodeFromBranches(t,r,!1)]}deserializeBranch(t){return t.map(r=>r.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(r):this.deserializeAction(r)).filter(r=>r!==null)}parseRecommendationApplyActions(t){let n=(t?.list??[])[0];if(!n)return{applyActions:[]};let i={id:n.id,name:n.name,description:n.description??void 0,stepLabels:n.stepLabels,processId:n.processId,uniqueName:n.uniqueName,actionType:n.actionType},o=n.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(n.steps?.list??[]).filter(l=>l.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(l=>{let u=l.specification;return{id:l.id||br(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Bp(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bp(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetFieldValue",displayName:t.description||t.name||this.label("setFieldValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bp(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==z.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var D$=k(()=>{"use strict";});function nie(e){return typeof e=="object"&&e!==null?e:null}function vl(e){let t=nie(e);if(!t)return!1;if(t.__class===tie){let r=t;return String(r.method)===rie?!0:Array.isArray(r.parameters)&&r.parameters.some(vl)}if(t.__class===eie)return vl(t.operand);if(t.__class===Zne){let r=t;return vl(r.left)||Array.isArray(r.right)&&r.right.some(vl)}return!1}var Zne,eie,tie,rie,I$=k(()=>{"use strict";D$();Zne="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",eie="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",tie="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",rie="23"});function yv(e){return iie.has(e.type)}function mv(e,t,r,n,i,o,a){let s=i.get(r);!s||!R$.has(s.attributeType)||n!=="Value"||a?.operator&&!tv(a.operator)||o.push({nodeId:e,kind:"INVALID_VALUE_TYPE_FOR_FIELD",message:`${t}: please select a record for this lookup field; a typed text value cannot be saved.`,target:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function oie(e,t){let r=t.get(e.field);return!!r&&R$.has(r.attributeType)&&tv(e.operator)}function hv(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function gv(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${hl}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:hl}}}function O$(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Dp(r,l)||a.push({nodeId:e,kind:"INVALID_CLEAR_FOR_FIELD",message:`${t}: Clear is only supported for optional fields with a legacy-compatible type.`,target:s?.target,itemId:s?.itemId,messageKey:"Validation.InvalidClearForField",messageParams:{label:t}})}function Wp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(yv(t))return!0}else if(Wp(t))return!0;return!1}function bv(e,t){if(e.id===t)return e;for(let r of[...e.trueBranch,...e.falseBranch]){if(r.id===t)return r;if(r.kind==="condition"){let n=bv(r,t);if(n)return n}}return null}function aie(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function sie(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||aie(e.rawConditionExpression))}function uie(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||vl(e.rawConditionExpression)}function wl(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=wl(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=wl(n,t);if(i)return i}}return null}function vv(e,t){return{...e,trueBranch:P$(e.trueBranch,t),falseBranch:P$(e.falseBranch,t)}}function P$(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?vv(r,t):r)}function Bo(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Bo(n,t,r):n)}}function Gp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Gp(n,t,r):n)}}function L$(e,t,r,n){return Bo(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function wv(e){return e.length===1&&e[0].kind==="condition"}function die(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(wv(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function fie(e){return!!e&&die(e)<cie}function pie(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(wv(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function k$(e,t,r){let n=pie(e,t);return!n||!fie(n)?e:Bo(e,t,i=>$$(i,r))}function $$(e,t){if(wv(e.falseBranch))return{...e,falseBranch:[$$(e.falseBranch[0],t)]};let r=Cv(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function x$(e,t){let r=wl(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return Bo(e,r.node.id,o=>({...o,falseBranch:i}))}function F$(e,t,r){let n=wl(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return Bo(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Cv(e){return{kind:"condition",id:br(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function M$(e,t){let r={kind:"action",id:br(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:br(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...r,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...r,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...r,type:"SetVisibility",field:"",visible:!0};default:return{...r,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function U$(e){if(!e)return[];let t=[];return B$(e,t),[...new Set(t)]}function B$(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?B$(r,t):"field"in r&&r.field&&t.push(r.field)})}function q$(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return G$(e,n,i,!0),r==="Entity"&&V$(e,n),Wp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function V$(e,t){uie(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&V$(r,t)})}function G$(e,t,r,n=!1){let i=n&&sie(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?Pa(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&!a.value&&!oie(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(qn(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else qn(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!gl(a.expression)?t.push(s==="invalidDayCount"?gv(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):qn(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});qn(a.operator)&&a.valueType==="Value"&&a.value&&Lk(r.get(a.field)?.attributeType)&&!Pp(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=xk(a);qn(a.operator)&&a.valueType==="Value"&&a.value&&Lp(l)&&!Fk(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:Xb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:Xb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),qn(a.operator)&&a.valueType==="Lookup"&&(hv(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),qn(a.operator)&&mv(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&lie.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")G$(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!$p(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:Pa(a.expression);!a.rawExpression&&!gl(a.expression)&&t.push(s==="invalidDayCount"?gv(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!hv(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(mv(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),O$(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:Pa(l.expression);!l.rawExpression&&!gl(l.expression)&&t.push(u==="invalidDayCount"?gv(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?hv(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(mv(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),O$(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var iie,R$,lie,cie,Ev=k(()=>{"use strict";Yb();zb();xp();gc();I$();ev();Qb();iie=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);R$=new Set(["Lookup","Customer","Owner"]);lie=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);cie=10});var W$={};nn(W$,{DAY_COUNT_MAX:()=>hl,DAY_COUNT_MIN:()=>iv,DEFAULT_DESERIALIZE_LABELS:()=>fv,WorkflowJsonMapper:()=>bl,addElseIfInTree:()=>k$,appendToBranch:()=>L$,areFieldKindsCompatible:()=>$p,attributeTypeToWorkflowType:()=>Hk,buildWorkflowEntity:()=>Ak,collectUsedFields:()=>U$,createEmptyAction:()=>M$,createEmptyCondition:()=>Cv,deserializeWorkflowJson:()=>T$,findNode:()=>bv,findParent:()=>wl,getDefaultOperatorForFieldType:()=>Vk,getExpressionModelIssue:()=>Pa,getOperatorsForFieldType:()=>kp,hasAnyTriggerGeneratingAction:()=>Wp,isDayCountValid:()=>ov,isExpressionModelComplete:()=>gl,isOperatorCompatible:()=>Gk,isTriggerGeneratingAction:()=>yv,moveBranchItemInTree:()=>F$,operatorNeedsValue:()=>qn,processTriggerFormIdFromScope:()=>Hb,processTriggerScopeFromScope:()=>jb,removeElseIfInTree:()=>x$,removeNodeFromTree:()=>vv,serializeToWorkflowJson:()=>_$,supportsClearForActionType:()=>Dp,updateActionInTree:()=>Gp,updateConditionInTree:()=>Bo,validateBusinessRule:()=>q$});var z$=k(()=>{"use strict";zb();Sk();pv();pv();Ev();Ev();xp();gc();gc();});var Av=v(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});zp.cloneJson=void 0;function mie(e){return JSON.parse(JSON.stringify(e))}zp.cloneJson=mie});var nx=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.BUSINESS_RULE_NULL_GUID=qo.businessRuleRegistration=qo.BusinessRuleAdapter=void 0;var j$=ct(),bc=(z$(),zr(W$)),H$=jr(),K$=Q(),hie=Av(),hi=cn(),gie=dh(),yie=ct(),bie=sa(),vie=new Set(["ShowErrorMessage","Recommendation"]);function X$(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?X$(n):vie.has(String(n.type))):!1}function wie(e){return Z$((0,hie.cloneJson)(e))}function Z$(e){var t,r;let n=i=>(i??[]).map(o=>Cie(o)?Z$(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(r=e.clauses)!==null&&r!==void 0?r:[],trueBranch:n(e.trueBranch),falseBranch:n(e.falseBranch)}}function Cie(e){return Object.prototype.hasOwnProperty.call(e,"type")?!1:Object.prototype.hasOwnProperty.call(e,"clauses")||Object.prototype.hasOwnProperty.call(e,"trueBranch")||Object.prototype.hasOwnProperty.call(e,"falseBranch")||Object.prototype.hasOwnProperty.call(e,"logic")}function Eie(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new K$.ValidationError("businessRule","(new)","/rootCondition",`rootCondition must be a condition object or null, got ${Array.isArray(e)?"array":typeof e}`);if(Object.prototype.hasOwnProperty.call(e,"type"))throw new K$.ValidationError("businessRule",(t=e.id)!==null&&t!==void 0?t:"(new)","/rootCondition","rootCondition looks like an ACTION (it carries 'type'), but it must be a condition. Wrap the action in a condition's trueBranch instead \u2014 a bare action would compile to an empty rule that saves successfully and does nothing.");return e}var Aie="00000000-0000-0000-0000-000000000000";qo.BUSINESS_RULE_NULL_GUID=Aie;var Sie=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Nie=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],_ie=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Tie=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function Vn(e,t){return e===void 0?t:{...e,...t}}var ka=["kind","id","type","displayName","field","stepName","stepLabels"],J$=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Die={Recommendation:[...ka,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...ka,"lock"],ShowErrorMessage:[...ka,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...ka,...J$],SetDefaultValue:[...ka,...J$],SetBusinessRequired:[...ka,"required"],SetVisibility:[...ka,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function ex(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Sv(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",ex(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function tx(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Iie=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function Oie(e){return Vn(e.bag,{id:e.id,field:e.field,...Sv(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Pie(e){let t=tx(e,Iie);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function Y$(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function Q$(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Rie=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Lie=new Set,kie="INVALID_CLEAR_FOR_FIELD";function $ie(e){let t=n=>{var i;return(0,hi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,hi.isJsonObject)(n))return n;let i={...n};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(r));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var jp=class{toArtifact(t){let r=this.residualBag(t,Nie),n={id:t.ruleId,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:t.rootCondition?this.conditionToJson(t.rootCondition):null};return r&&(n.bag=r),n}fromArtifact(t){let r=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return Vn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,bc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return X$(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,bc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:bie.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,j$.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,bc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(wie(Eie(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,j$.newId)()),u}assignMissingIds(t){return(0,yie.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,hi.isJsonObject)(n)?(rx(n,"/rootCondition",r),r):(r.push((0,hi.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof n}`)),r)}semanticIssues(t,r=[]){let n;try{n=this.fromArtifact(t)}catch(a){return[(0,hi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:$ie(n.rootCondition),o;return r.length===0?o=Rie:r.some(a=>a.requiredLevel!==void 0)?o=Lie:o=new Set([kie]),(0,bc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,hi.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return tx(t,r)}buildWorkflowEntity(t,r){return(0,bc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,_ie),n={id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseToJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemToJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemToJson(i))};return r&&(n.bag=r),n}clauseToJson(t){let r=this.residualBag(t,Tie),n={id:t.id,field:t.field,fieldDisplayName:t.fieldDisplayName,operator:t.operator,valueType:t.valueType,...t.value!==void 0?{value:t.value}:{},...t.valueField!==void 0?{valueField:t.valueField}:{},...t.lookupValue!==void 0?{lookupValue:t.lookupValue}:{},...t.expression!==void 0?{expression:t.expression}:{},...t.rawExpression!==void 0?{rawExpression:t.rawExpression}:{},...t.valueWorkflowType!==void 0?{valueWorkflowType:t.valueWorkflowType}:{}};return r&&(n.bag=r),n}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let r=this.residualBag(t,Die[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Pie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...Y$(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...Y$(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return Q$(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return Vn(n,{kind:"condition",isCollapsed:typeof n.isCollapsed=="boolean"?n.isCollapsed:!1,id:t.id,displayName:t.displayName,logic:t.logic,clauses:t.clauses.map(i=>this.clauseFromJson(i)),trueBranch:t.trueBranch.map(i=>this.branchItemFromJson(i)),falseBranch:t.falseBranch.map(i=>this.branchItemFromJson(i))})}clauseFromJson(t){var r;return Vn(t.bag,{id:t.id,field:t.field,fieldDisplayName:(r=t.fieldDisplayName)!==null&&r!==void 0?r:t.field,operator:t.operator,valueType:t.valueType,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",ex(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!Sie.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Fie(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return Vn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Oie),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return Vn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return Vn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return Vn(t.bag,{...r,type:"SetFieldValue",...Sv(t)});case"SetDefaultValue":return Vn(t.bag,{...r,type:"SetDefaultValue",...Sv(t)});case"SetBusinessRequired":return Vn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return Vn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return Q$(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};qo.BusinessRuleAdapter=jp;function rx(e,t,r){(0,hi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,hi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,hi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?rx(o,`${t}/${n}/${a}`,r):xie(o,`${t}/${n}/${a}`,r)})}function xie(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,hi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Fie(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Mie(){return{adapter:new jp,api:gie.businessRuleApi,publish:(e,t,r)=>(0,H$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,H$.boundEntityPublishScope)(t)}}qo.businessRuleRegistration=Mie});var Cx=v(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.appRegistration=Vo.AppAdapter=Vo.HEADER_NAV_BOOLEAN_RULE=void 0;var Zi=cn(),$t=wo(),wc=Eo(),Uie=jr(),px=Af(),Nv=tf(),_v=Co(),Bie=ct(),qie=oe(),mx=sa(),hx=Q(),gx=nf();Object.defineProperty(Vo,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return gx.HEADER_NAV_BOOLEAN_RULE}});var Yp="7.0.0.0",ix=`<SiteMap IntroducedVersion="${Yp}"></SiteMap>`,ox="/_imgs/imagestrips/transparent_spacer.gif",ax="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",yx=["Entity","Url","DefaultDashboard","Page","GenPageId"],vc="sitemapId",sx="sitemapName",Vie="sitemapNameUnique",lx="aiDescription",ux="[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",Gie=new RegExp(`^(?:\\{${ux}\\}|${ux})$`);function cx(e,t){if(!Gie.test(e.trim()))throw new hx.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function dx(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new hx.ValidationError("app",t,[bx(e)]);return e}function bx(e){return(0,Zi.issue)("/headerAndNavigationRefresh",gx.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function Wie(e){let t=n=>{let i=e[n];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},r=n=>{let i=t(n);if(i!==void 0)try{return(0,qie.normalizeGuid)(i,n)}catch{return}};switch(e.type){case"Entity":return t("entity")&&`Entity:${t("entity").toLowerCase()}`;case"URL":return t("url")&&`URL:${t("url").toLowerCase()}`;case"DashBoard":return r("dashboardId")&&`DashBoard:${r("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return r("genPageId")&&`GenPage:${r("genPageId")}`;default:return}}function zie(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var Qp=class{constructor(t=mx.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Hp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,$t.emptyBag)()}}fromArtifact(t){(0,_v.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,$t.rebuildRaw)(i,(0,wc.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,_v.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,wc.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:ix,ix),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[vc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[sx,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Vie,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[lx,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,_v.installDomShim)();let w=(0,wc.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?C.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let O=(s=t.bag)!==null&&s!==void 0?s:(0,$t.emptyBag)();return{sitemapId:Dv(O,vc)||(t.sitemapId?cx(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Dv(O,sx)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Dv(O,lx))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Nv.HEADER_AND_NAVIGATION_REFRESH]:dx(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Nv.APP_SETTING_ON:Nv.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Bie.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:cx(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:dx(t.headerAndNavigationRefresh,(s=t.id)!==null&&s!==void 0?s:"(new)",!0),...typeof t.published=="boolean"?{published:t.published}:{},...t.components?{components:t.components}:{}}}assignMissingIds(t){let r=t;if(!r||typeof r!="object")return t;let n=r.siteMap;return n&&Array.isArray(n.areas)?n.areas.forEach(Ov):Array.isArray(r.areas)?r.areas.forEach(Ov):Array.isArray(r.groups)?Ov(r):Array.isArray(r.subAreas)?wx(r):"type"in r&&Xp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Zi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(bx(o)),i==null)return r;if(!(0,Zi.isJsonObject)(i))return r.push((0,Zi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Zi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Zi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Zi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Zi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=Wie(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,Zi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,px.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,zie(t))}applyServerIdentity(t,r){let n=r[vc];if(!n)return;t.bag||(t.bag=(0,$t.emptyBag)());let i=t.bag.a.find(o=>o[0]===vc);i?i[1]=n:t.bag.a.push([vc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=Hp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Tv(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Hp(t,null),i=jie(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Tv(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==ox&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,$t.emptyBag)(),l=Kp(a)?[["IntroducedVersion",Yp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,$t.mergeAttrs)(a.a,l),c:(0,$t.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Yp]),t.icon!==void 0?a.push(["Icon",t.icon]):Jp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Iv((0,$t.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,$t.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),o=Kp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Yp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Iv((0,$t.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,$t.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,$t.emptyBag)(),i=Kp(n),o=Kie(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>yx.includes(c));Yie(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):Jp(o,"Icon",ox)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Jp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",ax]):s.push("VectorIcon"):t.type==="GenPage"&&!Hie(o,"VectorIcon")&&a.push(["VectorIcon",ax]);let u=Iv((0,$t.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,$t.mergeAttrs)(o,a,s),c:u}}};Vo.AppAdapter=Qp;function Hp(e,t){let r=(0,wc.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,$t.rawFromNode)((0,wc.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function fx(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function Tv(e,t){var r;let n=fx(e,"Titles")[0];if(!n)return"";let o=fx(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function jie(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Kp(e){return e.a.length===0&&e.c.length===0}function Hie(e,t){return e.some(([r])=>r===t)}function Jp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Dv(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Kie(e,t){let r=Jie(t);return e.filter(([n])=>!yx.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function Jie(e){switch(e){case"Entity":return new Set(["Entity"]);case"URL":return new Set(["Url"]);case"DashBoard":return new Set(["DefaultDashboard","Url"]);case"CustomPage":return new Set(["Page"]);case"GenPage":return new Set(["GenPageId"]);default:return new Set}}function Yie(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(a=t.page)!==null&&a!==void 0?a:""]);break;case"GenPage":e.push(["GenPageId",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Iv(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=Qie(e[i],t,n),o}return r?[Xie(t,n),...e]:e}function Qie(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Zie(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,$t.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(vx(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Xie(e,t){return{n:"Titles",a:[],c:[vx(e,t)]}}function vx(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Zie(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function eoe(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Xp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${eoe(8)}`)}function Ov(e){var t;Xp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])wx(r)}function wx(e){var t;Xp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Xp(r,"subarea")}function toe(e=mx.DEFAULT_LCID){return{adapter:new Qp(e),api:px.appApi,languageSensitive:!0,publish:(t,r)=>(0,Uie.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Vo.appRegistration=toe});var Ex={};nn(Ex,{ActionType:()=>Rv,AppActionOrigin:()=>Bv,AppActionVisibilityType:()=>Uv,ButtonType:()=>kv,CannotUpdateAppActionColumns:()=>roe,Context:()=>xv,IconType:()=>Lv,Location:()=>$v,OnClickEventType:()=>Mv,Scope:()=>Fv,VisibilityType:()=>Pv});var Pv,Rv,Lv,kv,$v,xv,Fv,Mv,Uv,Bv,roe,Ax=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Pv||(Pv={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Rv||(Rv={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Lv||(Lv={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(kv||(kv={}));(function(e){e[e.Form=0]="Form",e[e.HomePageGrid=1]="HomePageGrid",e[e.SubGridStandard=2]="SubGridStandard",e[e.SubGridAssociated=3]="SubGridAssociated",e[e.QuickForm=4]="QuickForm",e[e.Global=5]="Global",e[e.Dashboard=6]="Dashboard"})($v||($v={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(xv||(xv={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Fv||(Fv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(Mv||(Mv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Uv||(Uv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Bv||(Bv={}));roe=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Ox=v(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.assertOneWritePerRow=xt.commandApi=xt.COMMAND_DUPLICATE_ROW_CODE=xt.COMMAND_ROW_NOT_IN_BAR_CODE=xt.COMMAND_TABLE_MISMATCH_CODE=void 0;var qv=Tt(),Ur=fe(),eo=Q(),Br=oe();xt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";xt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";xt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var noe="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Vv(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Br.odataPathLiteral)(t)}')${(0,Br.odataQuery)([["$select","MetadataId"]])}`,i=(0,Ur.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Br.normalizeGuid)(o,"entityMetadataId"):""}function Gv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Br.odataLiteral)(e)}'`}function Cc(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function Sx(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function Nx(e,t,r){let n=await Vv(e,t);if(r){let i=(0,Br.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Cc(t))}return n}xt.commandApi={async get(e,t){let r=t,n=await Vv(e,r),i=Gv(r,n),o=`/appactions${(0,Br.odataQuery)([["$expand",noe],["$filter",i]])}`,a,s=await(0,qv.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Br.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Ur.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=Sx(n,r),o=await Nx(e,i,n.entityMetadataId);return _x(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=Sx(o,t),s=await Nx(e,a,o.entityMetadataId);return _x(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Vv(e,t),n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Ur.deleteRecord)(e,"appactions",o.appactionid)}};async function _x(e,t,r,n,i){let o=r.entityMetadataId?(0,Br.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await ooe(e,t,r,o,n,i),s={};try{await soe(e,a,o,s)}catch(l){throw(0,eo.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Wv(e){return e.replace(/[{}]/g,"").toLowerCase()}function Ix(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=Wv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new eo.SdkError(xt.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}xt.assertOneWritePerRow=Ix;var ioe={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Tx(e,t){let r=ioe[t].exec(e);return r?Wv(r[1]):void 0}async function ooe(e,t,r,n,i,o){var a,s;Ix(t,r);let l=loe(r.rows),u=new Set(l.map(f=>Wv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Tx(m,"entities")===n))throw new eo.SdkError(xt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Cc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Tx(p,"appactions");if(h===void 0||!u.has(h))throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+Cc(t))}if(i&&f.exists){let h=(0,Br.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Ur.isVersionToken)(g))throw Dx(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new eo.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,Br.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Ur.isVersionToken)(p))throw Dx(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await aoe(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new eo.SdkError(xt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Cc(t))}return c}function Dx(e,t,r,n){return new eo.SdkError(Ur.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Cc(e))}async function aoe(e,t,r){let n=`/appactions${(0,Br.odataQuery)([["$select","appactionid"],["$filter",Gv(t,r)]])}`,i=await(0,qv.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Br.normalizeGuid)(a.appactionid,"appactionid"));return o}async function soe(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Ur.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Ur.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Ur.readEtag)(s)}else{let o=(0,Ur.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Ur.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Ur.readCreatedId)(l,"appactionid");u&&(n[(0,Br.normalizeGuid)(u,"appactionid")]=(0,Ur.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Ur.deleteRecord)(e,"appactions",i,o),delete n[i]}function loe(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var jx=v(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.commandRegistration=Cl.CommandAdapter=void 0;var mt=(Ax(),zr(Ex)),Px=jr(),St=cn(),kx=Ox(),$x=ct(),El=oe(),xx=Q(),Hv="$ClientSvg:",Kv=".svg",uoe=2,coe=1,doe=1,Fx="entityMetadataId",foe=new Set(["@odata.etag","IconWebResourceId","OnClickEventJavaScriptWebResourceId","VisibilityFormulaComponentLibraryId","OnClickEventFormulaComponentLibraryId","ContextEntity","_appmoduleid_value","_contextentity_value","_createdby_value","_createdonbehalfby_value","_iconwebresourceid_value","_modifiedby_value","_modifiedonbehalfby_value","_onclickeventformulacomponentlibraryid_value","_onclickeventjavascriptwebresourceid_value","_organizationid_value","_parentappactionid_value","_visibilityformulacomponentlibraryid_value","createdon","modifiedon","overriddencreatedon","overwritetime","componentstate","componentidunique","solutionid","ismanaged","iscustomizable","versionnumber","importsequencenumber","timezoneruleversionnumber","utcconversiontimezonecode","statecode","statuscode","scope"]),Zp=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new xx.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=yoe(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:moe(g,f,qx(h),c)});return{id:c,entityLogicalName:c,commandBars:goe(p),bag:{a:[[Fx,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),appActions:zv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?zv(r).map(l=>l.appactionid):[]),i=zv(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?Ooe(l.row):zx(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,kx.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:Yv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(n=(r=t.entityLogicalName)!==null&&r!==void 0?r:t.id)!==null&&n!==void 0?n:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,$x.assignMissingIds)(t)}normalize(t){let r=Coe(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,St.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,St.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>Gx(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,St.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,St.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,St.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;rm(l.bag)||((0,St.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),Mx((0,St.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Cl.CommandAdapter=Zp;function rm(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function Mx(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;rm(n.bag)||(0,St.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,St.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,St.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,St.isJsonObject)(n.action)?(0,St.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,St.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,St.childObjects)(n,"children",o,"control",r);s.length>0&&Mx(s,`${o}/children`,r)})}function Jv(e){return{a:Object.entries(e)}}function poe(e){return Object.fromEntries(e.a)}function Ec(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Yv(e){let t=Ec(e.bag,Fx);return typeof t=="string"?t:""}function moe(e,t,r,n){var i,o;let a=[],s=[];for(let l of tm(e))l.type===mt.ButtonType.Group?a.push({id:Bx(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:tm((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>em(u,t,r,n)),bag:Jv(l)}):s.push(em(l,t,r,n));return s.length>0&&a.unshift({id:Ioe(n,r),title:"",controls:s}),a}function Qv(e){let t=e.bag?Ec(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function em(e,t,r,n){var i,o,a,s,l;let u=Bx(e.name,n),c={id:u,type:boe(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Jv(e)},d=Ux(e);d&&(c.icon=d);let f=hoe(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of tm(m))if(g.type===mt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Jv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let S of tm((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=em(S,t,r,n);p.push(O),C.push(Qv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(em(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function Ux(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Hv)?e.fonticon.slice(Hv.length)+Kv:e.fonticon}function hoe(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Rx(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function tm(e){return[...e].sort((t,r)=>Rx(t)-Rx(r))}function goe(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function Bx(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let r=e.split("!");return r.length===2?r[1]:e}function yoe(e){switch(e){case mt.Location.Form:case mt.Location.QuickForm:return"MainTab";case mt.Location.HomePageGrid:case mt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function qx(e){switch(e){case"MainTab":return mt.Location.Form;case"HomeTab":return mt.Location.HomePageGrid;default:return mt.Location.SubGridStandard}}function boe(e){switch(e){case mt.ButtonType.Dropdown:return"FlyoutAnchor";case mt.ButtonType.Split:return"SplitButton";default:return"Button"}}function voe(e){switch(e){case"FlyoutAnchor":return mt.ButtonType.Dropdown;case"SplitButton":return mt.ButtonType.Split;default:return mt.ButtonType.Standard}}function woe(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function Vx(e,t){var r,n,i;return((n=(r=e.bag)===null||r===void 0?void 0:r.a.length)!==null&&n!==void 0?n:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function zv(e,t=new Set){var r,n,i,o;let a=[],s=Yv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=qx(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!Vx(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(woe(m)){let h=Aoe(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])Wx(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function Gx(e,t){if(!(0,St.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>Gx(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!rm(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,$x.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Coe(e){let t=new Set,r=(o,...a)=>{if((0,St.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),rm(o.bag)?Ec(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,St.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,St.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,St.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function Wx(e,t,r,n,i,o,a,s=new Set){var l;let u=Eoe(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!Vx(h,s)),f=(h,g,b)=>{Wx(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[Qv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let L=O.id||(S===0?jv(u.appactionid):Zv("flyout-group",`${u.appactionid}#${S}`)),I=Lx(L,t,u.appactionid,n,i,O.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let P of O.childIds){let x=h.get(P);!x||g.has(P)||(g.add(P),f(x,D,b),b+=1)}}let C=w??jv(u.appactionid);for(let S of c){let O=Qv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||jv(u.appactionid);o.push(Lx(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Eoe(e,t,r,n,i,o){let a=Xv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=Ux(s);return e.location!==void 0&&(s.location=e.location),s.type=voe(e.type),s.buttonlabeltext=e.label,Noe(s,e.icon,l),Toe(s,e.action),_oe(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function Aoe(e,t,r,n,i){let o=Xv(e,t,r,n,i);return o.row.type=mt.ButtonType.Group,o.row.grouptitle=e.title,o}function Lx(e,t,r,n,i,o){let a=Xv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command flyout group id")})`,s.type=mt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Xv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=poe(e.bag),a=!0;let u=Ec(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Ec(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new xx.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=Soe(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,El.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==mt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Soe(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:mt.Context.Entity,contextvalue:r.entityLogicalName,scope:mt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,El.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Noe(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,El.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(Kv)?Hv+t.slice(0,t.length-Kv.length):t,e.IconWebResourceId=null}function _oe(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,El.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===coe&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===doe)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Toe(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=uoe,t.webResourceId){let r=(0,El.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function Doe(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function Zv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Doe(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function jv(e){return Zv("flyout-group",e)}function Ioe(e,t){return Zv("loose-group",`${e}|${t}`)}function zx(e){let t={...e};for(let r of foe)delete t[r];return t}function Ooe(e){let t=zx(e);for(let r of mt.CannotUpdateAppActionColumns)delete t[r];return t}function Poe(){return{adapter:new Zp,api:kx.commandApi,publish:(e,t,r)=>(0,Px.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Px.boundEntityPublishScope)(t)}}Cl.commandRegistration=Poe});var Kx=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.chartApi=void 0;var Roe=Tt(),qr=fe(),$a=oe(),Hx="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Loe="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";nm.chartApi={async get(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]);return{raw:(0,qr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,$a.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,$a.odataQuery)([["$select",Hx]]),i=(0,qr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,qr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,$a.odataQuery)([["$select",Loe],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,$a.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Roe.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,qr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,qr.ensureSuccess)(await e.post(o,(0,qr.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,qr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,qr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,$a.normalizeGuid)(t,"id"),a=(0,qr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,qr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,qr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,qr.readEtag)(l)}},delete(e,t){return(0,qr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var dF=v(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.chartRegistration=Sl.ChartAdapter=void 0;var ew=wo(),Jx=cn(),gi=Eo(),Yx=jr(),koe=Kx(),tw=Co(),$oe=ct(),xoe=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Foe=new Map(xoe.map(e=>[e.toLowerCase(),e]));function tF(e){var t;return e&&(t=Foe.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Moe(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Uoe(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${Al(h.series.attribute)}" aggregate="${Al(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${Al(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${Al(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${Al(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${Al(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var im=class{toArtifact(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,gi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,gi.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:om(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:iF(d),categories:oF(d),presentation:rF(f),dataBag:u?(0,gi.projectElementBag)(d):void 0,presentationBag:c?(0,gi.projectElementBag)(f):void 0,rowBag:Boe(t.charttype,t.type)}}fromArtifact(t){(0,tw.installDomShim)();let{datadescription:r,presentationdescription:n}=qoe(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:Qx(t.rowBag,"charttype"),type:Qx(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,s,l;let u=this.fromArtifact(t);return{name:(r=u.name)!==null&&r!==void 0?r:"",description:(n=u.description)!==null&&n!==void 0?n:"",datadescription:(i=u.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=u.charttype)!==null&&s!==void 0?s:0,isdefault:(l=u.isdefault)!==null&&l!==void 0?l:!1}}createDefault(t){var r,n,i,o,a,s,l;(0,tw.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,$oe.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"Column",isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,series:t.series&&t.series.length>0?t.series:[{attribute:"createdon",aggregate:"count"}],categories:t.categories&&t.categories.length>0?t.categories:[{attribute:"createdon",dateGrouping:"month"}],presentation:(l=t.presentation)!==null&&l!==void 0?l:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;return(0,Jx.childObjects)(n,"series","","series",r),(0,Jx.childObjects)(n,"categories","","category",r),r}};Sl.ChartAdapter=im;function Boe(e,t){let r=[];return e!==void 0&&r.push(["charttype",String(e)]),t!==void 0&&r.push(["type",String(t)]),r.length>0?{a:r,c:[]}:void 0}function Qx(e,t){if(!e)return;let r=e.a.find(([i])=>i===t);if(!r)return;let n=parseInt(r[1],10);return Number.isNaN(n)?void 0:n}function om(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return tF(t[r].getAttribute("ChartType"));return"Column"}function rF(e){var t;let r={showLegend:e.getElementsByTagName("Legend").length>0},n=e.getAttribute("Palette");n&&(r.palette=n);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function am(e){return e.getElementsByTagName("fetch")[0]}function nF(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function iF(e){let t=am(e);if(!t)return[];let r=nF(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=tF(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function oF(e){var t;let r=am(e);if(!r)return[];let n=nF(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function qoe(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!Xx(e.dataBag)||!Xx(e.presentationBag)){let c=Uoe({...e,series:n,categories:i});return{datadescription:c,presentationdescription:aae(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=Zx(e.dataBag,"datadefinition",o),s=Zx(e.presentationBag,"Chart",o),l=e.chartType||om(s),u=iF(a);if(!rw(n,u)){let c=nw(a);Voe(o,a,n);let d=nw(a),f=d.length>0?d:n.map(()=>"");aF(o,s,f,c,l)}return rw(i,oF(a))||Goe(o,a,i),e.chartType&&e.chartType!==om(s)&&uF(s,e.chartType),e.presentation&&!rw(e.presentation,rF(s))&&cF(s,e.presentation),{datadescription:(0,gi.serializeNode)(a),presentationdescription:(0,gi.serializeNode)(s)}}function Xx(e){return!!e&&(e.c.length>0||e.a.length>0)}function aF(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function nw(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function Zx(e,t,r){let n={n:t,a:(0,ew.mergeAttrs)(e.a,[]),c:(0,ew.spliceChildren)(e.c,[])};return(0,ew.rebuildRaw)(n,(0,gi.domEngine)(r),null)}function Voe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Yoe(n),r,Xoe,{aliasPrefix:"aggregate_column",addRef:joe,removeRef:Joe})}function Goe(e,t,r){let n=am(t),i=n?.getElementsByTagName("entity")[0];!n||!i||sF(e,t,i,Qoe(n),r,Zoe,{aliasPrefix:"groupby_column",addRef:Hoe,removeRef:Koe})}function sF(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=eae(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),eF(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||zoe(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),eF(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),rae(m)}}function Woe(e){let t=new Set;for(let r of["attribute","measure","category"]){let n=e.getElementsByTagName(r);for(let i=0;i<n.length;i+=1){let o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function zoe(e,t){let r=Woe(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function lF(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function joe(e,t,r){let n=lF(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function Hoe(e,t,r){let n=lF(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function Koe(e,t){let r=e.getElementsByTagName("category");for(let n=0;n<r.length;n+=1)r[n].getAttribute("alias")===t&&r[n].removeAttribute("alias")}function Joe(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!iae(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function Yoe(e){let t=[],r=e.getElementsByTagName("attribute");for(let n=0;n<r.length;n+=1)r[n].getAttribute("aggregate")&&t.push(r[n]);return t}function Qoe(e){var t;let r=[],n=e.getElementsByTagName("attribute");for(let i=0;i<n.length;i+=1)((t=n[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&r.push(n[i]);return r}function Xoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Zoe(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function eae(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function eF(e,t,r,n){n?tae(e,t,n).appendChild(r):t.appendChild(r)}function tae(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function rae(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!nae(t))){let r=t.parentNode;r&&r.removeChild(t)}}function nae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1){let i=n.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function iae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function uF(e,t){let r=e.getElementsByTagName("Series"),n=!1;for(let i=0;i<r.length;i+=1)r[i].getAttribute("ChartType")&&(r[i].setAttribute("ChartType",t),n=!0);if(!n){for(let i=0;i<r.length;i+=1)if(!oae(r[i])){r[i].setAttribute("ChartType",t);return}}}function oae(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName==="Series")return!0}return!1}function cF(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function aae(e,t){let r=(0,gi.parseXmlRoot)(Moe(),"<Chart/>"),n=e.chartType||om(r);uF(r,n),e.presentation&&cF(r,e.presentation);let i=nw((0,gi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&aF(r.ownerDocument,r,i,i.slice(0,1),n),(0,gi.serializeNode)(r)}function rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Al(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function sae(){return{adapter:new im,api:koe.chartApi,publish:(e,t,r)=>(0,Yx.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Yx.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Sl.chartRegistration=sae});var hF=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.dashboardApi=xa.dashboardEntity=void 0;var lae=Tt(),Go=fe(),Nl=oe(),uae=Jg(),fF=vu();function pF(e){return e&&e.toLowerCase()!=="none"?e:void 0}xa.dashboardEntity=pF;var mF="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",cae={select:mF,required:["name","type","objecttypecode","istabletenabled"]},dae="formid,name,type,objecttypecode",fae=0,pae=10;xa.dashboardApi={async get(e,t){let r=(0,Nl.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Nl.odataQuery)([["$select",mF]]),i=(0,Go.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,fF.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Go.readEtag)(i)}},async list(e,t){let r=[`(type eq ${fae} or type eq ${pae})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Nl.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Nl.odataQuery)([["$select",dae],["$filter",r.join(" and ")]])}`;return(await(0,lae.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=pF(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Go.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Go.ensureSuccess)(await e.post(o,(0,Go.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Go.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Go.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,uae.patchSystemForm)(e,(0,Nl.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,cae)},readContentThenToken(e,t){return xa.dashboardApi.get(e,t)},async delete(e,t){let r=(0,Nl.normalizeGuid)(t,"id");return await(0,fF.assertSystemFormKind)(e,r,"dashboard"),(0,Go.deleteRecord)(e,"systemforms",r)}}});var DF=v(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.dashboardRegistration=yi.TILE_CLASS_ID=yi.DashboardAdapter=void 0;var Sc=wo(),En=Eo(),iw=jr(),Ac=cn(),CF=hF(),ow=Co(),Fa=ct(),EF=oe(),AF=sa(),mae=yb(),gF="0",aw="10",hae=new Map([["{E7A81278-8635-4D9E-8D4D-59480B391C5B}","chart"],["{FD2A7985-3187-444E-908D-6624B21F69C0}","iframe"],["{9FDF5F91-88B1-47F4-AD53-C11EFC01A01D}","webresource"],["{EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8}","stream"],["{06375649-C143-495E-A496-C962E5B4488E}","timeline"],["{8C54228C-1B25-4909-A12A-F2B968BB0D62}","powerbi"],["{F9A8A302-114E-466A-B582-6771B2AE0D92}","assistant"]]),gae="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",lm=class{constructor(t=AF.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,ow.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,En.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:yae(t.type),entityLogicalName:(a=(0,CF.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:bae(l),components:yF(l,this.lcid),bag:(0,En.projectElementBag)(l)}}fromArtifact(t){var r;return(0,ow.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:bF(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,mae.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:bF(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?aw:gF,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,ow.installDomShim)();let c=(0,En.parseXmlRoot)(Pae(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Fa.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a:null,enabledForMobile:(s=t.enabledForMobile)!==null&&s!==void 0?s:!1,layoutType:(l=t.layoutType)!==null&&l!==void 0?l:0,components:(u=t.components)!==null&&u!==void 0?u:yF(c,this.lcid),bag:(0,En.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let r=t;(typeof r.id!="string"||r.id.length===0)&&(r.id=(0,Fa.newId)())}return t}validate(t){let r=[],n=(0,Ac.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,Ac.isJsonObject)(u)&&r.push((0,Ac.issue)(`${s}/${l}`,`component-${l}-must-be-object`,`a component ${l} must be a JSON object when present, got ${u===null?"null":typeof u}`))}if((0,Ac.isJsonObject)(o.position)){let l=Nc(o.position);i.has(l)?r.push((0,Ac.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};yi.DashboardAdapter=lm;function yae(e){return String(e??"")===aw?"Interactive":"Standard"}function bae(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function se(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function yF(e,t){let r=[];return se(e,"tabs").flatMap(i=>se(i,"tab")).forEach((i,o)=>{se(i,"columns").flatMap(s=>se(s,"column")).forEach((s,l)=>{se(s,"sections").flatMap(c=>se(c,"section")).forEach((c,d)=>{vae(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function vae(e,t,r,n){se(e,"rows").flatMap(o=>se(o,"row")).forEach((o,a)=>{se(o,"cell").forEach((s,l)=>{let u=wae(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function wae(e,t,r){var n,i;let o=_F((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=se(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=Aae(a),u=Sae(s,l,a),c=Cae(a);return{id:a.getAttribute("id")||o,type:u,name:NF(e,r),classId:s,position:t,colspan:um(e,"colspan",1),rowspan:um(e,"rowspan",1),parameters:l,bag:(0,En.projectElementBag)(e),...c?{icProperties:c}:{}}}function SF(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&n.tagName.toLowerCase()==="icproperties")return n}}function Cae(e){let t=SF(e);return t?(0,En.serializeNode)(t):void 0}function Eae(e,t,r){let n=SF(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,Sc.rebuildRaw)((0,Sc.rawFromNode)((0,En.nodeLikeFromDom)(i)),(0,En.domEngine)(e),null);n&&(0,En.serializeNode)(n)===(0,En.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function NF(e,t){var r,n;let i=se(e,"labels")[0];if(!i)return"";let o=se(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function Aae(e){var t;let r={},n=se(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function Sae(e,t,r){var n;let i=hae.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===gae?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function um(e,t,r){var n;let i=parseInt((n=e.getAttribute(t))!==null&&n!==void 0?n:"",10);return Number.isNaN(i)?r:i}function _F(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function Nae(e,t){let r={n:"form",a:(0,Sc.mergeAttrs)(e.bag.a,[]),c:(0,Sc.spliceChildren)(e.bag.c,[])};return(0,Sc.rebuildRaw)(r,(0,En.domEngine)(t),null)}function bF(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Nae(e,r);return Dae(r,n,e.components,t),_ae(r,n,e.components,t),(0,En.serializeNode)(n)}function _ae(e,t,r,n){let i=TF(t);for(let o of r)i.has(Nc(o.position))||Tae(e,t,o,n)}function Tae(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Rae(t,e,l);for(let x of se(u,"row"))se(x,"cell").some(K=>se(K,"control").length>0)||u.removeChild(x);let c=r.classId||yi.TILE_CLASS_ID[r.type]||yi.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&vF(r.bag,"id")?String(vF(r.bag,"id")):sm((0,Fa.newId)()),m=r.id?sm(r.id):sm((0,Fa.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=se(u,"row"),w=b[b.length-1],C=w?se(w,"cell").reduce((x,K)=>x+um(K,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let O=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),O.appendChild(L),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",sm(c));let D=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(P)){let K=(0,EF.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function vF(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Dae(e,t,r,n){var i;let o=TF(t),a=new Set(r.map(s=>Nc(s.position)));for(let s of r){let l=o.get(Nc(s.position));if(!l)continue;let u=se(l,"control")[0];u&&(Iae(e,l,s.name,n),Oae(e,u,s.parameters),wF(l,"colspan",s.colspan),wF(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Eae(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function TF(e){let t=new Map;return se(e,"tabs").flatMap(n=>se(n,"tab")).forEach((n,i)=>{se(n,"columns").flatMap(a=>se(a,"column")).forEach((a,s)=>{se(a,"sections").flatMap(u=>se(u,"section")).forEach((u,c)=>{se(u,"rows").flatMap(f=>se(f,"row")).forEach((f,m)=>{se(f,"cell").forEach((p,h)=>{var g;_F((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||se(p,"control")[0]&&t.set(Nc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function Nc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Iae(e,t,r,n){if(r===NF(t,n))return;let i=se(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=se(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function Oae(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=se(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,EF.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function wF(e,t,r){um(e,t,1)!==r&&e.setAttribute(t,String(r))}function Pae(e=2){let t=`{${(0,Fa.newId)()}}`,r=`{${(0,Fa.newId)()}}`,n=`{${(0,Fa.newId)()}}`,i=Math.max(1,Math.floor(e));return`<form><tabs><tab id="${t}" name="General" showlabel="true" expanded="true" verticallayout="true"><columns><column width="100%"><sections><section id="${r}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${n}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}yi.TILE_CLASS_ID={chart:"E7A81278-8635-4D9E-8D4D-59480B391C5B",list:"E7A81278-8635-4D9E-8D4D-59480B391C5B",iframe:"FD2A7985-3187-444E-908D-6624B21F69C0",webresource:"9FDF5F91-88B1-47F4-AD53-C11EFC01A01D"};function sm(e){return`{${e.replace(/[{}]/g,"")}}`}function Rae(e,t,r){var n;let i=se(e,"tabs").flatMap(u=>se(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=se(i,"columns").flatMap(u=>se(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=se(o,"sections").flatMap(u=>se(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=se(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Lae(e=AF.DEFAULT_LCID){return{adapter:new lm(e),api:CF.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,iw.publishBoundEntity)(t,n):(0,iw.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,iw.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}yi.dashboardRegistration=Lae});var lw=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.readEveryInOrder=Vr.readInOrder=Vr.plainRead=Vr.resolveReadConcurrency=Vr.MAX_READ_CONCURRENCY=void 0;var IF=Q();Vr.MAX_READ_CONCURRENCY=8;function kae(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Vr.MAX_READ_CONCURRENCY)throw new IF.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Vr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Vr.resolveReadConcurrency=kae;var $ae=e=>({ok:!0,value:e}),sw=e=>({ok:!1,error:e});function xae(e){let t=(async()=>e())().then($ae,sw);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Vr.plainRead=xae;async function OF(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new IF.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(sw);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:sw(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function Fae(e,t,r,n){return OF(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Vr.readInOrder=Fae;function Mae(e,t,r,n){return OF(e,t,r,n,"continue")}Vr.readEveryInOrder=Mae});var HF=v(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});dm.genPageApi=void 0;var cm=Tt(),VF=Es(),Ve=fe(),be=oe(),Gn=pa(),Qe=Q(),GF=ct(),PF=lw();function Uae(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var bi="uxagentprojects",Ua="uxagentprojectfiles",Dc="agentconversationmessages",Ic="uxagentprojectid",jt="uxagentprojectfileid",Ba="agentconversationmessageid",_c=`${Ic},name`,Bae=`${jt},filename,filetype`,WF=2e8,zF=200000001,qa={"MSCRM.IncludeUnpublished":"true"},uw={};function Ma(e,t){return{"MSCRM.VersioningChangeset":e,...qa,...t}}async function fw(e,t,r,n){var i;let o=`/${t}(${r})`+(0,be.odataQuery)([["$select",n]]),a=(0,Ve.ensureSuccess)(await e.get(o,{headers:{...qa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Ve.readEtag)(a)}}async function Oc(e,t,r=qa){let n=`/${Ua}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ve.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Uae(o);if(a)return{status:"available",data:(0,Gn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,Gn.utf8ToBase64)(o)};throw new Qe.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function jF(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function qae(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED",`Refusing to push generative-page file '${t}': its content cannot be written because the injected HttpClient does not implement patchRaw(). A Dataverse File column is not writable through a JSON body, so saving the row without its bytes would report success for a page whose source never uploaded.`);let a=`/${Ua}(${t})/filecontent`,s=(0,Gn.base64ToBytes)(n);(0,be.assertNoControlChars)(r,"generative-page file name"),(0,Ve.ensureSuccess)(await e.patchRaw(a,s,{headers:Ma(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":jF(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function Tc(e,t,r=qa){let n=`/${Ua}`+(0,be.odataQuery)([["$select",Bae],["$filter",`_${Ic}_value eq ${t}`]]);return(await(0,cm.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function cw(e,t){let r=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,cm.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...qa}})}async function RF(e,t){var r,n,i;let{row:o,etag:a}=await fw(e,bi,t,_c),s=new Map;for(let{row:l,etag:u}of await Tc(e,t))s.set((0,be.normalizeGuid)(String((r=l[jt])!==null&&r!==void 0?r:""),jt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function LF(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,be.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Qe.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Qe.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function pw(e){let t=(0,Gn.base64ToUtf8)(e);return(0,Gn.utf8ToBase64)(t)===(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(e))?t:void 0}function Vae(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Ba]:(0,be.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${bi}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?WF:zF}}async function Gae(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,be.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${Dc}`+(0,be.odataQuery)([["$select",`${Ba},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ba} eq ${f}`).join(" or ")]]),u=await(0,cm.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...qa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ba])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,be.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?WF:zF)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Qe.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function dw(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${bi}`,body:(0,Ve.withClientMintedId)({name:t.name},Ic,e),headers:Ma(n)};case"createRow":return{method:"POST",path:`/${Ua}`,body:(0,Ve.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${Ic}@odata.bind`]:`/${bi}(${e})`},jt,(0,be.normalizeGuid)(t.file.id,"file id")),headers:Ma(n)};case"renameRow":return{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ma(n,{"If-Match":"*"})};case"content":{let i=pw(t.data);if(i===void 0)throw new Qe.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,be.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Ua}(${(0,be.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ma(n,{"x-ms-file-name":jF(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Ua}(${t.fileId})`,headers:Ma(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${bi}(${e})`,body:{name:t.name},headers:Ma(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${Dc}`,body:Vae(e,t.turn,r,n)};default:{let i=t;throw new Qe.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function kF(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||pw(r.data)!==void 0)}async function $F(e,t,r,n,i){await(0,VF.postChangeSet)(e,r.map(o=>dw(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function xF(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await qae(e,(0,be.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=dw(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Ve.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>dw(t,l,n,i));if(e.supportsAtomicBatch)await(0,VF.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Ve.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function FF(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await RF(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,be.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,S]of c){let O=u.rows.get(C);O&&(O.filename!==S.name||O.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${O.filename}' (type ${O.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await Oc(e,(0,be.normalizeGuid)(C.file.id,"file id")),O=(0,Gn.bytesToBase64)((0,Gn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,Gn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,Gn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,be.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await Oc(e,C)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await RF(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(C=>{var S,O;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((O=m.rows.get(C))===null||O===void 0?void 0:O.etag)}),g=p.length!==i.size||p.some(C=>!i.has(C)),b={},w=[];for(let[C,S]of m.rows){let O=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;b[C]=O,O!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):Wae({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function MF(e,t,r,n=e.readConcurrency){var i;let o=(0,be.normalizeGuid)(t,"id"),{row:a,etag:s}=await fw(e,bi,o,_c),l=await Tc(e,o),u={},c=[];if(n>1)await(0,PF.readInOrder)(l,n,({row:f})=>{var m;let p=(0,be.normalizeGuid)(String((m=f[jt])!==null&&m!==void 0?m:""),jt);return(0,PF.plainRead)(async()=>({fileId:p,content:await Oc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,be.normalizeGuid)(String((i=f[jt])!==null&&i!==void 0?i:""),jt);u[p]=m;let h=await Oc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await cw(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}dm.genPageApi={get(e,t,r){return MF(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return MF(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,be.normalizeGuid)(t,"id"),o=`/${bi}(${i})`+(0,be.odataQuery)([["$select",_c]]),a=await e.get(o);if(a.status===404)return null;(0,Ve.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await Tc(e,i,uw);for(let{row:g,etag:b}of c){let w=(0,be.normalizeGuid)(String((n=g[jt])!==null&&n!==void 0?n:""),jt);l[w]=b,u.push({...g,content:await Oc(e,w,uw)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[jt])}@${String(w)}`).sort().join("|"),f=()=>new Qe.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Ve.ensureSuccess)(m,e.apiUrl(o));let p=await Tc(e,i,uw);if([(0,Ve.readEtag)(a),(0,Ve.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Qe.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Ve.readEtag)(m)!==(0,Ve.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Ve.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${bi}`+(0,be.odataQuery)([["$select",_c]]);return(await(0,cm.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...qa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[Ic])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,be.normalizeGuid)(r,"id"):(0,GF.newId)(),a=LF(o,i,void 0);qF(e,a),BF(e,o,i);let s=UF(),l=[],u=!0;kF(e,a)?await $F(e,o,a,i,s):{warnings:l,turnRecorded:u}=await xF(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,be.normalizeGuid)(f.id,"file id"))),d=await FF(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,be.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Qe.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await Gae(e,l,s);BF(e,l,u);let c=await Tc(e,l),{row:d,etag:f}=await fw(e,bi,l,_c);if(n&&f&&n!==f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \u2014 another writer edited it. A page row accepts no If-Match validator, so this push would silently overwrite them. Re-fetch the page and re-apply the edit.`);if(!n||!f)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,P;return[(0,be.normalizeGuid)(String((D=I[jt])!==null&&D!==void 0?D:""),jt),{filename:String((P=I.filename)!==null&&P!==void 0?P:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,be.normalizeGuid)(I.id,"file id")));if(!i)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}));for(let[I,D]of Object.entries(i)){let P=I.toLowerCase();if(!p.has(P))continue;let x=b.get(P);if(!D||!x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${D?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(D!==x)throw new Qe.SdkError(Ve.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \u2014 another writer edited it. A file row accepts no If-Match validator, so this push would silently overwrite that change. Re-fetch the page and re-apply the edit.`)}let w=LF(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(qF(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,be.normalizeGuid)(String((P=I[jt])!==null&&P!==void 0?P:""),jt),D]}))};let C=UF(),S=[],O=!0;kF(e,w)?await $F(e,l,w,u,C):{warnings:S,turnRecorded:O}=await xF(e,l,w,u,C);let L=await FF(e,l,w,u,h,b,S);return O?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,be.normalizeGuid)(t,"id"),i=await cw(e,n);await(0,Ve.deleteRecord)(e,bi,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ba])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await cw(e,n)){let u=String((r=l[Ba])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Ve.deleteRecord)(e,Dc,l)}catch(u){u instanceof Qe.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Qe.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${Dc} rows regarding '${n}'.`)}};function UF(){return`uxagentproject_${(0,GF.newId)()}`}function Wae(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function BF(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function qF(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>pw(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Qe.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var cM=v(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.genPageRegistration=Tl.GenPageAdapter=void 0;var zae=HF(),jae=jr(),Ie=cn(),gm=ct(),ym=pa(),Hae=oe(),Va=Q(),iM=v0(),mw=Oh(),Wo=2e8,oM=200000001,ro={source:{name:"src/pages/page.tsx",fileType:Wo},output:{name:"src/pages/page.compiled",fileType:oM},config:{name:"config.json",fileType:Wo},prompt:{name:"firstPrompt.json",fileType:Wo}},aM=Object.keys(ro),Kae=["dataSources","model","connectorBindings","actionBindings"],Jae=["userMessage","agentMessage"],KF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Yae={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},Qae="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function sM(e,t,r){let n=(0,Hae.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function fm(e,t){return sM(e,Yae[t],"id")}function Xae(e,t){let r=sM(e,Qae,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function JF(e){return typeof e=="string"&&e.trim()!==""?e:(0,gm.newId)()}function to(e){return(0,Ie.isJsonObject)(e)?e:{}}function _l(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function pm(e){return JSON.parse(JSON.stringify(e))}function Zae(e){let t=to(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function Rc(e){if(!e||e.status!=="available")return;let t=(0,ym.base64ToUtf8)(e.data);return(0,ym.utf8ToBase64)(t)===e.data?t:void 0}function lM(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&_l((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,iM.isLoadableGenPageOutput)(r)}function ese(e,t){var r;try{return lM(e,t,Rc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function mm(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function YF(e,t){if(t===Wo&&e.includes("page.tsx"))return"source";if(t===oM&&e.includes(".compiled"))return"output";if(t===Wo&&e===ro.config.name)return"config";if(t===Wo&&e===ro.prompt.name)return"prompt"}function QF(e){let t=e.toLowerCase();return aM.some(r=>ro[r].name.toLowerCase()===t)}function hw(e){return Object.fromEntries(e)}function uM(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),hw(i)}function XF(e){var t,r,n;return uM({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},Kae,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function ZF(e){var t,r;return uM({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},Jae,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function eM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=hw(n)),!0}function tM(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=hw(n)),!0}function Lc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var tse=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function rM(e){return Lc(e)?[]:tse.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function nM(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function hm(e){return{status:"available",data:(0,ym.utf8ToBase64)(e)}}function Pc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var bm=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=to(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=to(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:Wo),content:Zae(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=to(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((w=C.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=YF(g.name,g.fileType);b?((s.has(b)||g.name!==ro[b].name)&&(u=!1),s.set(b,g)):(QF(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(Pc(n,i));let c=Pc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=Rc(f.content);if(g===void 0)return a(Pc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=mm(Rc(p.content));if(!g||!eM(c,d,g))return a(Pc(n,i))}let h=s.get("prompt");if(h){let g=mm(Rc(h.content));if(!g||!tM(c,d,g))return a(Pc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!_l((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=rM(t);if(b.length>0)throw new Va.ValidationError("genPage",t.id,b);let w=[],C=r===void 0,S=C&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(Lc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Ge=>{var Ut;return(Ut=I[Ge])!==null&&Ut!==void 0?Ut:fm(S.id,Ge)},P=(Ge,Ut,de)=>{w.push({id:D(Ge),name:ro[Ge].name,fileType:ro[Ge].fileType,content:Ut,unchanged:de})};if(S.source!==void 0){P("source",hm(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Ge=Rc((l=S.bag)===null||l===void 0?void 0:l.output);lM(S,r,Ge)?P("output",{status:"retain"},!0):P("output",hm(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Va.ValidationError("genPage",S.id,[nM()]);if(I.output!==void 0){if(!C&&!_l((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Va.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);P("output",{status:"retain"},!0)}}let x=XF(S),K=!C&&r!==void 0&&_l(XF(r),x);(C||I.config!==void 0||!K)&&P("config",hm(JSON.stringify(x)),K&&I.config!==void 0);let Le=ZF(S),lr=!C&&r!==void 0&&_l(ZF(r),Le);(I.prompt!==void 0||Object.keys(Le).length>0&&!lr)&&P("prompt",hm(JSON.stringify(Le)),lr&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(P=>P.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&_l(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Xae(I,P)}:{};O.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&O.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...O.length>0?{messages:O,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:pm(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!Lc(t)&&!t.newTurn)return t;let u=pm(t);if(delete u.newTurn,!Lc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=aM.find(p=>ro[p].name===d.name&&ro[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,ym.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,eM(u,c,(s=mm(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,tM(u,c,(l=mm(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&KF.test(r.id)?t:{...t,newTurn:{...r,id:(0,gm.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Va.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Va.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,mw.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,mw.buildGenPageLegacyEnums)(a):void 0,d=(0,iM.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Va.ValidationError("genPage",t.id,d.diagnostics.map(rse));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=ese(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=JF(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:JF(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Wo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=pm(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=pm(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:fm(i,"source"),output:fm(i,"output"),config:fm(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,gm.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,gm.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&to(to(n.bag).rows).source!==void 0&&r.push(nM()),r.push(...rM(t)),n.newTurn!==void 0){let s=to(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!KF.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!mw.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=Lc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=to(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(QF(f)||YF(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=to(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Tl.GenPageAdapter=bm;function rse(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function nse(){return{adapter:new bm,api:zae.genPageApi,publish:(e,t)=>(0,jae.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Tl.genPageRegistration=nse});var fM=v(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});wm.reconcileBpfSecurityRoles=void 0;var dM=Tt(),yw=Q(),vm=fe(),kc=oe(),ise="Global",gw={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function ose(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,dM.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(gw).forEach(u=>{let c=a.find(d=>d.PrivilegeType===gw[u]);if(c){let d=(0,kc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function ase(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,vm.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new yw.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,dM.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,kc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function sse(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:ise,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function lse(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,vm.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function use(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await ose(e,t.toLowerCase());for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new yw.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=gw[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,kc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await ase(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await sse(e,l,f);for(let p of m)await lse(e,l,p)}}wm.reconcileBpfSecurityRoles=use});var NM=v(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.bpfApi=void 0;var vr=lo(),pM=Es(),cse=Tt(),Xe=Q(),ht=fe(),An=oe(),dse=fM(),fse=lh(),$c=ch(),pse={"Content-Type":"application/json",Accept:"application/json"},vw={...pse,Prefer:"return=representation"},mse=`category eq ${vr.WorkflowCategory.BusinessProcessFlow} and type eq ${vr.WorkflowTypeCode.Definition} and businessprocesstype eq ${vr.BusinessProcessType.BusinessFlow}`,hse="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",gse="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",yse=["xaml","name","description","processorder"];async function bw(e,t){var r;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let n=String((r=t.record.uniquename)!==null&&r!==void 0?r:"");n!==""&&await(0,dse.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Cw(e,t,r){let n={statecode:vr.StateCode.Activated,statuscode:vr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await SM(e,i,n,r,null);try{return(0,ht.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?EM(s):s}}var CM=new WeakSet;function EM(e){return typeof e=="object"&&e!==null&&CM.add(e),e}function AM(e){return typeof e=="object"&&e!==null&&CM.has(e)}function mM(e){return e instanceof Xe.ConnectionError&&(e.statusCode===0||ht.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function SM(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ht.resendWhile)(ht.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...vw};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ht.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?EM(s):s}}async function hM(e,t,r){return(0,ht.readEtag)(await Cw(e,t,r))}function gM(e,t){return new Xe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Cm(e))}async function xc(e,t){var r;let n=`/workflows(${t})${(0,An.odataQuery)([["$select","statecode"]])}`,i=(0,ht.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Xe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function ww(e,t,r,n,i=null){if((n??await xc(e,t))!==vr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:vr.StateCode.Draft,statuscode:vr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await SM(e,a,o,r,i))}catch(c){return await yM(e,t,c,AM(c))}if(ht.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await yM(e,t,new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ht.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ht.readEtag)(u)}}async function yM(e,t,r,n){let i;try{i=await xc(e,t)}catch{i=void 0}if(i===vr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===vr.StateCode.Activated)throw r;let o=new Xe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===vr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Xe.attachCause)(o,r),o}async function bse(e,t){let r=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,r,null),"restored"}catch{return Ew(e,r)}}async function vse(e,t,r){let n=(0,An.normalizeGuid)(t,"workflowid");try{return await Cw(e,n,r),"restored"}catch(i){return i instanceof Xe.SdkError&&i.code===ht.VERSION_CONFLICT_CODE?"changed":Ew(e,n)}}async function Ew(e,t){try{let r=await xc(e,t);return r===vr.StateCode.Activated?"restored":r===vr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function bM(e,t,r,n){return r?{outcome:await vse(e,t,r),attempted:!0}:n?{outcome:await Ew(e,(0,An.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await bse(e,t),attempted:!0}}function wse(e,t){let r=new Xe.SdkError($c.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,$c.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function vM(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Xe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Xe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Xe.attachCause)(s,n),s}async function Cse(e,t){try{return await xc(e,t),"survived"}catch(r){return r instanceof Xe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Ese(e,t,r){if(r)try{let{deactivated:n,etag:i}=await ww(e,t,r),o=n?i:r;if(o)return await(0,$c.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Cse(e,t)}function Cm(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function wM(e,t){return new Xe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Cm(e)}`)}function Ase(e,t){let r=new Xe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Sse(e,t){let r=new Xe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Cm(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Nse(e,t){let r=new Xe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Xe.attachCause)(r,t),r}function Aw(e){let t={};for(let r of yse)e[r]!==void 0&&(t[r]=e[r]);return t}var _se=["name,processorder","description,name,processorder"];function Tse(e){let{xaml:t,...r}=Aw(e);return typeof t=="string"&&_se.includes(Object.keys(r).sort().join(","))}async function Dse(e,t,r,n){let{xaml:i,...o}=Aw(r),[,a]=await(0,pM.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,An.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ht.readEtag)((0,pM.partResponse)(a))}Em.bpfApi={async get(e,t){let n=`/workflows(${(0,An.normalizeGuid)(t,"id")})${(0,An.odataQuery)([["$select",gse]])}`,i=(0,ht.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ht.readEtag)(i)}},async list(e,t){let r=[mse];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,An.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,An.odataQuery)([["$select",hse],["$filter",r.join(" and ")]])}`;return(await(0,cse.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,An.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ht.ensureSuccess)(await e.post(i,r.record,{headers:vw}),e.apiUrl(i)),a=(0,ht.readEtag)(o);if(!a)throw wM(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await hM(e,n,a)),await bw(e,r)}catch(l){let u=await Ese(e,n,s);throw u==="survived"?Ase(n,l):u==="unknown"?Sse(n,l):l instanceof Xe.SdkError&&l.code===ht.VERSION_CONFLICT_CODE?Nse(n,l):l}if(!s)throw wM(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,An.normalizeGuid)(t,"id"),a=(0,ht.requireEtag)(n,"bpf",o),s=await xc(e,o);if(s===vr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Tse(i.record)){let m=await Dse(e,o,i.record,a);return await bw(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await ww(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw gM(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ht.ensureSuccess)(await e.patch(p,Aw(i.record),{headers:{...vw,"If-Match":m}}),e.apiUrl(p))}catch(b){throw mM(b)&&(d=null),b}let g=(0,ht.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw gM(o,"definition write");try{g=await hM(e,o,g)}catch(b){throw mM(b)&&(d=null),b}f=!0}return await bw(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await bM(e,o,d,AM(m));if(p!=="restored")throw vM(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,An.normalizeGuid)(t,"id"),n=await(0,fse.assertWorkflowKind)(e,r,vr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await ww(e,r,null,void 0,n);try{await(0,$c.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,$c.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await bM(e,r,o,!1);if(s==="changed")throw wse(r,a);if(s!=="restored")throw vM(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var lU=v(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});Il.bpfRegistration=Il.BpfAdapter=void 0;var Am=lo(),Ise=NM(),Sw=wo(),Ga=Eo(),MM=Co(),tn=cn(),Gr=ct(),Wn=Q(),Ose=100,Nw='<?xml version="1.0" encoding="utf-16"?>',_M=1033,UM="mxswa:Workflow",Pse="mxswa:ActivityReference.Properties",Rse="mcwo:StepLabel",Lse="mcwb:Control",TM="mcwb:Control.ControlDisplayName",BM="mcwb:Control.DataFieldName",qM="DataFieldName",DM="ControlDisplayName",VM="Literal",Nm="x:Null",IM="x:String",_w="x:Key",Tw="DisplayName",Tm="Activities",kse="StepLabels",GM="StageId",WM="StageCategory",zM="NextStageId",jM="ProcessStepId",Sm="IsProcessRequired",HM="EntityComposite",KM="StageComposite",JM="StepComposite";function Fc(e){return(0,tn.isJsonObject)(e)?e:{}}function wi(e){if(!e)return[];let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1){let i=r[n];i.nodeType===1&&t.push(i)}return t}function Wa(e,t){var r;return(r=wi(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Ei(e){return Wa(e,Pse)}function wr(e,t){var r;return(r=wi(e).find(n=>n.getAttribute(_w)===t))!==null&&r!==void 0?r:null}function Dl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function YM(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Mc(e){var t;let r=(t=e.getAttribute(Tw))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function QM(e,t){var r;let n=(r=e.getAttribute(Tw))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Tw,i>=0?n.slice(0,i+2)+t:t)}function XM(e,t){let r=wr(e,kse),n=Wa(r,Rse);n&&n.setAttribute("Description",t)}function $se(e){let t=wr(e,WM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:Number(r)}function xse(e){let t=wr(e,zM);if(!t||t.tagName===Nm)return;let r=Ci(t).trim();return r===""?void 0:r}function ZM(e){let t=eU(e);if(!t)return;let r=rU(t,qM,BM);return r===""?void 0:r}function Dw(e,t){let r=wi(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of wi(n))r.push(i)}return null}function eU(e){let t=wr(Ei(e),Tm);return t?Dw(t,Lse):null}function tU(e,t){let r=e.attributes;for(let n=0;n<r.length;n+=1)if(r[n].name===t)return!0;return!1}function rU(e,t,r){var n;return tU(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":qse(e,r)}function OM(e,t,r,n){if(tU(e,t)){e.setAttribute(t,n);return}if(Wa(e,r)){Fse(e,r,n);return}throw new Wn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Fse(e,t,r){let n=Wa(e,t),i=n?Dw(n,VM):null;if(!i)throw new Wn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function nU(e){return Mc(e)}function Dm(e){let t=Wa(e,UM),r=[];for(let n of wi(t).filter(i=>Dl(i,HM))){let i=wr(Ei(n),Tm);for(let o of wi(i).filter(a=>Dl(a,KM)))r.push({el:o,entity:nU(n)})}return r}function Iw(e){let t=wr(Ei(e),Tm);return wi(t).filter(r=>Dl(r,JM))}function Mse(e){let t=Ei(e),r=Ci(wr(t,Sm)).trim().toLowerCase(),n=ZM(e),i={id:Ci(wr(t,jM)),name:Mc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Use(e,t){let r=Ei(e),n=$se(r),i=xse(r),o={id:Ci(wr(r,GM)),name:Mc(e),entityLogicalName:t,steps:Iw(e).map(Mse)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Bse(e){return Dm(e).map(({el:t,entity:r})=>Use(t,r))}function vi(e){return new Wn.NotImplementedError("bpf-structural-authoring",`${e} is not supported yet (this phase authors identity, stage/step names, step required, step field binding, stage categories, and adding/removing/reordering stages & steps on a single-table process; branching, actions, security-role wiring and multi-table processes land in later phases). The rest of the process round-trips losslessly.`)}function qse(e,t){var r;let n=Wa(e,t),i=n?Dw(n,VM):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Ow(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Ow(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function iU(e){return wr(Ei(e),Tm)}function Vse(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Gr.newId)(),{body:a}=Im(Pw(i,(0,Gr.newId)(),t.id,o));return Ow(e,Dm((0,Ga.parseXmlRoot)(a,"<Activity/>"))[0].el)}function Gse(e,t){let{body:r}=Im(Pw("account",(0,Gr.newId)(),(0,Gr.newId)(),t.id));return Ow(e,Iw(Dm((0,Ga.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function oU(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function aU(e,t,r,n){let i=wr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw vi(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Nm&&Ci(i).trim()!==""){let s=t.createElement(Nm);s.setAttribute(_w,r),o.replaceChild(s,i)}return}if(i.tagName===IM){Ci(i).trim()!==n&&YM(i,t,n);return}let a=t.createElement(IM);a.setAttribute(_w,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function Wse(e,t,r){aU(e,t,WM,r===void 0?void 0:String(r))}function zse(e,t,r){aU(e,t,zM,r)}function sU(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(r(e[n])!==t[n])return!1;return!0}function PM(e){return Ci(wr(Ei(e),GM))}function RM(e){return Ci(wr(Ei(e),jM))}function LM(e,t,r){var n,i,o,a;let s=Ei(e);r.name!==Mc(e)&&(QM(e,r.name),XM(s,r.name));let l=Ci(wr(s,Sm)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=wr(s,Sm);if(!u)throw vi(`setting '${Sm}' on a step whose xaml does not expose that slot`);YM(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=ZM(e))!==null&&o!==void 0?o:"")){let u=eU(e);if(!u)throw new Wn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";OM(u,qM,BM,c),c!==""&&rU(u,DM,TM)===""&&OM(u,DM,TM,c)}}function kM(e,t,r,n){var i;let o=Ei(e);if(!o)throw new Wn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Mc(e)&&(QM(e,r.name),XM(o,r.name)),Wse(o,t,r.category),zse(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw vi("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw vi("stage actions or conditional branching");let a=iU(e);if(!a)throw new Wn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Wn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Iw(e);if(sU(l,s.map(d=>d.id),RM)){l.forEach((d,f)=>LM(d,t,s[f]));return}let u=new Map(l.map(d=>[RM(d),d]));if(wi(a).some(d=>!Dl(d,JM)))throw vi("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:Gse(t,d)});oU(a,c),c.forEach((d,f)=>LM(d,t,s[f]))}function jse(e,t,r){let n=Wa(e,UM);if(!n)throw new Wn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw vi("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Wn.InvalidArgumentError("a BPF must have at least one stage");let i=Dm(e),o=i.map(f=>f.el);if(sU(o,r.stages.map(f=>f.id),PM)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw vi(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);kM(f,t,h,h.nextStageId)});return}let a=wi(n).filter(f=>Dl(f,HM));if(a.length!==1)throw vi("adding, removing or reordering stages on a multi-table process");let s=a[0],l=nU(s),u=iU(s);if(!u)throw new Wn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(wi(u).some(f=>!Dl(f,KM)))throw vi("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw vi(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[PM(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Vse(t,f,l)});oU(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;kM(f,t,r.stages[m],p)})}function Im(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function Hse(e){var t,r,n,i,o,a;(0,MM.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,Sw.mergeAttrs)(s.a,[]),c:(0,Sw.spliceChildren)(s.c,[])};return{root:(0,Sw.rebuildRaw)(m,(0,Ga.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Nw,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Pw(e.entityLogicalName,(0,Gr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Gr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Gr.newId)()),{body:d}=Im(c);return{root:(0,Ga.parseXmlRoot)(d,"<Activity/>"),prolog:Nw,eol:"lf"}}function Kse(e){let{root:t,prolog:r,eol:n}=Hse(e);jse(t,t.ownerDocument,e);let i=(0,Ga.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function Jse(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var _m=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,MM.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((r=i.name)!==null&&r!==void 0?r:""),entityLogicalName:String((n=i.primaryentity)!==null&&n!==void 0?n:""),status:Number(i.statecode)===1?"Active":"Draft",stages:[]};if(i.uniquename&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=Im(o),u=(0,Ga.parseXmlRoot)(l,"<Activity/>");a.stages=Bse(u),a.bag={xaml:(0,Ga.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:t.name,uniquename:Jse(t),primaryentity:t.entityLogicalName,xaml:Kse(t),category:Am.WorkflowCategory.BusinessProcessFlow,type:Am.WorkflowTypeCode.Definition,businessprocesstype:Am.BusinessProcessType.BusinessFlow,scope:Am.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Ose};t.description!==void 0&&(n.description=t.description);let i={record:n,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new Wn.InvalidArgumentError('securityRoles require the BPF to be Active \u2014 the backing table they grant access to is created on activation; set status to "Active" to wire security roles');i.securityRoles=t.securityRoles}return i}createDefault(t){var r,n,i;let o=t.stages&&t.stages.length>0?t.stages.map(xM):[xM({id:(0,Gr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Gr.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"New business process flow",entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",status:(i=t.status)!==null&&i!==void 0?i:"Draft",stages:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Fc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Gr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,tn.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof n}`)),r;let i=Array.isArray(n)?n:[];i.length>30&&r.push((0,tn.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Fc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,tn.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,tn.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,tn.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,tn.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Fc(h).id=="string"?h.id.trim():"";w===""?r.push((0,tn.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,tn.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!$M(i,d.branch.nextStageId)&&r.push((0,tn.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!$M(i,d.nextStageId)&&r.push((0,tn.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,tn.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=Yse(i);return s>=0&&r.push((0,tn.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Il.BpfAdapter=_m;function Yse(e){let t=new Map(e.map(r=>[Fc(r).id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function $M(e,t){return e.some(r=>Fc(r).id===t)}function xM(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(FM):[FM({id:(0,Gr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(r=e.entityLogicalName)!==null&&r!==void 0?r:"",steps:n};return e.category!==void 0&&(i.category=e.category),e.nextStageId!==void 0&&(i.nextStageId=e.nextStageId),e.relationshipName!==void 0&&(i.relationshipName=e.relationshipName),e.actions!==void 0&&(i.actions=e.actions),e.branch!==void 0&&(i.branch=e.branch),i}function FM(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Gr.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(r.fieldName=e.fieldName),e.required!==void 0&&(r.required=e.required),r}function Pw(e,t,r,n){return`${Nw}<Activity x:Class="XrmWorkflow00000000000000000000000000000000" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mcwb="clr-namespace:Microsoft.Crm.Workflow.BusinessProcessFlowActivities;assembly=Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mcwo="clr-namespace:Microsoft.Crm.Workflow.ObjectModel;assembly=Microsoft.Crm, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxs="clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:mxswa="clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:srs="clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" xmlns:this="clr-namespace:" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><x:Members><x:Property Name="InputEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /><x:Property Name="CreatedEntities" Type="InArgument(scg:IDictionary(x:String, mxs:Entity))" /></x:Members><this:XrmWorkflow00000000000000000000000000000000.InputEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.InputEntities><this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><InArgument x:TypeArguments="scg:IDictionary(x:String, mxs:Entity)" /></this:XrmWorkflow00000000000000000000000000000000.CreatedEntities><mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings><mxswa:Workflow><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.EntityComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="EntityStep1: ${e}"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StageComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StageStep2: New Stage"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><mxswa:ActivityReference AssemblyQualifiedName="Microsoft.Crm.Workflow.Activities.StepComposite, Microsoft.Crm.Workflow, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" DisplayName="StepStep3: New Step"><mxswa:ActivityReference.Properties><sco:Collection x:TypeArguments="Variable" x:Key="Variables" /><sco:Collection x:TypeArguments="Activity" x:Key="Activities"><Sequence DisplayName="ControlStep4"><mcwb:Control ControlId="${t}" IsSystemControl="False" IsUnbound="False" SystemStepType="0"><mcwb:Control.ClassId><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ClassId><mcwb:Control.ControlDisplayName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.ControlDisplayName><mcwb:Control.DataFieldName><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.DataFieldName><mcwb:Control.Parameters><InArgument x:TypeArguments="x:String"><Literal x:TypeArguments="x:String" Value="" /></InArgument></mcwb:Control.Parameters></mcwb:Control></Sequence></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Step" LabelId="${n}" LanguageCode="${_M}" /></sco:Collection><x:String x:Key="ProcessStepId">${n}</x:String><x:Boolean x:Key="IsProcessRequired">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><sco:Collection x:TypeArguments="mcwo:StepLabel" x:Key="StepLabels"><mcwo:StepLabel Description="New Stage" LabelId="${r}" LanguageCode="${_M}" /></sco:Collection><x:String x:Key="StageId">${r}</x:String><x:Null x:Key="StageCategory" /><x:Null x:Key="NextStageId" /></mxswa:ActivityReference.Properties></mxswa:ActivityReference></sco:Collection><x:Null x:Key="RelationshipName" /><x:Null x:Key="AttributeName" /><x:Boolean x:Key="IsClosedLoop">False</x:Boolean></mxswa:ActivityReference.Properties></mxswa:ActivityReference></mxswa:Workflow></Activity>`}function Qse(){return{adapter:new _m,api:Ise.bpfApi,languageSensitive:!0}}Il.bpfRegistration=Qse});var uU=v(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});Om.buildRegistrations=void 0;var Xse=tk(),Zse=Ck(),ele=nx(),tle=Cx(),rle=jx(),nle=dF(),ile=DF(),ole=cM(),ale=lU();function sle(e){let t=new Map;return t.set("form",(0,Xse.formRegistration)(e)),t.set("view",(0,Zse.viewRegistration)()),t.set("businessRule",(0,ele.businessRuleRegistration)()),t.set("app",(0,tle.appRegistration)(e)),t.set("command",(0,rle.commandRegistration)()),t.set("chart",(0,nle.chartRegistration)()),t.set("dashboard",(0,ile.dashboardRegistration)(e)),t.set("genPage",(0,ole.genPageRegistration)()),t.set("bpf",(0,ale.bpfRegistration)()),t}Om.buildRegistrations=sle});var AU=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var za=Tt(),Sn=fe(),He=oe(),cU=ct(),Ze=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var gU={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},lle=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>gU[e]===t).map(([e])=>e)),ule={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Rw(e){return ule[e]}var Pm=1e6;function cle(e,t){let r=Rw(t),n=()=>{throw new Ze.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Pm} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Pm?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Pm).length||Number(s)>Pm?n():s}}return n()}function dle(e,t){let r=Rw(t);return r?e===r.enabled:e!=="0"}async function fle(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function ple(e,t){var r,n;let i=`/appmodules${(0,He.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${l.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ze.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var dU=new WeakMap;async function mle(e,t){var r,n;let i=dU.get(e);if(i||(i=new Map,dU.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,He.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,He.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function hle(e,t,r){var n,i;let o=await mle(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,He.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ze.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var gle=4,yle=500,fU=20,pU=3e4;function ble(e){if(e===void 0)return gle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${fU}; got ${e}.`);return Math.min(fU,Math.max(1,Math.floor(e)))}function vle(e){if(e===void 0)return yle;if(!Number.isFinite(e))throw new Ze.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${pU}; got ${e}.`);return Math.min(pU,Math.max(0,Math.floor(e)))}async function wle(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await hle(e,m,n),f===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(m){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await Rm(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function yU(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Rw(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Rm(e,t,r={}){var n;let i=[`SettingName='${(0,He.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,He.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=Rm;async function bU(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Sn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=bU;async function Cle(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Rm(e,i,t);r[n]={enabled:yU(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Cle;async function Ele(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ze.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=ble(n.verifyAttempts),a=vle(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=gU[p];g&&s.push({feature:p,setting:g,requestedValue:cle(h,p)})}let l=[],u=n.appModuleId?(0,He.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await ple(e,t);if(p&&(0,He.normalizeGuid)(p,"appModuleId")!==u)throw new Ze.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await fle(e,t)),c),f=new Map,m=async p=>{if(lle.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Rm(e,h);f.set(h,{enabled:yU(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await bU(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await wle(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let C=dle(g,p)?await m(p):void 0;C&&!C.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${C.setting}' reads '${C.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=Ele;var vU="GptPowerPrompt",Ale='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function wU(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=wU;async function Sle(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,He.odataPathLiteral)(t)}')${(0,He.odataQuery)([["$select","MetadataId"]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,za.describeMalformedValue)(o)}`);return o}async function CU(e){var t,r;let n=`/msdyn_aitemplates${(0,He.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${vU}'`],["$top",1]])}`,i=(0,Sn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(t=i.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(o))throw new Ze.ConnectionError(e.apiUrl(n),i.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(o)}`);return((r=o[0])!==null&&r!==void 0?r:{}).msdyn_aitemplateid}function EU(e){return`${e} row summary`}async function Nle(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,He.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,Sn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await CU(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===EU(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function _le(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ze.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(s)}`);let l=s[0];if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Sle(e,t.entityLogicalName),c=await CU(e);if(c===void 0)throw new Ze.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${vU}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,cU.newId)(),f=(0,cU.newId)(),m=JSON.stringify(wU(t)),p={ModelId:d,RunConfigurationId:f,ModelName:EU(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:Ale,RunConfiguration:""};(0,Sn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,Sn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,Sn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=_le;async function Tle(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,He.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,He.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,Sn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ze.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,za.describeMalformedValue)(a)}`);let s=a[0];if(!s)return;let l=(0,He.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,He.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Nle(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await mU(e,f,`${f}${(0,He.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${hU(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await mU(e,p,`${p}${(0,He.odataQuery)([["$select","msdyn_aimodelid"]])}`,Ile);if(h.kind==="failed")throw(0,Ze.attachCause)(new Ze.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${hU(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}}Te.removeRowSummary=Tle;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Dle="0x8004f01f";function Ile(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Dle}function Ole(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function mU(e,t,r,n=()=>!1){let i;try{let o=await(0,Sn.resendWhile)(Ole,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,Sn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function hU(e){return e instanceof Error?e.message:String(e)}});var _U=v(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.findArtifact=Ol.resolveArtifact=void 0;var Ht=oe(),no=Zd(),Ple=Af(),Rle=Tt(),Lle=fe(),SU=Q();async function NU(e,t,r){let n="/uxagentprojects"+(0,Ht.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Ht.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Rle.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function kle(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Ple.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Ht.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Lle.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,no.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Ht.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Ht.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,no.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Ht.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Ht.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,no.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Ht.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Ht.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,no.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Ht.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,no.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Ht.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return NU(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}Ol.resolveArtifact=kle;async function $le(e,t,r){var n,i,o,a,s,l;let u=(0,Ht.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Ht.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,no.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Ht.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await NU(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new SU.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=xle(t,u,c,r),f=t!=="app",m=await(0,no.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new SU.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}Ol.findArtifact=$le;function xle(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,Ht.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var DU=v(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});km.seedRecordGraph=void 0;var TU=Zd(),Fle=$d(),Lm=oe(),Mle=Q();async function Ule(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Fle.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let P=D.parentEntity.toLowerCase(),x=(s=d(P))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Mle.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,Lm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Le=(0,Lm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Le})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Lm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Lm.odataLiteral)(x)}'`).join(" or "),P=await(0,TU.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let P=D.toLowerCase(),x=C.get(P);if(x!==void 0)return x;let K=w.push(L)-1;return C.set(P,K),K}return w.push(L)-1}),O=w.length?await(0,TU.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}km.seedRecordGraph=Ule});var MU=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.getEntityPrivileges=or.addEntityPrivilegesToRole=or.deleteSecurityRole=or.createPersonaRole=or.createSecurityRole=or.SDK_ROLE_MARKER=void 0;var zn=fe(),Ft=oe(),rn=Q(),$m={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},kw={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},IU={user:1,businessUnit:2,parentChild:3,organization:4},Lw={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};or.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Ble(e){return Object.prototype.hasOwnProperty.call($m,e)?$m[e]:void 0}function qle(e){return Object.prototype.hasOwnProperty.call(kw,e)}var OU=new WeakMap,PU=new WeakMap;async function kU(e,t){var r,n;(0,Ft.assertODataName)(t,"entity logical name");let i=OU.get(e);i||(i=new Map,OU.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Ft.odataPathLiteral)(t)}')${(0,Ft.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,zn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new rn.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Vle(e){var t,r,n;let i=PU.get(e);if(i)return i;let o=`/businessunits${(0,Ft.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&r!==void 0?r:[])[0])===null||n===void 0?void 0:n.businessunitid;if(!l)throw new rn.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Ft.normalizeGuid)(l,"businessUnitId");return PU.set(e,u),u}async function $U(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new rn.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!qle(o))throw new rn.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await kU(e,i.entity);for(let s of i.access){let l=Ble(s);if(!l)throw new rn.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new rn.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Lw[o];if(u[c]===!1)throw new rn.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Ft.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new rn.InvalidArgumentError(`Entities '${p}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}f.scope=IU[o]>IU[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function Gle(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:kw[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,zn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function RU(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Ft.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,zn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function Wle(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Ft.normalizeGuid)(l,"teamId");if(!await RU(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Ft.normalizeGuid)(l,"userId");if(!await RU(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,zn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function LU(e,t,r){var n,i;let o=`/roles${(0,Ft.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Ft.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,zn.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(d=>!!d.roleid);if(l.length===0)return;let u=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===or.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new rn.InvalidArgumentError(`A role named '${t}' already exists in this business unit and was not created by the SDK; refusing to modify or assign it. Choose a different persona/role name.`);if(l.length>1)throw new rn.InvalidArgumentError(`Multiple (${l.length}) SDK-owned roles named '${t}' exist in this business unit; refusing to reuse one arbitrarily. Remove the duplicate role(s) and retry.`);let c=l[0].roleid;return c?(0,Ft.normalizeGuid)(c,"roleId"):void 0}function zle(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Ft.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Ft.normalizeGuid)(n,"userId"))}}function xU(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function FU(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Ft.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Vle(e),a=await $U(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=zle(t.assignTo),l=await LU(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:or.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,zn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Ft.normalizeGuid)((0,zn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await LU(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await Gle(e,l,a,u);let c=await Wle(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:xU(a),assignedTeams:c.teams,assignedUsers:c.users}}or.createSecurityRole=FU;async function jle(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new rn.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return FU(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}or.createPersonaRole=jle;async function Hle(e,t){let n=`/roles(${(0,Ft.normalizeGuid)(t,"roleId")})`;(0,zn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}or.deleteSecurityRole=Hle;async function Kle(e,t,r){let n=(0,Ft.normalizeGuid)(t,"roleId");if(r.length===0)throw new rn.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await $U(e,r),o={Privileges:i.map(s=>({Depth:kw[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,zn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),xU(i)}or.addEntityPrivilegesToRole=Kle;var Jle=new Map(Object.keys($m).map(e=>[$m[e],e]));async function Yle(e,t){return(await kU(e,t)).map(n=>{let i=Object.keys(Lw).filter(a=>n[Lw[a]]!==!1),o=Jle.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}or.getEntityPrivileges=Yle});var tB=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.createMakerSdk=Er.MakerSdk=Er.PUSH_NOT_ATTEMPTED_CODE=Er.ALREADY_EXISTS_CODE=void 0;var UU=dh(),BU=jr(),Z=Q(),Nn=Xa(),Qle=CE(),QU=DE(),Pl=kE(),Xle=ph(),Zle=tA(),Rl=iA(),eue=bA(),tue=SA(),rue=tS(),qU=QS(),Mt=$d(),$w=e0(),VU=l_(),xm=vu(),io=Zd(),Fm=g_(),Ll=tf(),nue=nf(),ar=Jd(),iue=aT(),oue=v0(),aue=T0(),GU=w0(),sue=uU(),Mm=ct(),lue=sa(),Ai=Av(),_n=bh(),xw=lw(),uue=3e5,Cr=fe(),ja=oe(),kl=AU(),WU=_U(),cue=DU(),due=Ub(),Uc=MU(),XU=Symbol("cds-maker-sdk.committedWrite");function fue(e){return typeof e=="object"&&e!==null&&(e[XU]=!0),e}function pue(e){return typeof e=="object"&&e!==null&&e[XU]===!0}var mue={fileConcurrency:1},Fw="SOLUTION_COMPONENT_UNCLASSIFIED",hue=2,gue=4,yue="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function zU(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:yue}:{}}}function jU(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:zo(t)}}function HU(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,Cr.nowIso)(),isDirty:!1}}var bue=new Set(["entity","appmodule","dashboard","uxagentproject"]);function vue(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,ja.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function wue(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new QU.WorkspaceManager(Eue,e.instanceUrl,(0,Xle.assertStorageContract)(t))}Er.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Cue="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";Er.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Eue="<injected workspaceStorage>",Um=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,xw.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:lue.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:uue,this.compiler={load:(0,oue.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=wue(t),this.versions=new Pl.VersionManager(this.workspace),this.dataverse=new Zle.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new rue.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,sue.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,_n.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,Cr.nowIso)()},b)}return(0,Ai.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,Ai.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,ar.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(zU(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(HU(a,o,s))}catch(a){i.push(jU(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,Cr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,xw.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(zU(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(HU(a.type,o,s))}catch(a){n.push(jU(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,mue);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,xw.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,Rl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,eue.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,Rl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,tue.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,Rl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Mt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Mt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Mt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Mt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,$w.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,$w.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Mt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Mt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Mt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Mt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Mt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Mt.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large})),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,ja.xmlText)(t)}</entity></entities></importexportxml>`;(0,Cr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Mt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Mt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Mt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Mt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Mt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Mt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Uc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Uc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Uc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Uc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Uc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,io.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,io.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,io.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,io.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,io.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,io.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,io.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,cue.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,WU.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,WU.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,aue.deleteAppCascade)(this.dataverse,t,r),i=(0,ja.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,io.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,io.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Fm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Fm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Fm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Fm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Ll.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Ll.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:nue.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Ll.setAppSetting)(this.dataverse,t,Ll.HEADER_AND_NAVIGATION_REFRESH,r?Ll.APP_SETTING_ON:Ll.APP_SETTING_OFF)}getSolution(t){return(0,ar.getSolution)(this.dataverse,t)}createPublisher(t){return(0,ar.createPublisher)(this.dataverse,t)}createSolution(t){return(0,ar.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,ar.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,ar.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,ar.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,ar.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,ar.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,ar.getDeploymentSettingsTemplate)(this.dataverse,t)}registerPcfControl(t,r){let n=()=>(0,iue.registerPcfControl)(this.dataverse,t,r);return r?.publishAll===!0?this.schemaWrite(void 0,n):n()}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,ar.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,QU.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,_n.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=Nn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,Qle.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=Nn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=oo(s)&&oo(i)?{...s,...i}:i;return Nn.JsonPointer.set(a,n,(0,Ai.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=Nn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!oo(l)||!oo(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,Ai.cloneJson)(i[f]),p=(0,Mm.isValueMapKey)(f)||(0,Mm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>oo(h)?this.assignMissingIds(t,h):h):oo(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))Nn.JsonPointer.set(s,Nn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,Mm.pointerTouchesValueMap)(n)?(0,Ai.cloneJson)(i):this.assignMissingIds(t,(0,Ai.cloneJson)(i)),c=_ue(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=Nn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=Nn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");Nn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),YU(c);let f=Nn.JsonPointer.resolve(l,JU(n));return Array.isArray(f)&&f!==c&&YU(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(Nn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return Nn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,JU(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,kl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,kl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,kl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,kl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,kl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,kl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,due.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,BU.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&pue(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,Ai.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=vue(a),f;if(d)try{await(0,BU.publishXml)(this.dataverse,d)}catch(p){f=zo(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!bue.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,_n.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:zo(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,Cr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!Sue(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,_n.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,Cr.isVersionToken)(o)||!ZU(a,t.heldSiblings)||!eB(a)||!(o!==t.heldEtag||!(0,_n.deepEqual)(a??void 0,t.heldSiblings))||!(0,_n.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,Cr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${zo(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,_n.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,_n.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,Cr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i,o,a,s,l;if(t!=="app"){let u=this.registrations.get(t);return u?.api.getPublished?this.verifyPublishedContent(u,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let u=`/appmodules(${(0,ja.normalizeGuid)(r,"id")})${(0,ja.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},f=n;if(!f)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let m=[];return((o=f.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&m.push("name"),((s=f.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&m.push("description"),m.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${m.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:zo(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,_n.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,_n.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:zo(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,Rl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let P=await this.createWithMintedId(m,d,f,g,p);if("adopted"in P)return await this.persistAdoption(d,f,p,P.adopted);w=P.written}b=!0;let C=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,O=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,C,O.artifact,h&&C===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,_n.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,C,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,C,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(O.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},C===f?h:void 0),{type:d,id:C,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var P;let x=(P=m.publishScope)===null||P===void 0?void 0:P.call(m,C,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let C=(0,Z.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},O={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(O).length>0?{siblingEtags:O}:{}},h)}if(w instanceof Z.SdkError&&w.code===Er.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===UU.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===Cr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,GU.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?fue(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==Pl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${Pl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,$w.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,VU.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n,u)+(this.createRecovery==="adoptExact"?` ${KU(Cue)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==Cr.VERSION_CONFLICT_CODE||(0,GU.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,VU.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,`${Mw(r,n)} ${KU(l.refused)}`)}throw new Z.SdkError(Er.ALREADY_EXISTS_CODE,Mw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,_n.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:Pl.PROJECTION_VERSION,fetchedAt:(0,Cr.nowIso)(),snapshot:(0,Ai.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=Rl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(P=>P.entityLogicalName===L).map(P=>P.fieldName);try{let P=await(0,Rl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,P,x;return(P=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,C=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),O=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:Nue(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...C!==void 0?{baseLanguageCode:C}:{},...O?{pcf:O}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,qU.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,qU.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(Er.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:zo(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,Mm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case ar.SolutionComponentType.SavedQuery:return"view";case ar.SolutionComponentType.SavedQueryVisualization:return"chart";case ar.SolutionComponentType.AppModule:return"app";case ar.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case ar.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,xm.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(Fw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,xm.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,ja.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,ja.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,Cr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,xm.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(Fw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===hue)return"businessRule";if(a===gue){let s=(0,xm.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(Fw,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};Er.MakerSdk=Um;function Aue(e){return new Um(e)}Er.createMakerSdk=Aue;function zo(e){return e instanceof Error?e:new Error(String(e))}function ZU(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function eB(e){return Object.values(e??{}).every(Cr.isVersionToken)}function Sue(e,t){return ZU(e,t)&&eB(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function KU(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Mw(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function Nue(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JU(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function YU(e){e.length===0||!e.every(t=>oo(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function _ue(e,t){if(t===void 0||t==="end")return e.length;if(t==="start")return 0;if("index"in t)return Math.max(0,Math.min(t.index,e.length));if("before"in t){let n=e.findIndex(i=>oo(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>oo(n)&&n.id===t.after);return r<0?e.length:r+1}});var rB=v(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.ARTIFACT_TYPES=void 0;Bm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var iB=v(nB=>{"use strict";Object.defineProperty(nB,"__esModule",{value:!0})});var aB=v(oB=>{"use strict";Object.defineProperty(oB,"__esModule",{value:!0})});var lB=v(sB=>{"use strict";Object.defineProperty(sB,"__esModule",{value:!0})});var cB=v(uB=>{"use strict";Object.defineProperty(uB,"__esModule",{value:!0})});var fB=v(dB=>{"use strict";Object.defineProperty(dB,"__esModule",{value:!0})});var mB=v(pB=>{"use strict";Object.defineProperty(pB,"__esModule",{value:!0})});var gB=v(hB=>{"use strict";Object.defineProperty(hB,"__esModule",{value:!0})});var bB=v(yB=>{"use strict";Object.defineProperty(yB,"__esModule",{value:!0})});var wB=v(vB=>{"use strict";Object.defineProperty(vB,"__esModule",{value:!0})});var EB=v(CB=>{"use strict";Object.defineProperty(CB,"__esModule",{value:!0})});var SB=v(AB=>{"use strict";Object.defineProperty(AB,"__esModule",{value:!0})});var _B=v(NB=>{"use strict";Object.defineProperty(NB,"__esModule",{value:!0})});var DB=v(TB=>{"use strict";Object.defineProperty(TB,"__esModule",{value:!0})});var OB=v(IB=>{"use strict";Object.defineProperty(IB,"__esModule",{value:!0})});var RB=v(PB=>{"use strict";Object.defineProperty(PB,"__esModule",{value:!0})});var kB=v(LB=>{"use strict";Object.defineProperty(LB,"__esModule",{value:!0})});var xB=v($B=>{"use strict";Object.defineProperty($B,"__esModule",{value:!0})});var MB=v(FB=>{"use strict";Object.defineProperty(FB,"__esModule",{value:!0})});var BB=v(UB=>{"use strict";Object.defineProperty(UB,"__esModule",{value:!0})});var VB=v(qB=>{"use strict";Object.defineProperty(qB,"__esModule",{value:!0})});var WB=v(GB=>{"use strict";Object.defineProperty(GB,"__esModule",{value:!0})});var jB=v(zB=>{"use strict";Object.defineProperty(zB,"__esModule",{value:!0})});var KB=v(ce=>{"use strict";var Tue=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ue=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Tue(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Due=tB();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Due.createMakerSdk}});Ue(rB(),ce);Ue(iB(),ce);Ue(aB(),ce);Ue(lB(),ce);Ue(cB(),ce);Ue(fB(),ce);Ue(mB(),ce);Ue(gB(),ce);Ue(bB(),ce);Ue(wB(),ce);Ue(EB(),ce);Ue(SB(),ce);Ue(_B(),ce);Ue(DB(),ce);Ue(OB(),ce);Ue(nf(),ce);Ue(RB(),ce);Ue(kB(),ce);Ue(xB(),ce);Ue(MB(),ce);Ue(BB(),ce);Ue(VB(),ce);Ue(WB(),ce);Ue(jB(),ce);Ue(Q(),ce);var HB=Wl();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return HB.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return HB.projectConnectorOperationSchema}})});var Bw=v(Si=>{"use strict";var Iue=Si&&Si.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Oue=Si&&Si.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),QB=Si&&Si.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Iue(t,e,r);return Oue(t,e),t};Object.defineProperty(Si,"__esModule",{value:!0});Si.NodeFileSystemStorage=void 0;var Nt=QB(require("fs")),sr=QB(require("path")),JB=Q(),YB=mh();async function XB(e){let t;try{t=await Nt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Nt.promises.unlink(e)}catch{await Nt.promises.rmdir(e)}return}if(!t.isDirectory()){await Nt.promises.unlink(e);return}for(let r of await Nt.promises.readdir(e))await XB(sr.join(e,r));await Nt.promises.rmdir(e)}var Uw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(sr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Nt.existsSync(r);){n.unshift(sr.basename(r));let i=sr.dirname(r);if(i===r)return sr.resolve(t);r=i}return sr.resolve(Nt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=sr.resolve(this.root),i=sr.resolve(t);if(i!==n&&!i.startsWith(n+sr.sep))throw new JB.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):sr.resolve(this.realPathThroughNearestAncestor(sr.dirname(i)),sr.basename(i));if(a!==o&&!a.startsWith(o+sr.sep))throw new JB.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Nt.existsSync(r))return null;try{return await(0,YB.retryTransientIoAsync)(()=>Nt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=sr.dirname(n);await Nt.promises.mkdir(i,{recursive:!0});let o=sr.join(i,`.${sr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Nt.promises.writeFile(o,r,"utf8"),await(0,YB.retryTransientIoAsync)(()=>Nt.promises.rename(o,n))}catch(a){try{Nt.existsSync(o)&&await Nt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Nt.existsSync(r)&&await Nt.promises.unlink(r)}async deleteByPrefix(t){await XB(this.pathFor(t,!1))}async ensureContainer(t){await Nt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Nt.existsSync(this.pathFor(t))}};Si.NodeFileSystemStorage=Uw});var ZB=v(Wr=>{"use strict";var Pue=Wr&&Wr.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Rue=Wr&&Wr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Lue=Wr&&Wr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Pue(t,e,r);return Rue(t,e),t};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.loadNodeTypeScript=Wr.createNodeWorkspaceStorage=Wr.NodeFileSystemStorage=void 0;var kue=Bw(),$ue=Bw();Object.defineProperty(Wr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return $ue.NodeFileSystemStorage}});function xue(e){return new kue.NodeFileSystemStorage(e)}Wr.createNodeWorkspaceStorage=xue;async function Fue(){return await Promise.resolve().then(()=>Lue(require("typescript")))}Wr.loadNodeTypeScript=Fue});var ao={};module.exports=zr(ao);so(ao,Ce(KB()),module.exports);so(ao,Ce(ZB()),module.exports);+`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,he.resendWhile)(m=>uW(m,s),()=>e.postBatch(o,r),he.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=a_(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,e_.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new Se.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function $d(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,he.readEtag)(r)}catch{return null}}async function JN(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,he.ensureSuccess)(n,e.apiUrl(r)),(0,he.readEtag)(n)}function YN(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Ig(e,t,r,n){if(!n)return null;let i=await $d(e,t);if(!i)return null;try{let o=await e.get(Fd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=nu(o);return!a||!Md(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function l_(e){return e>=400&&e<500&&e!==408&&e!==429}function QN(e,t,r){if(!e)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${r} read returned no ETag, so the delete cannot be made conditional on the row that was actually inspected. Without that condition a row renamed or re-pointed between the read and the delete would be destroyed. Retry.`);return e}async function u_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:QN(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await cW(e,n,i);return}if(!e.supportsAtomicBatch)throw new Se.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await lW(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:QN(r.sitemapEtag,t,"sitemap")}])}async function cW(e,t,r){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function XN(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,V8.collectGenPageIds)(t))]}catch(i){throw new Se.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Oi(i)}).`)}if(r.length===0)return;let n=await(0,G8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Se.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function dW(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 fW(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 ZN(e,t,r){var n;let i=(0,Ne.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await JN(e,i):null,s=Rg(Pg,i),l=(0,he.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=nu(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new Se.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await t_(e,u.uniquename),d=c?(0,Ne.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await $d(e,d));let p=Fd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,he.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=nu(h),b=w=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Md(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await $d(e,d))}o||(a=await JN(e,i));let m=a??H8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ne.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Qn.appApi={get(e,t){return ZN(e,t,"tokens-first")},readContentThenToken(e,t){return ZN(e,t,"content-first")},async list(e,t){let r=Rg(Pg);return(await(0,ms.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new Se.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 XN(e,n.sitemapxml);let i=await jN(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await J8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new Se.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${n.appModuleName}': its icon (\`appmodule.webresourceid\`) is a REQUIRED attribute and this environment has no image web resource to use. Pass \`iconWebResourceId\` explicitly, or add an image (PNG/JPG/GIF/ICO/SVG) web resource to the environment.`);let s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.id}). That creates a cross-solution dependency which can fail to import into an environment without the owning managed solution. Pass \`iconWebResourceId\` with an in-solution image to avoid it.`);let l=n.appModuleUniqueName||K8(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,he.ensureSuccess)(await(0,he.resendDeadlockVictim)(()=>e.post(c,(0,he.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,he.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ne.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Og.newId)(),w=!1,E=YN(n);try{let P="/sitemaps",L=(0,he.echoWrite)("sitemapid"),I=await e.post(`${P}${L.query}`,{sitemapid:b,sitemapnameunique:l,...E},L.options);w=l_(I.status);let D=(0,he.ensureSuccess)(I,e.apiUrl(P));p=(0,he.readEtag)(D),m=p??await Ig(e,b,E,l);let O=await WN(e,n,i);h.push(...O.warnings);let x=O.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await HN(e,f,x);let K=kd(e,f);await KN(e,f,O.tables,K),i&&await tW(e,f,i,K);let Re=await Y8(e,f);Re&&h.push(Re),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,W8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,BN.publishAppModule)(e,f),g={kind:"submitted"})}catch(P){let L=await nW(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,z8.failedAfterPrimaryWrite)(iW(P,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let P=await e.get(`/appmodules(${f})?$select=appmoduleid`);P.status>=200&&P.status<300&&(S=(0,he.readEtag)(P))}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,Ne.normalizeGuid)(t,"id");if(await XN(e,u.sitemapxml),!u.sitemapId)throw new Se.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,Ne.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,he.isVersionToken)(n))throw new Se.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 jN(e,u,c),m=await WN(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let ge=Rg(Pg,c),je=await e.get(ge);if(je.status>=200&&je.status<300){let de=nu(je);if(typeof de=="object"&&de!==null&&!Array.isArray(de)){g=de;let He=g.uniquename;b=typeof He=="string"&&He?He:void 0}}}catch{}let w=fW(u,g),E=h;if(Object.keys(w).length>0){if(!(0,he.isVersionToken)(h))throw new Se.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 ge=(0,he.echoWrite)("appmoduleid",{"If-Match":h}),je=await e.patch(`${p}${ge.query}`,w,ge.options);if(dW(je))throw new Se.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,he.ensureSuccess)(je,e.apiUrl(p)),E=(0,he.readEtag)(je)}let S=YN(u),P=b||u.appModuleUniqueName||void 0,L=(0,he.echoWrite)("sitemapid",{"If-Match":n}),I=`/sitemaps(${d})`,D;try{D=(0,he.ensureSuccess)(await e.patch(`${I}${L.query}`,{...S},L.options),e.apiUrl(I))}catch(ge){throw(0,Se.withPartialTokens)(ge,{siblingEtags:{[c]:E}})}let O=[...m.warnings],x=kd(e,c);try{await HN(e,c,m.components),await KN(e,c,m.tables,x)}catch(ge){O.push(`App '${c}': one or more components were not pinned (${ge.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&O.push(...await rW(e,c,f,x));let K={kind:"notRequested"},Re=E,qt=(s=(0,he.readEtag)(D))!==null&&s!==void 0?s:await Ig(e,d,S,P);if(u.published===!0){try{await(0,BN.publishAppModule)(e,c),K={kind:"submitted"}}catch(ge){K={kind:"failed",error:ge},O.push(`App '${c}': saved, but publishing failed (${ge.message}). The app remains unpublished; re-push to retry.`)}if(K.kind==="submitted"){Re=null;try{let ge=await e.get(`/appmodules(${c})?$select=appmoduleid`);ge.status>=200&&ge.status<300&&(Re=(0,he.readEtag)(ge)),qt=(l=await Ig(e,d,S,P))!==null&&l!==void 0?l:qt}catch{}}}return{id:c,etag:qt,siblingEtags:{[c]:Re},publish:K,...O.length>0?{warnings:O}:{}}},async delete(e,t){let r=(0,Ne.normalizeGuid)(t,"id");await u_(e,r,await o_(e,r))}}});var $g=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.deleteAppCascade=hs.collectGenPageIds=void 0;var pW=Ud(),mW=Q(),xg=se(),hW=es();function c_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new hW.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 mW.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,xg.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}hs.collectGenPageIds=c_;async function gW(e,t,r){let n=(0,xg.normalizeGuid)(t,"appModuleId");(0,xg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,pW.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...c_(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}hs.deleteAppCascade=gW});var d_={};Hr(d_,{Guid:()=>U});var U,pt=k(()=>{"use strict";U=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var q,Yt=k(()=>{"use strict";ot();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 f_={};Hr(f_,{ScriptUtilities:()=>R});var R,ot=k(()=>{"use strict";pt();Yt();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 Bd,qd,ea,Vd,Fg,Gd,Mg=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Bd||(Bd={}));qd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ea=class extends qd{key;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Vd=class extends qd{property;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Fg=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()})}},Gd=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 Fg(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 p_={};Hr(p_,{ChartGridMode:()=>an,ColumnLayoutWidths:()=>CW,ComponentCategory:()=>zd,ComponentType:()=>Ug,ControlLayoutTypes:()=>jg,DisplayConditionsInfo:()=>vW,ElementNames:()=>C,ElementProperties:()=>y,ElementType:()=>qg,EntityAttributeProperty:()=>Vg,EventType:()=>iu,FormActivationState:()=>zg,FormCanvasServiceScope:()=>LW,FormDesignerSideBarTab:()=>Bg,FormPresentation:()=>Gg,FormState:()=>Wd,FormType:()=>mt,HeaderDensityType:()=>mo,LookUpTable:()=>Xn,MORE_TAB_PREFIX:()=>AW,NavBarChildElementType:()=>Wg,PREVIEW_ID_HEADER_FLYOUT:()=>TW,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>IW,PREVIEW_ID_NAVIGATION_AREA:()=>NW,PREVIEW_ID_QUICKCREATE_ROOT:()=>PW,PREVIEW_ID_TAB:()=>OW,PREVIEW_ID_TAB_LIST:()=>DW,PREVIEW_ID_TAB_PANEL:()=>_W,PropertyModelKeys:()=>Jg,PropertyModelSectionKeys:()=>EW,RELATED_TAB_ID:()=>Yg,RELATED_TAB_PREFIX:()=>SW,SectionDefaultProperties:()=>wW,SectionLayoutTypes:()=>ze,TabContentType:()=>Hg,TabDefaultProperties:()=>ho,TabLayoutTypes:()=>We,TelemetryPropertyNames:()=>RW,UnboundControlPropertyKeys:()=>Kg,compositeAddressFields:()=>bW,compositeFieldNames:()=>Gr,compositeFields:()=>yW});var mt,Ug,Bg,C,y,qg,Gr,yW,bW,Vg,Xn,Wd,mo,Gg,vW,Wg,zg,We,wW,ho,ze,jg,Hg,CW,Kg,Jg,EW,iu,an,Yg,AW,SW,NW,_W,TW,DW,IW,OW,PW,RW,zd,LW,le=k(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(mt||(mt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Ug||(Ug={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Bg||(Bg={}));(function(e){e.form="form",e.formTab="tab",e.formColumn="column",e.formSection="section",e.formRow="row",e.formCell="cell",e.formLabel="label",e.formControl="control",e.formEvent="event",e.dependency="dependency",e.queryStringParameter="querystringparameter",e.controlDescriptions="controlDescriptions",e.controlDescription="controlDescription",e.customControl="customControl",e.dataset="data-set",e.formFooter="footer",e.formHeader="header",e.formNavigation="Navigation",e.formTabs="tabs",e.formColumns="columns",e.formSections="sections",e.formRows="rows",e.formEvents="events",e.quickFormDependencies="externaldependencies",e.controlParameters="parameters",e.formDependencies="dependencies",e.formNavBarAreas="NavBarAreas",e.formNavBarArea="NavBarArea",e.formNavBar="NavBar",e.spacerControl="SpacerControl",e.formField="Field",e.formNavBarByRelationshipItem="NavBarByRelationshipItem",e.formNavBarItem="NavBarItem",e.Title="Title",e.Titles="Titles",e.NavigationLink="Navigation Link",e.Relationship="Relationship",e.NavigationLinkIconClass="mscrm-glyph-NavLinkIcon",e.formDisplayConditions="DisplayConditions",e.formLibraries="formLibraries",e.internalLibraries="internaljscriptfile",e.eventHandlers="Handlers",e.handler="Handler",e.library="Library",e.formRoles="Role",e.formEveryOne="Everyone",e.Handler="Handler",e.EventHandlers="Handlers",e.InternalEventHandlers="InternalHandlers",e.HiddenControl="hiddencontrols",e.EventDependencies="dependencies",e.EventDependency="dependency",e.isvisibleinmocaonly="msinternal.isvisibleinmocaonly"})(C||(C={}));y={ShowImage:"showImage",ShowNavigationbar:"shownavigationbar",MaxWidth:"maxWidth",HeaderDensityType:"headerdensity",OnLoadEvent:"onload",EventActive:"active",EventAttribute:"attribute",Relationship:"relationship",Control:"control",HandlerUniqueId:"handlerUniqueId",functionName:"functionName",libraryNameEventHandler:"libraryName",enabledForField:"enabled",passExecutionContext:"passExecutionContext",parameters:"parameters",eventFunctionName:"eventFunctionName",eventEnabled:"eventEnabled",indicationOfSubgrid:"indicationOfSubgrid",Name:"name",Type:"type",TitleResourceId:"TitleResourceId",Show:"Show",RelationshipName:"RelationshipName",Sequence:"Sequence",Area:"Area",headerPrefix:"header_",application:"application",labelId:"labelid",showbar:"showbar",layout:"layout",classid:"classid",uniqueid:"uniqueid",isUnbound:"isunbound",isRequired:"isrequired",rowspan:"rowspan",rowheight:"rowheight",colspan:"colspan",width:"width",IsUserDefined:"IsUserDefined",expanded:"expanded",related:"related",showlabel:"showlabel",locklevel:"locklevel",datafieldname:"datafieldname",formFactor:"formFactor",static:"static",disabled:"disabled",description:"description",languagecode:"languagecode",LCID:"LCID",groupName:"group",contentType:"contenttype",showCommandBar:"showcommandbar",showBody:"showbody",showTabNavigator:"showtabnavigator",userspacer:"userspacer",columnName:"columns",LabelWidth:"labelwidth",Fieldlabelalignment:"celllabelalignment",Fieldlabelposition:"celllabelposition",availableforphone:"availableforphone",Locked:"bLocked",ReadOnly:"bDisabled",visible:"visible",ForControl:"forControl",text:"Text",url:"Url",passParameters:"PassParameters",autoExpand:"AutoExpand",auto:"auto",Auto:"Auto",Fixed:"Fixed",icon:"Icon",id:"id",Id:"Id",showOnMobileClient:"ShowOnMobileClient",webResourceId:"WebResourceId",viewName:"ViewName",failureTimeField:"FailureTimeField",successCondition:"SuccessConditionName",successConditionValue:"SuccessConditionValue",failureCondition:"FailureConditionName",failureConditionValue:"FailureConditionValue",warningCondition:"WarningConditionName",warningConditionValue:"WarningConditionValue",cancelCondition:"CancelConditionName",cancelConditionValue:"CancelConditionValue",pauseCondition:"PauseConditionName",pauseConditionValue:"PauseConditionValue",filterResults:"FilterResults",autoSuggestionSource:"AutoSuggestionSource",numberOfResults:"NumberOfResults",addressField:"AddressField",displayAsCustomer360Tile:"DisplayAsCustomer360Tile",hideQuickFormBorder:"HideQuickFormBorder",quickForms:"QuickForms",entityName:"EntityName",controlMode:"ControlMode",headerColorCode:"HeaderColorCode",targetEntityType:"TargetEntityType",enableQuickFind:"EnableQuickFind",enableViewPicker:"EnableViewPicker",enableChartPicker:"EnableChartPicker",recordsPerPage:"RecordsPerPage",chartGridMode:"ChartGridMode",referencePanelSubgridIconUrl:"ReferencePanelSubgridIconUrl",referencePanelQuickFormCollectionIconUrl:"ReferencePanelQuickFormCollectionIconUrl",referencePanelSearchWidgetIconUrl:"ReferencePanelSearchWidgetIconUrl",viewId:"ViewId",isUserView:"IsUserView",enableJumpBar:"EnableJumpBar",isUserChart:"IsUserChart",viewIds:"ViewIds",filteredViewIds:"FilteredViewIds",visualizationId:"VisualizationId",teamTemplateId:"TeamTemplateId",selectDefaultLanguage:"SelectDefaultLanguage",allowChangingFiltersOnUI:"AllowChangingFiltersOnUI",enableAutoSuggestions:"EnableAutoSuggestions",enableRating:"EnableRating",searchForAutoSuggestionsUsing:"SearchForAutoSuggestionsUsing",showContextualActions:"ShowContextualActions",showDepartmentFilter:"ShowDepartmentFilter",showLanguageFilter:"ShowLanguageFilter",showRatingUsing:"ShowRatingUsing",actionList:"ActionList",Order:"Order",FallbackForm:"FallbackForm",allowSearchFilter:"allowSearchFilter",socialInstanceParameters:"<Parameters>k__BackingField",signalUrl:"SignalUrl",border:"Border",scrolling:"Scrolling",security:"Security",BingMapsAddress1Composite:"address1_composite",BingMapsAddress2Composite:"address2_composite",UrlHttpsProtocolPrefix:"https://",UrlHttpProtocolPrefix:"http://",showAll:"ShowAll",ShowFilterPane:"UClientShowFilterPane",ExpandFilterPane:"UClientExpandFilterPane",SortOption:"UClientOrderBy",DefaultModuleCreateExperience:"UClientDefaultModuleForCreateExperience",RecordPerPages:"UClientRecordPerPage",moduleList:"UClientModules",showAllModule:"Show All",showSelectedModule:"Show Selected",Ascending:"Ascending",Descending:"Descending",Activities:"Activities",Posts:"Posts",Notes:"Notes",CardForm:"CardForm",SelectActivity:"SelectActivity",DisplayActivity:"UClientDisplayActivityUsing",CreateActivity:"UClientCreateActivityUsing",DisplayActivityHeader:"UClientDisplayActivityHeaderUsing",SortTimeLine:"UClientSortActivitiesByValue",activityList:"UClientActivities",CardActivityMap:"UClientActivityCardMap",DefaultTabId:"DefaultTabId",EmailConversationView:"EmailConversationView",OrderByActivityWall:"OrderByActivityWall",ShowArticleTab:"ShowArticleTab",SortActivityWall:"SortActivityWall",TimelineUniqueName:"UClientUniqueName",SortTimeLineBy:"modifiedon",SelectActivityListDefault:"appointment",SelectCardDefault:"Select Card Form",AscendingValue:"ascending",DescendingValue:"descending",DefaultTabIdValue:"ActivitiesTab",EmailConversationViewDefault:"true",ShowArticleTabDefault:"false",SelectDefaultLanguage:"SelectDefaultLanguage",SelectDefaultLanguageValue:"00000000-0000-0000-0000-000000000000",SortActivityWallDefault:"modifiedon",RecordPerPagesDefault:"10",TimelineNameLabel:"Timeline",showSelectedActions:"Show Selected",defaultFormat:"defaultformat",fieldLabels:"fieldlabels",QuickCreateForm:"quickcreateform",QuickFormNameToIdXMLTempate:"<QuickFormId e,yname={0}>{1}</QuickFormId>",QuickFormIdListXMLTempate:"<QuickFormId,}</QuickFormIds>",AllowFilterOff:"AllowFilterOff",AutoResolve:"AutoResolve",DefaultViewId:"DefaultViewId",DependentAttributeName:"DependentAttributeName",DependentAttributeType:"DependentAttributeType",DisableMru:"DisableMru",UseMFDForCreate:"useMainFormDialogForCreate",UseMFDForEdit:"useMainFormDialogForEdit",DisableQuickFind:"DisableQuickFind",DisableViewPicker:"DisableViewPicker",FilterRelationshipName:"FilterRelationshipName",AvailableViewIds:"AvailableViewIds",MainForm:"mainform",DefaultsFields:"defaultfields",TimeLineCardForm:"cardform",libraryUniqueId:"libraryUniqueId",libraryName:"name",displayName:"displayName",OnChangeEvent:"onchange",ViewIdRAControlDefault:"{92AFD454-0F2E-4397-A1C8-05E37C6AD699}",TargetEntityTypeRAControlDefault:"actioncard",ChartGridModeRAControlDefault:"All",RecordsPerPageRAControlDefault:"4",RAControlDefaultValue:"false",RAcontrolDefaultHeaderColorCode:"#000000",DropdownSelectedDefaultValue:"1",selectPrimaryCustomer:"SelectPrimaryCustomer",bindAttribute:"BindAttribute"};(function(e){e[e.TAB=0]="TAB",e[e.SECTION=1]="SECTION",e[e.BASIC_CONTROL=2]="BASIC_CONTROL",e[e.HEADER=3]="HEADER",e[e.FOOTER=4]="FOOTER",e[e.UB_CONTROL=5]="UB_CONTROL",e[e.RELATIONSHIPITEM=6]="RELATIONSHIPITEM",e[e.RELATIONSHIPGROUP=7]="RELATIONSHIPGROUP",e[e.NAVIGATIONLINK=8]="NAVIGATIONLINK",e[e.FORMMODEL=9]="FORMMODEL",e[e.UNDEFINED=10]="UNDEFINED"})(qg||(qg={}));Gr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},yW=[Gr.fullname,Gr.yomifullname,Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto],bW=[Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Vg||(Vg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Xn||(Xn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Wd||(Wd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(mo||(mo={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Gg||(Gg={}));vW={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Wg||(Wg={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(zg||(zg={}));(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"})(We||(We={}));wW={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},ho={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"})(ze||(ze={}));(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"})(jg||(jg={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Hg||(Hg={}));CW={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"})(Kg||(Kg={}));(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"})(Jg||(Jg={}));EW={display:"DisplayOptions",format:"Formatting",control:"Controls",data:"DataOptions",form:"FormProperties",events:"EventProperties",activeBusinessRules:"activeBusinessRules",addBusinessRule:"addBusinessRule",inactiveBusinessRules:"inactiveBusinessRules"};(function(e){e.onChange="onchange",e.onTabStateChange="tabstatechange",e.onLoad="onload",e.onSave="onsave",e.onReadyStateComplete="onreadystatecomplete",e.onRecordSelect="onrecordselect"})(iu||(iu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(an||(an={}));Yg="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",AW="more_tab_",SW="related_tab_",NW="preview_id_navigation_area",_W="tab-section",TW="headerFieldsFlyout",DW="tablist",IW="header_overflowButton",OW="tab",PW="quickCreateRoot",RW={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"})(zd||(zd={}));LW="CellCanvasServiceScope"});var m_={};Hr(m_,{Attribute:()=>jd,FormElementNode:()=>re});var jd,re,Dt=k(()=>{"use strict";ot();Yt();Mg();le();pt();jd=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(C.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new jd(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 ea(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 ea(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 ea(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 Vd(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 ea(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 C.formCell:let t=this.getAncestor(C.formSection);return t||(t=this.getAncestor(C.formHeader),t)||(t=this.getAncestor(C.formFooter),t)?t:null;case C.formSection:return this.getAncestor(C.formTab);case C.formTab:return this.getAncestor(C.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(r=>r.changeSet.some(n=>n.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(C.form);return t?t.changeTracker():null}}});var h_={};Hr(h_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Hd,getControlDisplayNames:()=>kW});function kW(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,Hd,ta=k(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(N||(N={}));Hd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ra=v((Dle,y_)=>{var ou=new Proxy(function(){return ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ou},apply:function(){return ou},construct:function(){return{}}}),g_=function(){return ou};Object.setPrototypeOf(g_,ou);y_.exports=g_});var sr,Pi,b_,v_,gs=k(()=>{"use strict";sr="cds-designer-models",Pi="FormCustomControl",b_="FormCell",v_="Form"});var na,Qg=k(()=>{"use strict";Bl();le();na=class e{static lockedFieldCount=new nr;static dependencyFieldCount=new nr;static getNecessaryLookUpTable(t){switch(t){case Xn.DependencyFieldTable:return e.dependencyFieldCount;case Xn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Xn.DependencyFieldTable:e.dependencyFieldCount=new nr;case Xn.LockedFieldTable:e.lockedFieldCount=new nr}}}});var Kd,w_=k(()=>{"use strict";pt();ot();le();Dt();Kd=class extends re{constructor(t){super(C.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(C.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 Ri(){return Zn||(Zn=window._makerConfig,Zn&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Zn={...Zn,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Zn?.region==="prod"&&(Zn={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/"}}},...Zn}),Zn||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Zn,Jd=k(()=>{"use strict";});function C_(e,t,r){if(!e)return Yd.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Yd.add("")),!1;if(e){if(e=e.toLowerCase(),Yd.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}}),Yd.add(e),!1}return!0}function $W(e){return C_(e,Xg,"Location dictionary")?Xg[e.toLowerCase()]:"us"}function xW(){let e=Ri().location.toLowerCase();return C_(e,Xg,"Current location dictionary")?e:"us"}var Yd,Xg,qle,E_=k(()=>{"use strict";Jd();Yd=new Set,Xg={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"};qle=$W(xW())});var Y,Gle,A_=k(()=>{"use strict";Y={USWest:"westus",USWest2:"westus2",USCentral:"centralus",USEast:"eastus",USEast2:"eastus2",USNorthCentral:"northcentralus",USSouthCentral:"southcentralus",USWestCentral:"westcentralus",CanadaCentral:"canadacentral",CanadaEast:"canadaeast",BrazilSouth:"brazilsouth",EuropeNorth:"northeurope",EuropeWest:"westeurope",UKSouth:"uksouth",UKWest:"ukwest",FranceCentral:"francecentral",FranceSouth:"francesouth",SwitzerlandNorth:"switzerlandnorth",SwitzerlandWest:"switzerlandwest",GermanyNorth:"germanynorth",GermanyWestCentral:"germanywestcentral",NorwayWest:"norwaywest",NorwayEast:"norwayeast",SwedenCentral:"swedencentral",ItalyNorth:"italynorth",PolandCentral:"polandcentral",AsiaEast:"eastasia",AsiaSouthEast:"southeastasia",JapanEast:"japaneast",JapanWest:"japanwest",AustraliaEast:"australiaeast",AustraliaSouthEast:"australiasoutheast",AustraliaCentral:"australiacentral",AustraliaCentral2:"australiacentral2",IndiaCentral:"centralindia",IndiaSouth:"southindia",IndiaWest:"westindia",KoreaSouth:"koreasouth",KoreaCentral:"koreacentral",NewZealandNorth:"newzealandnorth",UAECentral:"uaecentral",UAENorth:"uaenorth",SouthAfricaNorth:"southafricanorth",SouthAfricaWest:"southafricawest",QatarCentral:"qatarcentral",GermanyCentral:"germanycentral",GermanyNorthEast:"germanynortheast",SingaporeSouthEast:"southeastasia",GovernmentUSVirginia:"usgovvirginia",GovernmentUSIowa:"usgoviowa",GovernmentUSArizona:"usgovarizona",GovernmentUSTexas:"usgovtexas",GovernmentUSDodEast:"usdodeast",GovernmentUSDodCentral:"usdodcentral",ChinaNorth:"chinanorth",ChinaNorth2:"chinanorth2",ChinaNorth3:"chinanorth3",ChinaEast:"chinaeast",ChinaEast2:"chinaeast2",ChinaEast3:"chinaeast3",UssecEast:"usseceast",UssecWest:"ussecwest",UsnatEast:"usnateast",UsnatWest:"usnatwest"},Gle={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var S_=k(()=>{"use strict";Jd();});var au=k(()=>{"use strict";Jd();E_();A_();S_();});function su(e,t){return N_?N_.isOverridden(e,t):{overridden:!1}}var N_,lu=k(()=>{"use strict";});var Zg=k(()=>{"use strict";au();lu();});function FW(e,t){let{region:r}=Ri();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=su(e.packageName,t);if(s.overridden)return typeof s.value=="string"?MW(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 MW(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function UW(e){let t=e.packageName;if(Qd.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=>t0(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=>!Zd(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function uu(e){UW(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:FW(e,r)}}),Qd.set(e.packageName,e),Object.defineProperties({},t)}function e0(e,t){return Qd.has(e)?!!Qd.get(e).settings[t]:!1}var Qd,Xd=k(()=>{"use strict";au();lu();r0();cu();Qd=new Map});function __(e,t){let{region:r}=Ri();return()=>{let n=su(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function BW(e){let t=e.packageName;if(ef.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=>e0(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=>!Zd(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function n0(e){BW(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:__(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:__(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},ef.set(e.packageName,e),Object.defineProperties(r,t)}function t0(e,t){return ef.has(e)?!!ef.get(e).features[t]:!1}var ef,r0=k(()=>{"use strict";au();cu();lu();Xd();ef=new Map});var D_=v((mue,T_)=>{"use strict";T_.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 P_=v(i0=>{"use strict";var qW=Object.prototype.hasOwnProperty,VW;function I_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function O_(e){try{return encodeURIComponent(e)}catch{return null}}function GW(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=I_(n[1]),o=I_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function WW(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(qW.call(e,i)){if(n=e[i],!n&&(n===null||n===VW||isNaN(n))&&(n=""),i=O_(i),n=O_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}i0.stringify=WW;i0.parse=GW});var s0=v((gue,F_)=>{"use strict";var L_=D_(),tf=P_(),k_=/[\n\r\t]/g,zW=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,jW=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,HW=/^[a-zA-Z]:/,KW=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function a0(e){return(e||"").toString().replace(KW,"")}var o0=[["#","hash"],["?","query"],function(t,r){return ei(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]],R_={hash:1,query:1};function $_(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 ti(unescape(e.pathname),{});else if(i==="string"){n=new ti(e,{});for(o in R_)delete n[o]}else if(i==="object"){for(o in e)o in R_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=zW.test(e.href))}return n}function ei(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function x_(e,t){e=a0(e),e=e.replace(k_,""),t=t||{};var r=jW.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)):ei(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ei(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ei(n),slashesCount:a,rest:s}}function JW(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 ti(e,t,r){if(e=a0(e),e=e.replace(k_,""),!(this instanceof ti))return new ti(e,t,r);var n,i,o,a,s,l,u=o0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=tf.parse),t=$_(t),i=x_(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||HW.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ei(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=JW(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ei(d.protocol)&&(d.pathname="/"+d.pathname),L_(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:"&&ei(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function YW(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||tf.parse)(t)),n[e]=t;break;case"port":n[e]=t,L_(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<o0.length;a++){var s=o0[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:"&&ei(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function QW(e){(!e||typeof e!="function")&&(e=tf.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||ei(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ei(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}ti.prototype={set:YW,toString:QW};ti.extractProtocol=x_;ti.location=$_;ti.trimLeft=a0;ti.qs=tf;F_.exports=ti});var XW,M_=k(()=>{"use strict";XW=Ee(s0());});function l0(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 rf=k(()=>{"use strict";});var u0,c0,d0=k(()=>{"use strict";rf();u0=class{features=new Map;register(t,r){let n=l0(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()}},c0=new u0});var f0=k(()=>{"use strict";});function Zd(e){return ZW.has(e)}var ZW,cu=k(()=>{"use strict";Zg();r0();Xd();lu();Zg();M_();d0();rf();f0();ZW=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var e6,U_=k(()=>{"use strict";cu();e6=uu({packageName:"cds-designer-models",settings:{testCustomControls:{description:"Test Custom Controls to show up in the component picker.",allowOverrides:!0,values:{default:"",test:"",preprod:"",preview:"",gov:""}}}})});var G_,m0,ys,ia,p0,nf,bs,Li,Ue,B_,q_,V_,_n=k(()=>{"use strict";G_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},m0={ONE_COLUMN:"1",TWO_COLUMN:"2",THREE_COLUMN:"3",FOUR_COLUMN:"4"};(function(e){e[e.SUBGRID=0]="SUBGRID",e[e.SPACER=1]="SPACER",e[e.QUICK_VIEW=2]="QUICK_VIEW",e[e.WEB_RESOURCE=3]="WEB_RESOURCE",e[e.IFRAME=4]="IFRAME",e[e.BING_MAPS=5]="BING_MAPS",e[e.TIMER=6]="TIMER",e[e.TIMELINE=7]="TIMELINE",e[e.SOCIAL_INSIGHTS=8]="SOCIAL_INSIGHTS",e[e.KB_SEARCH=9]="KB_SEARCH",e[e.ACI_CONTROL=10]="ACI_CONTROL",e[e.RELATIONSHIP_ASSISTANT=11]="RELATIONSHIP_ASSISTANT",e[e.REFERENCE_PANEL=12]="REFERENCE_PANEL",e[e.REF_PANEL_QUICKVIEW=13]="REF_PANEL_QUICKVIEW",e[e.REF_PANEL_SUBGRID=14]="REF_PANEL_SUBGRID",e[e.REF_PANEL_KBSEARCH=15]="REF_PANEL_KBSEARCH",e[e.WEB_RESOURCE_HTML=16]="WEB_RESOURCE_HTML",e[e.PRED_LEAD_SCORING=17]="PRED_LEAD_SCORING"})(ys||(ys={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(ia||(ia={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(p0||(p0={}));nf=class{static ONE_COLUMN=1;static TWO_COLUMN=2;static THREE_COLUMN=3;static FIVE_COLUMN=5};(function(e){e.Left="Left",e.Top="Top"})(bs||(bs={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:ia.Left,labelPosition:bs.Left,MarginalControlColumns:"111",referencePanelNamePrefix:"ref_pan_"};(function(e){e.AddFormBodyFieldToReadOnlyHeader="AddFormBodyFieldToReadOnlyHeader",e.AddFieldPaneFieldToReadOnlyHeader="AddFieldPaneFieldToReadOnlyHeader",e.AddFieldExceedsReadOnlyHeaderLimit="AddFieldExceedsReadOnlyHeaderLimit",e.AddCustomComponentToReadOnlyHeader="AddCustomComponentToReadOnlyHeader",e.AddNonDisplayableComponentToReadOnlyHeader="AddNonDisplayableComponentToReadOnlyHeader",e.AddFieldToFlyoutOnly="AddFieldToFlyoutOnly",e.DisplayedFieldToFlyout="DisplayedFieldToFlyout",e.FlyoutFieldToDisplayed="FlyoutFieldToDisplayed",e.AddControlBeforeDefaultLabel="AddControlBeforeDefaultLabel"})(B_||(B_={}));(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"})(V_||(V_={}))});var h0,W_=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(h0||(h0={}))});var H_,t6,z_,dce,fce,du,j_,pce,mce,K_=k(()=>{"use strict";H_=Ee(ra());ot();gs();U_();rs();_n();zo();le();t6=Ee(Yi());W_();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(z_||(z_={}));dce={Read:no.Read,Edit:no.Edit,Both:no.Both,Container:no.Container},fce={input:Wo.Input,bound:Wo.Bound,output:Wo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(du||(du={}));(function(e){e[e.None=0]="None",e[e.HiddenControl=1]="HiddenControl",e[e.CompatibleDataTypesIsMissing=2]="CompatibleDataTypesIsMissing",e[e.TagNameIsUnsupported=3]="TagNameIsUnsupported",e[e.PropertyTypeIsUnsupported=4]="PropertyTypeIsUnsupported",e[e.PropertyTypeGroupIsUnsupported=5]="PropertyTypeGroupIsUnsupported"})(j_||(j_={}));pce=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]),mce={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 Tn,of,J_=k(()=>{"use strict";Tn=Ee(ra());pt();ot();Yt();gs();zo();K_();rs();le();Dt();_n();of=class extends re{constructor(t){super(C.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(jt.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===jt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===jt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(jt.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:Lh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===du.dataset?o.get(jt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===du.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Tn.trackInfoTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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===jt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===_i.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(Rh.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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Tn.trackWarningTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return od.includes(t)}isNumberTypeProperty(t,r){return ad.includes(r)||t.ofTypeGroup.some(n=>ad.includes(n))}isDataSet(t){return jt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,g0=k(()=>{"use strict";ee=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var Y_={};Hr(Y_,{CustomControlUniqueId:()=>oa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>at,mapFieldTypeToControl:()=>r6});function r6(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,oa,at,fu=k(()=>{"use strict";pt();Bl();ot();Yt();rs();ta();g0();_n();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"}};oa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},at=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new nr;static initializeFieldControls(){let t=new nr,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 E=e.getControlName($.Currency,W.None);t.add(E,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let P=e.getControlName($.MultipleLineofText,W.Text);t.add(P,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let O=e.getControlName($.TwoOptions,W.None);t.add(O,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 Re=e.getControlName($.TwoOptions,"Radio");t.add(Re,new U(G.RadioControl));let qt=e.getControlName($.TwoOptions,"CheckBox");t.add(qt,new U(G.CheckBoxControl));let ge=e.getControlName($.TwoOptions,"List");t.add(ge,new U(G.PicklistControl));let je=e.getControlName($.State,W.None);t.add(je,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let He=e.getControlName($.OwnerType,W.None);t.add(He,new U(G.LookupControl));let bn=e.getControlName($.PartyListType,W.None);t.add(bn,new U(G.PartyListControl));let CU=e.getControlName($.LookupType,W.Regarding);t.add(CU,new U(G.RegardingControl));let EU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(EU,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 nr;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(oa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new nr;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 ts;return t.add(ys.IFRAME,!0),t.add(ys.SPACER,!0),t.add(ys.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===oa.RelationshipAssistant||t.guidString===oa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===oa.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 af,Q_=k(()=>{"use strict";af=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 aa,vs,X_,Z_,go,eT,tT,y0=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(aa||(aa={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(vs||(vs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(X_||(X_={}));(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"})(Z_||(Z_={}));(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"})(go||(go={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(eT||(eT={}));(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"})(tT||(tT={}))});var ws,rT=k(()=>{"use strict";cu();ws=n0({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 nT(e){return{...e,extractConfig:t=>n6(t,Object.keys(e.fallback))}}function n6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var b0=k(()=>{"use strict";});var v0=v((qce,oT)=>{var pu=new Proxy(function(){return pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:pu},apply:function(){return pu},construct:function(){return{}}}),iT=function(){return pu};Object.setPrototypeOf(iT,pu);oT.exports=iT});var lT=v((Vce,sT)=>{var mu=new Proxy(function(){return mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:mu},apply:function(){return mu},construct:function(){return{}}}),aT=function(){return mu};Object.setPrototypeOf(aT,mu);sT.exports=aT});var w0=v((Gce,cT)=>{var hu=new Proxy(function(){return hu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:hu},apply:function(){return hu},construct:function(){return{}}}),uT=function(){return hu};Object.setPrototypeOf(uT,hu);cT.exports=uT});var fT=v((Wce,dT)=>{function i6(){this.__data__=[],this.size=0}dT.exports=i6});var Cs=v((zce,pT)=>{function o6(e,t){return e===t||e!==e&&t!==t}pT.exports=o6});var gu=v((jce,mT)=>{var a6=Cs();function s6(e,t){for(var r=e.length;r--;)if(a6(e[r][0],t))return r;return-1}mT.exports=s6});var gT=v((Hce,hT)=>{var l6=gu(),u6=Array.prototype,c6=u6.splice;function d6(e){var t=this.__data__,r=l6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():c6.call(t,r,1),--this.size,!0}hT.exports=d6});var bT=v((Kce,yT)=>{var f6=gu();function p6(e){var t=this.__data__,r=f6(t,e);return r<0?void 0:t[r][1]}yT.exports=p6});var wT=v((Jce,vT)=>{var m6=gu();function h6(e){return m6(this.__data__,e)>-1}vT.exports=h6});var ET=v((Yce,CT)=>{var g6=gu();function y6(e,t){var r=this.__data__,n=g6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}CT.exports=y6});var yu=v((Qce,AT)=>{var b6=fT(),v6=gT(),w6=bT(),C6=wT(),E6=ET();function Es(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Es.prototype.clear=b6;Es.prototype.delete=v6;Es.prototype.get=w6;Es.prototype.has=C6;Es.prototype.set=E6;AT.exports=Es});var NT=v((Xce,ST)=>{var A6=yu();function S6(){this.__data__=new A6,this.size=0}ST.exports=S6});var TT=v((Zce,_T)=>{function N6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}_T.exports=N6});var IT=v((ede,DT)=>{function _6(e){return this.__data__.get(e)}DT.exports=_6});var PT=v((tde,OT)=>{function T6(e){return this.__data__.has(e)}OT.exports=T6});var C0=v((rde,RT)=>{var D6=typeof global=="object"&&global&&global.Object===Object&&global;RT.exports=D6});var Dn=v((nde,LT)=>{var I6=C0(),O6=typeof self=="object"&&self&&self.Object===Object&&self,P6=I6||O6||Function("return this")();LT.exports=P6});var bu=v((ide,kT)=>{var R6=Dn(),L6=R6.Symbol;kT.exports=L6});var MT=v((ode,FT)=>{var $T=bu(),xT=Object.prototype,k6=xT.hasOwnProperty,$6=xT.toString,vu=$T?$T.toStringTag:void 0;function x6(e){var t=k6.call(e,vu),r=e[vu];try{e[vu]=void 0;var n=!0}catch{}var i=$6.call(e);return n&&(t?e[vu]=r:delete e[vu]),i}FT.exports=x6});var BT=v((ade,UT)=>{var F6=Object.prototype,M6=F6.toString;function U6(e){return M6.call(e)}UT.exports=U6});var sa=v((sde,GT)=>{var qT=bu(),B6=MT(),q6=BT(),V6="[object Null]",G6="[object Undefined]",VT=qT?qT.toStringTag:void 0;function W6(e){return e==null?e===void 0?G6:V6:VT&&VT in Object(e)?B6(e):q6(e)}GT.exports=W6});var ki=v((lde,WT)=>{function z6(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}WT.exports=z6});var sf=v((ude,zT)=>{var j6=sa(),H6=ki(),K6="[object AsyncFunction]",J6="[object Function]",Y6="[object GeneratorFunction]",Q6="[object Proxy]";function X6(e){if(!H6(e))return!1;var t=j6(e);return t==J6||t==Y6||t==K6||t==Q6}zT.exports=X6});var HT=v((cde,jT)=>{var Z6=Dn(),ez=Z6["__core-js_shared__"];jT.exports=ez});var YT=v((dde,JT)=>{var E0=HT(),KT=(function(){var e=/[^.]+$/.exec(E0&&E0.keys&&E0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function tz(e){return!!KT&&KT in e}JT.exports=tz});var A0=v((fde,QT)=>{var rz=Function.prototype,nz=rz.toString;function iz(e){if(e!=null){try{return nz.call(e)}catch{}try{return e+""}catch{}}return""}QT.exports=iz});var ZT=v((pde,XT)=>{var oz=sf(),az=YT(),sz=ki(),lz=A0(),uz=/[\\^$.*+?()[\]{}|]/g,cz=/^\[object .+?Constructor\]$/,dz=Function.prototype,fz=Object.prototype,pz=dz.toString,mz=fz.hasOwnProperty,hz=RegExp("^"+pz.call(mz).replace(uz,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gz(e){if(!sz(e)||az(e))return!1;var t=oz(e)?hz:cz;return t.test(lz(e))}XT.exports=gz});var tD=v((mde,eD)=>{function yz(e,t){return e?.[t]}eD.exports=yz});var yo=v((hde,rD)=>{var bz=ZT(),vz=tD();function wz(e,t){var r=vz(e,t);return bz(r)?r:void 0}rD.exports=wz});var lf=v((gde,nD)=>{var Cz=yo(),Ez=Dn(),Az=Cz(Ez,"Map");nD.exports=Az});var wu=v((yde,iD)=>{var Sz=yo(),Nz=Sz(Object,"create");iD.exports=Nz});var sD=v((bde,aD)=>{var oD=wu();function _z(){this.__data__=oD?oD(null):{},this.size=0}aD.exports=_z});var uD=v((vde,lD)=>{function Tz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}lD.exports=Tz});var dD=v((wde,cD)=>{var Dz=wu(),Iz="__lodash_hash_undefined__",Oz=Object.prototype,Pz=Oz.hasOwnProperty;function Rz(e){var t=this.__data__;if(Dz){var r=t[e];return r===Iz?void 0:r}return Pz.call(t,e)?t[e]:void 0}cD.exports=Rz});var pD=v((Cde,fD)=>{var Lz=wu(),kz=Object.prototype,$z=kz.hasOwnProperty;function xz(e){var t=this.__data__;return Lz?t[e]!==void 0:$z.call(t,e)}fD.exports=xz});var hD=v((Ede,mD)=>{var Fz=wu(),Mz="__lodash_hash_undefined__";function Uz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Fz&&t===void 0?Mz:t,this}mD.exports=Uz});var yD=v((Ade,gD)=>{var Bz=sD(),qz=uD(),Vz=dD(),Gz=pD(),Wz=hD();function As(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}As.prototype.clear=Bz;As.prototype.delete=qz;As.prototype.get=Vz;As.prototype.has=Gz;As.prototype.set=Wz;gD.exports=As});var wD=v((Sde,vD)=>{var bD=yD(),zz=yu(),jz=lf();function Hz(){this.size=0,this.__data__={hash:new bD,map:new(jz||zz),string:new bD}}vD.exports=Hz});var ED=v((Nde,CD)=>{function Kz(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}CD.exports=Kz});var Cu=v((_de,AD)=>{var Jz=ED();function Yz(e,t){var r=e.__data__;return Jz(t)?r[typeof t=="string"?"string":"hash"]:r.map}AD.exports=Yz});var ND=v((Tde,SD)=>{var Qz=Cu();function Xz(e){var t=Qz(this,e).delete(e);return this.size-=t?1:0,t}SD.exports=Xz});var TD=v((Dde,_D)=>{var Zz=Cu();function ej(e){return Zz(this,e).get(e)}_D.exports=ej});var ID=v((Ide,DD)=>{var tj=Cu();function rj(e){return tj(this,e).has(e)}DD.exports=rj});var PD=v((Ode,OD)=>{var nj=Cu();function ij(e,t){var r=nj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}OD.exports=ij});var uf=v((Pde,RD)=>{var oj=wD(),aj=ND(),sj=TD(),lj=ID(),uj=PD();function Ss(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Ss.prototype.clear=oj;Ss.prototype.delete=aj;Ss.prototype.get=sj;Ss.prototype.has=lj;Ss.prototype.set=uj;RD.exports=Ss});var kD=v((Rde,LD)=>{var cj=yu(),dj=lf(),fj=uf(),pj=200;function mj(e,t){var r=this.__data__;if(r instanceof cj){var n=r.__data__;if(!dj||n.length<pj-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new fj(n)}return r.set(e,t),this.size=r.size,this}LD.exports=mj});var S0=v((Lde,$D)=>{var hj=yu(),gj=NT(),yj=TT(),bj=IT(),vj=PT(),wj=kD();function Ns(e){var t=this.__data__=new hj(e);this.size=t.size}Ns.prototype.clear=gj;Ns.prototype.delete=yj;Ns.prototype.get=bj;Ns.prototype.has=vj;Ns.prototype.set=wj;$D.exports=Ns});var FD=v((kde,xD)=>{var Cj="__lodash_hash_undefined__";function Ej(e){return this.__data__.set(e,Cj),this}xD.exports=Ej});var UD=v(($de,MD)=>{function Aj(e){return this.__data__.has(e)}MD.exports=Aj});var qD=v((xde,BD)=>{var Sj=uf(),Nj=FD(),_j=UD();function cf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Sj;++t<r;)this.add(e[t])}cf.prototype.add=cf.prototype.push=Nj;cf.prototype.has=_j;BD.exports=cf});var GD=v((Fde,VD)=>{function Tj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}VD.exports=Tj});var zD=v((Mde,WD)=>{function Dj(e,t){return e.has(t)}WD.exports=Dj});var N0=v((Ude,jD)=>{var Ij=qD(),Oj=GD(),Pj=zD(),Rj=1,Lj=2;function kj(e,t,r,n,i,o){var a=r&Rj,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&Lj?new Ij: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(!Oj(t,function(b,w){if(!Pj(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}jD.exports=kj});var _0=v((Bde,HD)=>{var $j=Dn(),xj=$j.Uint8Array;HD.exports=xj});var JD=v((qde,KD)=>{function Fj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}KD.exports=Fj});var QD=v((Vde,YD)=>{function Mj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}YD.exports=Mj});var rI=v((Gde,tI)=>{var XD=bu(),ZD=_0(),Uj=Cs(),Bj=N0(),qj=JD(),Vj=QD(),Gj=1,Wj=2,zj="[object Boolean]",jj="[object Date]",Hj="[object Error]",Kj="[object Map]",Jj="[object Number]",Yj="[object RegExp]",Qj="[object Set]",Xj="[object String]",Zj="[object Symbol]",e7="[object ArrayBuffer]",t7="[object DataView]",eI=XD?XD.prototype:void 0,T0=eI?eI.valueOf:void 0;function r7(e,t,r,n,i,o,a){switch(r){case t7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case e7:return!(e.byteLength!=t.byteLength||!o(new ZD(e),new ZD(t)));case zj:case jj:case Jj:return Uj(+e,+t);case Hj:return e.name==t.name&&e.message==t.message;case Yj:case Xj:return e==t+"";case Kj:var s=qj;case Qj:var l=n&Gj;if(s||(s=Vj),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=Wj,a.set(e,t);var c=Bj(s(e),s(t),n,i,o,a);return a.delete(e),c;case Zj:if(T0)return T0.call(e)==T0.call(t)}return!1}tI.exports=r7});var iI=v((Wde,nI)=>{function n7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}nI.exports=n7});var bo=v((zde,oI)=>{var i7=Array.isArray;oI.exports=i7});var sI=v((jde,aI)=>{var o7=iI(),a7=bo();function s7(e,t,r){var n=t(e);return a7(e)?n:o7(n,r(e))}aI.exports=s7});var uI=v((Hde,lI)=>{function l7(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}lI.exports=l7});var dI=v((Kde,cI)=>{function u7(){return[]}cI.exports=u7});var mI=v((Jde,pI)=>{var c7=uI(),d7=dI(),f7=Object.prototype,p7=f7.propertyIsEnumerable,fI=Object.getOwnPropertySymbols,m7=fI?function(e){return e==null?[]:(e=Object(e),c7(fI(e),function(t){return p7.call(e,t)}))}:d7;pI.exports=m7});var gI=v((Yde,hI)=>{function h7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}hI.exports=h7});var vo=v((Qde,yI)=>{function g7(e){return e!=null&&typeof e=="object"}yI.exports=g7});var vI=v((Xde,bI)=>{var y7=sa(),b7=vo(),v7="[object Arguments]";function w7(e){return b7(e)&&y7(e)==v7}bI.exports=w7});var D0=v((Zde,EI)=>{var wI=vI(),C7=vo(),CI=Object.prototype,E7=CI.hasOwnProperty,A7=CI.propertyIsEnumerable,S7=wI((function(){return arguments})())?wI:function(e){return C7(e)&&E7.call(e,"callee")&&!A7.call(e,"callee")};EI.exports=S7});var SI=v((efe,AI)=>{function N7(){return!1}AI.exports=N7});var df=v((Eu,_s)=>{var _7=Dn(),T7=SI(),TI=typeof Eu=="object"&&Eu&&!Eu.nodeType&&Eu,NI=TI&&typeof _s=="object"&&_s&&!_s.nodeType&&_s,D7=NI&&NI.exports===TI,_I=D7?_7.Buffer:void 0,I7=_I?_I.isBuffer:void 0,O7=I7||T7;_s.exports=O7});var ff=v((tfe,DI)=>{var P7=9007199254740991,R7=/^(?:0|[1-9]\d*)$/;function L7(e,t){var r=typeof e;return t=t??P7,!!t&&(r=="number"||r!="symbol"&&R7.test(e))&&e>-1&&e%1==0&&e<t}DI.exports=L7});var I0=v((rfe,II)=>{var k7=9007199254740991;function $7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=k7}II.exports=$7});var PI=v((nfe,OI)=>{var x7=sa(),F7=I0(),M7=vo(),U7="[object Arguments]",B7="[object Array]",q7="[object Boolean]",V7="[object Date]",G7="[object Error]",W7="[object Function]",z7="[object Map]",j7="[object Number]",H7="[object Object]",K7="[object RegExp]",J7="[object Set]",Y7="[object String]",Q7="[object WeakMap]",X7="[object ArrayBuffer]",Z7="[object DataView]",eH="[object Float32Array]",tH="[object Float64Array]",rH="[object Int8Array]",nH="[object Int16Array]",iH="[object Int32Array]",oH="[object Uint8Array]",aH="[object Uint8ClampedArray]",sH="[object Uint16Array]",lH="[object Uint32Array]",$e={};$e[eH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=!0;$e[U7]=$e[B7]=$e[X7]=$e[q7]=$e[Z7]=$e[V7]=$e[G7]=$e[W7]=$e[z7]=$e[j7]=$e[H7]=$e[K7]=$e[J7]=$e[Y7]=$e[Q7]=!1;function uH(e){return M7(e)&&F7(e.length)&&!!$e[x7(e)]}OI.exports=uH});var LI=v((ife,RI)=>{function cH(e){return function(t){return e(t)}}RI.exports=cH});var $I=v((Au,Ts)=>{var dH=C0(),kI=typeof Au=="object"&&Au&&!Au.nodeType&&Au,Su=kI&&typeof Ts=="object"&&Ts&&!Ts.nodeType&&Ts,fH=Su&&Su.exports===kI,O0=fH&&dH.process,pH=(function(){try{var e=Su&&Su.require&&Su.require("util").types;return e||O0&&O0.binding&&O0.binding("util")}catch{}})();Ts.exports=pH});var pf=v((ofe,MI)=>{var mH=PI(),hH=LI(),xI=$I(),FI=xI&&xI.isTypedArray,gH=FI?hH(FI):mH;MI.exports=gH});var P0=v((afe,UI)=>{var yH=gI(),bH=D0(),vH=bo(),wH=df(),CH=ff(),EH=pf(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e,t){var r=vH(e),n=!r&&bH(e),i=!r&&!n&&wH(e),o=!r&&!n&&!i&&EH(e),a=r||n||i||o,s=a?yH(e.length,String):[],l=s.length;for(var u in e)(t||SH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||CH(u,l)))&&s.push(u);return s}UI.exports=NH});var mf=v((sfe,BI)=>{var _H=Object.prototype;function TH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||_H;return e===r}BI.exports=TH});var R0=v((lfe,qI)=>{function DH(e,t){return function(r){return e(t(r))}}qI.exports=DH});var GI=v((ufe,VI)=>{var IH=R0(),OH=IH(Object.keys,Object);VI.exports=OH});var zI=v((cfe,WI)=>{var PH=mf(),RH=GI(),LH=Object.prototype,kH=LH.hasOwnProperty;function $H(e){if(!PH(e))return RH(e);var t=[];for(var r in Object(e))kH.call(e,r)&&r!="constructor"&&t.push(r);return t}WI.exports=$H});var Nu=v((dfe,jI)=>{var xH=sf(),FH=I0();function MH(e){return e!=null&&FH(e.length)&&!xH(e)}jI.exports=MH});var KI=v((ffe,HI)=>{var UH=P0(),BH=zI(),qH=Nu();function VH(e){return qH(e)?UH(e):BH(e)}HI.exports=VH});var YI=v((pfe,JI)=>{var GH=sI(),WH=mI(),zH=KI();function jH(e){return GH(e,zH,WH)}JI.exports=jH});var ZI=v((mfe,XI)=>{var QI=YI(),HH=1,KH=Object.prototype,JH=KH.hasOwnProperty;function YH(e,t,r,n,i,o){var a=r&HH,s=QI(e),l=s.length,u=QI(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:JH.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 E=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(E===void 0?b===w||i(b,w,r,n,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,P=t.constructor;S!=P&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof P=="function"&&P instanceof P)&&(h=!1)}return o.delete(e),o.delete(t),h}XI.exports=YH});var tO=v((hfe,eO)=>{var QH=yo(),XH=Dn(),ZH=QH(XH,"DataView");eO.exports=ZH});var nO=v((gfe,rO)=>{var eK=yo(),tK=Dn(),rK=eK(tK,"Promise");rO.exports=rK});var oO=v((yfe,iO)=>{var nK=yo(),iK=Dn(),oK=nK(iK,"Set");iO.exports=oK});var sO=v((bfe,aO)=>{var aK=yo(),sK=Dn(),lK=aK(sK,"WeakMap");aO.exports=lK});var hO=v((vfe,mO)=>{var L0=tO(),k0=lf(),$0=nO(),x0=oO(),F0=sO(),pO=sa(),Ds=A0(),lO="[object Map]",uK="[object Object]",uO="[object Promise]",cO="[object Set]",dO="[object WeakMap]",fO="[object DataView]",cK=Ds(L0),dK=Ds(k0),fK=Ds($0),pK=Ds(x0),mK=Ds(F0),la=pO;(L0&&la(new L0(new ArrayBuffer(1)))!=fO||k0&&la(new k0)!=lO||$0&&la($0.resolve())!=uO||x0&&la(new x0)!=cO||F0&&la(new F0)!=dO)&&(la=function(e){var t=pO(e),r=t==uK?e.constructor:void 0,n=r?Ds(r):"";if(n)switch(n){case cK:return fO;case dK:return lO;case fK:return uO;case pK:return cO;case mK:return dO}return t});mO.exports=la});var AO=v((wfe,EO)=>{var M0=S0(),hK=N0(),gK=rI(),yK=ZI(),gO=hO(),yO=bo(),bO=df(),bK=pf(),vK=1,vO="[object Arguments]",wO="[object Array]",hf="[object Object]",wK=Object.prototype,CO=wK.hasOwnProperty;function CK(e,t,r,n,i,o){var a=yO(e),s=yO(t),l=a?wO:gO(e),u=s?wO:gO(t);l=l==vO?hf:l,u=u==vO?hf:u;var c=l==hf,d=u==hf,f=l==u;if(f&&bO(e)){if(!bO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new M0),a||bK(e)?hK(e,t,r,n,i,o):gK(e,t,l,r,n,i,o);if(!(r&vK)){var m=c&&CO.call(e,"__wrapped__"),p=d&&CO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new M0),i(h,g,r,n,o)}}return f?(o||(o=new M0),yK(e,t,r,n,i,o)):!1}EO.exports=CK});var TO=v((Cfe,_O)=>{var EK=AO(),SO=vo();function NO(e,t,r,n,i){return e===t?!0:e==null||t==null||!SO(e)&&!SO(t)?e!==e&&t!==t:EK(e,t,r,n,NO,i)}_O.exports=NO});var IO=v((Efe,DO)=>{var AK=TO();function SK(e,t){return AK(e,t)}DO.exports=SK});var U0=v((Afe,OO)=>{var NK=yo(),_K=(function(){try{var e=NK(Object,"defineProperty");return e({},"",{}),e}catch{}})();OO.exports=_K});var gf=v((Sfe,RO)=>{var PO=U0();function TK(e,t,r){t=="__proto__"&&PO?PO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}RO.exports=TK});var B0=v((Nfe,LO)=>{var DK=gf(),IK=Cs();function OK(e,t,r){(r!==void 0&&!IK(e[t],r)||r===void 0&&!(t in e))&&DK(e,t,r)}LO.exports=OK});var $O=v((_fe,kO)=>{function PK(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}}kO.exports=PK});var FO=v((Tfe,xO)=>{var RK=$O(),LK=RK();xO.exports=LK});var VO=v((_u,Is)=>{var kK=Dn(),qO=typeof _u=="object"&&_u&&!_u.nodeType&&_u,MO=qO&&typeof Is=="object"&&Is&&!Is.nodeType&&Is,$K=MO&&MO.exports===qO,UO=$K?kK.Buffer:void 0,BO=UO?UO.allocUnsafe:void 0;function xK(e,t){if(t)return e.slice();var r=e.length,n=BO?BO(r):new e.constructor(r);return e.copy(n),n}Is.exports=xK});var zO=v((Dfe,WO)=>{var GO=_0();function FK(e){var t=new e.constructor(e.byteLength);return new GO(t).set(new GO(e)),t}WO.exports=FK});var HO=v((Ife,jO)=>{var MK=zO();function UK(e,t){var r=t?MK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}jO.exports=UK});var JO=v((Ofe,KO)=>{function BK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}KO.exports=BK});var XO=v((Pfe,QO)=>{var qK=ki(),YO=Object.create,VK=(function(){function e(){}return function(t){if(!qK(t))return{};if(YO)return YO(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();QO.exports=VK});var q0=v((Rfe,ZO)=>{var GK=R0(),WK=GK(Object.getPrototypeOf,Object);ZO.exports=WK});var tP=v((Lfe,eP)=>{var zK=XO(),jK=q0(),HK=mf();function KK(e){return typeof e.constructor=="function"&&!HK(e)?zK(jK(e)):{}}eP.exports=KK});var nP=v((kfe,rP)=>{var JK=Nu(),YK=vo();function QK(e){return YK(e)&&JK(e)}rP.exports=QK});var aP=v(($fe,oP)=>{var XK=sa(),ZK=q0(),eJ=vo(),tJ="[object Object]",rJ=Function.prototype,nJ=Object.prototype,iP=rJ.toString,iJ=nJ.hasOwnProperty,oJ=iP.call(Object);function aJ(e){if(!eJ(e)||XK(e)!=tJ)return!1;var t=ZK(e);if(t===null)return!0;var r=iJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&iP.call(r)==oJ}oP.exports=aJ});var V0=v((xfe,sP)=>{function sJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}sP.exports=sJ});var G0=v((Ffe,lP)=>{var lJ=gf(),uJ=Cs(),cJ=Object.prototype,dJ=cJ.hasOwnProperty;function fJ(e,t,r){var n=e[t];(!(dJ.call(e,t)&&uJ(n,r))||r===void 0&&!(t in e))&&lJ(e,t,r)}lP.exports=fJ});var cP=v((Mfe,uP)=>{var pJ=G0(),mJ=gf();function hJ(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?mJ(r,s,l):pJ(r,s,l)}return r}uP.exports=hJ});var fP=v((Ufe,dP)=>{function gJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}dP.exports=gJ});var mP=v((Bfe,pP)=>{var yJ=ki(),bJ=mf(),vJ=fP(),wJ=Object.prototype,CJ=wJ.hasOwnProperty;function EJ(e){if(!yJ(e))return vJ(e);var t=bJ(e),r=[];for(var n in e)n=="constructor"&&(t||!CJ.call(e,n))||r.push(n);return r}pP.exports=EJ});var W0=v((qfe,hP)=>{var AJ=P0(),SJ=mP(),NJ=Nu();function _J(e){return NJ(e)?AJ(e,!0):SJ(e)}hP.exports=_J});var yP=v((Vfe,gP)=>{var TJ=cP(),DJ=W0();function IJ(e){return TJ(e,DJ(e))}gP.exports=IJ});var AP=v((Gfe,EP)=>{var bP=B0(),OJ=VO(),PJ=HO(),RJ=JO(),LJ=tP(),vP=D0(),wP=bo(),kJ=nP(),$J=df(),xJ=sf(),FJ=ki(),MJ=aP(),UJ=pf(),CP=V0(),BJ=yP();function qJ(e,t,r,n,i,o,a){var s=CP(e,r),l=CP(t,r),u=a.get(l);if(u){bP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=wP(l),m=!f&&$J(l),p=!f&&!m&&UJ(l);c=l,f||m||p?wP(s)?c=s:kJ(s)?c=RJ(s):m?(d=!1,c=OJ(l,!0)):p?(d=!1,c=PJ(l,!0)):c=[]:MJ(l)||vP(l)?(c=s,vP(s)?c=BJ(s):(!FJ(s)||xJ(s))&&(c=LJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),bP(e,r,c)}EP.exports=qJ});var z0=v((Wfe,NP)=>{var VJ=S0(),GJ=B0(),WJ=FO(),zJ=AP(),jJ=ki(),HJ=W0(),KJ=V0();function SP(e,t,r,n,i){e!==t&&WJ(t,function(o,a){if(i||(i=new VJ),jJ(o))zJ(e,t,a,r,SP,n,i);else{var s=n?n(KJ(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),GJ(e,a,s)}},HJ)}NP.exports=SP});var j0=v((zfe,_P)=>{function JJ(e){return e}_P.exports=JJ});var DP=v((jfe,TP)=>{function YJ(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)}TP.exports=YJ});var PP=v((Hfe,OP)=>{var QJ=DP(),IP=Math.max;function XJ(e,t,r){return t=IP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=IP(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),QJ(e,this,s)}}OP.exports=XJ});var LP=v((Kfe,RP)=>{function ZJ(e){return function(){return e}}RP.exports=ZJ});var xP=v((Jfe,$P)=>{var eY=LP(),kP=U0(),tY=j0(),rY=kP?function(e,t){return kP(e,"toString",{configurable:!0,enumerable:!1,value:eY(t),writable:!0})}:tY;$P.exports=rY});var MP=v((Yfe,FP)=>{var nY=800,iY=16,oY=Date.now;function aY(e){var t=0,r=0;return function(){var n=oY(),i=iY-(n-r);if(r=n,i>0){if(++t>=nY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}FP.exports=aY});var BP=v((Qfe,UP)=>{var sY=xP(),lY=MP(),uY=lY(sY);UP.exports=uY});var VP=v((Xfe,qP)=>{var cY=j0(),dY=PP(),fY=BP();function pY(e,t){return fY(dY(e,t,cY),e+"")}qP.exports=pY});var WP=v((Zfe,GP)=>{var mY=Cs(),hY=Nu(),gY=ff(),yY=ki();function bY(e,t,r){if(!yY(r))return!1;var n=typeof t;return(n=="number"?hY(r)&&gY(t,r.length):n=="string"&&t in r)?mY(r[t],e):!1}GP.exports=bY});var H0=v((epe,zP)=>{var vY=VP(),wY=WP();function CY(e){return vY(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&&wY(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})}zP.exports=CY});var HP=v((tpe,jP)=>{var EY=z0(),AY=H0(),SY=AY(function(e,t,r,n){EY(e,t,r,n)});jP.exports=SY});var sn,Tu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(sn||(sn={}))});function JP(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${KP.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 KP,NY,YP=k(()=>{"use strict";KP=Ee(w0()),NY=Ee(v0());});var K0,QP=k(()=>{"use strict";Xd();K0=uu({packageName:"shell-settings",settings:{prodEcsEndpoint:{description:"The url for the PROD ECS endpoint",values:{default:"https://ecs.office.com",dod:"https://config.ecs.dod.teams.microsoft.us",high:"https://config.ecs.gov.teams.microsoft.us",ex:"https://config.ecs.teams.eaglex.ic.gov",rx:"https://config.ecs.teams.microsoft.scloud"}},integrationEcsEndpoint:{description:"The url for the INT ECS endpoint",values:{default:"https://config.edge.skype.net"}}}})});var ZP,eR,tR,rR,J0,_Y,yf,XP,Y0=k(()=>{"use strict";ZP=Ee(v0()),eR=Ee(lT()),tR=Ee(w0()),rR=Ee(IO()),J0=Ee(HP());Tu();YP();QP();_Y=60*1e3,yf=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=sn.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"?K0.prodEcsEndpoint:K0.integrationEcsEndpoint}client=new eR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=ZP.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:[tR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:JP(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===sn.NotLoaded&&(this._status=sn.Initialized)}catch(s){this._status=sn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*_Y)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,J0.default)({},t.fallback,n,t.override,XP)};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,rR.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,J0.default)({},this.client.getConfig()?.config,this.clientConfigOverride,XP);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=sn.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})}},XP=(e,t)=>{if(Array.isArray(t))return t}});var iR=v((cpe,nR)=>{"use strict";var TY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};nR.exports=TY});var Q0=v((dpe,aR)=>{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{}}}),oR=function(){return Du};Object.setPrototypeOf(oR,Du);aR.exports=oR});var uR=v((fpe,lR)=>{var Iu=new Proxy(function(){return Iu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Iu},apply:function(){return Iu},construct:function(){return{}}}),sR=function(){return Iu};Object.setPrototypeOf(sR,Iu);lR.exports=sR});var gR=v((ppe,hR)=>{"use strict";var X0=uR(),DY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},IY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},OY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},pR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Z0={};Z0[X0.ForwardRef]=OY;Z0[X0.Memo]=pR;function cR(e){return X0.isMemo(e)?pR:Z0[e.$$typeof]||DY}var PY=Object.defineProperty,RY=Object.getOwnPropertyNames,dR=Object.getOwnPropertySymbols,LY=Object.getOwnPropertyDescriptor,kY=Object.getPrototypeOf,fR=Object.prototype;function mR(e,t,r){if(typeof t!="string"){if(fR){var n=kY(t);n&&n!==fR&&mR(e,n,r)}var i=RY(t);dR&&(i=i.concat(dR(t)));for(var o=cR(e),a=cR(t),s=0;s<i.length;++s){var l=i[s];if(!IY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=LY(t,l);try{PY(e,l,u)}catch{}}}}return e}hR.exports=mR});function bR(e,t,r){let[n,i]=(0,Os.useState)(e.getConfig(t));return(0,Os.useEffect)(()=>{if(!r?.subscribe&&e.status===sn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function vR(e){return function(t,r){return bR(e,t,r)}}function wR(e,t,r,n){let i=o=>{let a=bR(e,t,n),s={...o,...a};return Os.default.createElement(r,{...s})};return(0,yR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function CR(e,t,r,n){return t.reduce((i,o)=>wR(e,o,i,n),r)}function ER(e){return function(t,r,n){return wR(e,t,r,n)}}var yR,Os,ey=k(()=>{"use strict";yR=Ee(gR()),Os=Ee(Q0());Tu();});var SR=v((gpe,AR)=>{var $Y=z0(),xY=H0(),FY=xY(function(e,t,r){$Y(e,t,r)});AR.exports=FY});var bf=v((ype,NR)=>{var MY=sa(),UY=vo(),BY="[object Symbol]";function qY(e){return typeof e=="symbol"||UY(e)&&MY(e)==BY}NR.exports=qY});var TR=v((bpe,_R)=>{var VY=bo(),GY=bf(),WY=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zY=/^\w*$/;function jY(e,t){if(VY(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||GY(e)?!0:zY.test(e)||!WY.test(e)||t!=null&&e in Object(t)}_R.exports=jY});var OR=v((vpe,IR)=>{var DR=uf(),HY="Expected a function";function ty(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(HY);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(ty.Cache||DR),r}ty.Cache=DR;IR.exports=ty});var RR=v((wpe,PR)=>{var KY=OR(),JY=500;function YY(e){var t=KY(e,function(n){return r.size===JY&&r.clear(),n}),r=t.cache;return t}PR.exports=YY});var kR=v((Cpe,LR)=>{var QY=RR(),XY=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ZY=/\\(\\)?/g,eQ=QY(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(XY,function(r,n,i,o){t.push(i?o.replace(ZY,"$1"):n||r)}),t});LR.exports=eQ});var xR=v((Epe,$R)=>{function tQ(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}$R.exports=tQ});var VR=v((Ape,qR)=>{var FR=bu(),rQ=xR(),nQ=bo(),iQ=bf(),oQ=1/0,MR=FR?FR.prototype:void 0,UR=MR?MR.toString:void 0;function BR(e){if(typeof e=="string")return e;if(nQ(e))return rQ(e,BR)+"";if(iQ(e))return UR?UR.call(e):"";var t=e+"";return t=="0"&&1/e==-oQ?"-0":t}qR.exports=BR});var WR=v((Spe,GR)=>{var aQ=VR();function sQ(e){return e==null?"":aQ(e)}GR.exports=sQ});var jR=v((Npe,zR)=>{var lQ=bo(),uQ=TR(),cQ=kR(),dQ=WR();function fQ(e,t){return lQ(e)?e:uQ(e,t)?[e]:cQ(dQ(e))}zR.exports=fQ});var KR=v((_pe,HR)=>{var pQ=bf(),mQ=1/0;function hQ(e){if(typeof e=="string"||pQ(e))return e;var t=e+"";return t=="0"&&1/e==-mQ?"-0":t}HR.exports=hQ});var QR=v((Tpe,YR)=>{var gQ=G0(),yQ=jR(),bQ=ff(),JR=ki(),vQ=KR();function wQ(e,t,r,n){if(!JR(e))return e;t=yQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=vQ(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=JR(c)?c:bQ(t[i+1])?[]:{})}gQ(s,l,u),s=s[l]}return e}YR.exports=wQ});var ZR=v((Dpe,XR)=>{var CQ=QR();function EQ(e,t,r){return e==null?e:CQ(e,t,r)}XR.exports=EQ});function n2(e){let{query:t}=(0,r2.default)(window.location.href,!0);return SQ(e,t),e}function SQ(e,t){let r=AQ+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+i2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,t2.default)(u,c,s)}(0,e2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var e2,t2,r2,i2,AQ,o2=k(()=>{"use strict";e2=Ee(SR()),t2=Ee(ZR()),r2=Ee(s0());i2=".",AQ="ecs"+i2});function wf(e,t,r){let n=n2(new yf(e,t,r));function i(o){(0,vf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:_Q(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>CR(n,o,a,s)}}function _Q(e){let t=vR(e),r=ER(e);return function(i){let o=nT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===sn.ConfigsLoaded,c0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var NQ,vf,ry=k(()=>{"use strict";NQ=Ee(iR()),vf=Ee(Q0());b0();Y0();Tu();ey();o2();d0();});var a2=k(()=>{"use strict";b0();Y0();ry();Tu();ey();rf();f0();});function Cf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Ps.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Ps.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Ps.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Ps,ny=k(()=>{"use strict";Ps=Ee(ra());});var Kpe,Jpe,Ype,s2=k(()=>{"use strict";a2();ny();({featuresClient:Kpe,createFeature:Jpe,useFeaturesClientInitParams:Ype}=wf("PowerApps-Shell-Test",Cf("shell-features")))});var c2=v((Xpe,u2)=>{var Ou=new Proxy(function(){return Ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ou},apply:function(){return Ou},construct:function(){return{}}}),l2=function(){return Ou};Object.setPrototypeOf(l2,Ou);u2.exports=l2});var TQ,DQ,d2=k(()=>{"use strict";au();TQ=Ee(c2()),DQ=Ee(ra());});var f2=k(()=>{"use strict";s2();ny();d2();});var sme,Rs,lme,p2=k(()=>{"use strict";f2();ry();({featuresClient:sme,createFeature:Rs,useFeaturesClientInitParams:lme}=wf("PowerApps-MakerPortal",Cf("powerapps-features")))});var m2,h2,fme,pme,mme,hme,iy=k(()=>{"use strict";rT();p2();({feature:m2}=Rs({teamName:"MakerPortal",owners:["debeshd"],description:"Enable the auto insertion of cell in a row when a section is initialized",createdOn:"09/01/2023",fallback:{enableAutoInsertionOfCellInRow:ws.enableAutoInsertionOfCellInRow}})),{feature:h2}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:ws.enableOneGridEvents}}),{feature:fme}=Rs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:ws.disablePBIComponents}}),{feature:pme}=Rs({teamName:"MakerPortal",owners:["jennietu"],description:"Enables agent response in form designer. This feature is used to enable the agent response in form designer",createdOn:"04/24/2025",fallback:{enableAgentResponse:ws.enableAgentResponse}}),{feature:mme,useFeature:hme}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:ws.enableDelayedLocalizationForCustomControls}})});var b2=v((yme,y2)=>{var Pu=new Proxy(function(){return Pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Pu},apply:function(){return Pu},construct:function(){return{}}}),g2=function(){return Pu};Object.setPrototypeOf(g2,Pu);y2.exports=g2});var Qt,wo=k(()=>{"use strict";pt();ot();Yt();fu();le();Dt();Qt=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(C.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){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(C.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(C.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(C.formControl);if(t&&t.ClassId){let r=at.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&at.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===C.formSection||this.NodeName===C.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(C.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(C.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Ls,oy=k(()=>{"use strict";Yt();le();Dt();Ls=class extends re{constructor(t,r){super(C.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var v2,ks,ay=k(()=>{"use strict";ot();oy();le();Dt();wo();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(v2||(v2={}));ks=class extends Qt{constructor(t,r){super(C.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(C.EventHandlers);return t&&t.length?t[0].getChildren(C.handler):[]}getAllDependencies(){let t=this.getChildren(C.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(C.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(C.formDependencies,this)),r=this.getFirstChild(C.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Ls(r,n.toString()))}}}});var In,Ru=k(()=>{"use strict";pt();Bl();ot();ta();le();Dt();_n();In=class extends re{previewVersion;constructor(t){super(C.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return 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 nr,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(C.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 nr;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()===mt.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 $s,sy=k(()=>{"use strict";Yt();zo();Ru();le();Dt();$s=class extends In{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 an.Chart:return an.Chart;case an.Grid:return an.Grid;default:return an.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=an.Chart:this.chartGridMode=this.enableChartPicker?an.All:an.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(jt.dataset)?n[i].getParameters().get(jt.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 xs,ly=k(()=>{"use strict";Yt();zo();Ru();le();xs=class extends In{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(jt.value)?n[i].getParameters().get(jt.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 w2,uy,_r,Lu=k(()=>{"use strict";w2=Ee(b2());wo();le();ot();pt();ay();Ru();fu();g0();Qg();_n();ta();gs();sy();ly();cy();rs();uy="_",_r=class e extends Qt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(C.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof In?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:!na.dependencyFieldCount.containsKey(this.control.id):!na.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ks(this,iu.onLoad))}get dependencies(){let t=this.getChildren(C.formEvents);for(let r of t){let n=r.getChildren(C.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Hd[i])o=Hd[i].replace(/ /g,uy)+uy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,w2.trackErrorTrace)(sr,{eventName:`${b_}/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===ln.Grid?(l=new $s(this),l.indicationOfSubgrid=!0):o===ln.Lookup?l=new xs(this):l=new In(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=at.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(at.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!at.isUnboundFormControlByIdentifier(d)?o!==ln.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=at.GetRowSpan(l),(at.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||at.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(at.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||at.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||at.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()===C.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(C.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return 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(m0.ONE_COLUMN),n=Number(m0.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(C.formRow)}getParentSection(){return this.getAncestor(C.formSection)}getParentTab(){return this.getAncestor(C.formTab)}getParentForm(){return this.getAncestor(C.form)}isInHeader(){let t=this.getAncestor(C.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(C.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(C.formHeader):this.isInFooter()?this.getAncestor(C.formFooter):null}get FieldRequiredLevel(){return this.fieldRequiredLevel}set FieldRequiredLevel(t){this.fieldRequiredLevel=t}get FieldPlaceholder(){return this.fieldPlaceholder}set FieldPlaceholder(t){this.fieldPlaceholder=t}get IsNewField(){return this.isNewField}set IsNewField(t){this.isNewField=t}get IsUserSpacer(){let t=this.getProperty(y.userspacer);return 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 ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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===io.ApplicationRequired||a===io.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?io.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??io.None}isCellLockedByExternal(t){return this.control||this.IsUnboundControl?!1:t.getEntityAttributeByName(this.control.dataFieldName).isRequiredForForm||!this.isIndependent}async toJSON(t){return{Id:this.id&&this.id.guidString,Name:this.Name,Label:this.getDisplayName(t.langCode),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId.guidString,PreviewId:this.id&&this.id.guidString,ColSpan:this.colspan,RowSpan:this.rowspan,AutoExpand:this.autoexpand,IsInFirstColumnOfSection:!1,IsInLastColumnOfSection:!1,AvailableForPhone:this.availableforphone,UserSpacer:this.IsUserSpacer,IsPreviewCell:!1,IsStreamCell:!1,IsChartCell:!1,IsTileCell:!1,Control:this.control&&await this.control.toJSON(t)}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===C.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===C.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let r=t.length-1,n=0;for(;r>0&&parseInt(t.charAt(r),10);)r--;return r>0&&r!==t.length-1&&t.charAt(r)===uy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Fs,dy=k(()=>{"use strict";Yt();le();Dt();Fs=class extends re{isInternal;constructor(t,r,n,i){super(C.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.libraryUniqueId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),t?.toUpperCase()}set libraryUniqueId(t){this.setProperty(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var ua,fy=k(()=>{"use strict";ot();Lu();le();Dt();ua=class extends re{isRowAddedOnDragOver;constructor(t){super(C.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let r of t)this.addChild(r)}updateCell(t,r){return this.updateChild(t,r)}removeCell(t){return 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(C.formSection)}insertPaddingCellAtIndex(t){let r=new _r(this);r.setDefaultProperties(),this.insertCellAtIndex(r,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(C.formCell)}get rowColspan(){return this.cells.reduce((t,r)=>t+r.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let r=[],n=[];if(this.cells){for(let i of this.cells)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function IQ(e){switch(e){case ia.Left:return aa.Left;case ia.Right:return aa.Right;case ia.Center:return aa.Center;default:return aa.Left}}function OQ(e){switch(e){case bs.Left:return vs.Left;case bs.Top:return vs.Top;default:return vs.Left}}function C2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var PQ,ri,ku=k(()=>{"use strict";y0();pt();ot();Yt();iy();Lu();le();_n();wo();fy();PQ=115,ri=class e extends Qt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=ze.ONE_COLUMN;break;case 11:t=ze.TWO_COLUMN;break;case 111:t=ze.THREE_COLUMN;break;case 1111:t=ze.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===ze.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 ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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 ua(null);if(this.addGrandChild(C.formRows,r),m2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new _r(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===ze.REFERENCE_PANEL&&(n=ze.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(C.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(C.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(C.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(C.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(C.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(C.formRows);return t.length===0?[]:t[0].getChildren(C.formRow)}get columns(){let t=this.getProperty(y.columnName),r=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 C2(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(C.formColumn)}getParentTab(){return this.getAncestor(C.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){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?PQ: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:IQ(this.fieldLabelAlignment),Position:OQ(this.fieldLabelPosition)},Columns:C2(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===C.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===C.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===C.formFooter||this.NodeName===C.formHeader}}});var Co,Ef=k(()=>{"use strict";le();Dt();ku();Co=class e extends re{constructor(t){super(C.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ri(C.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}initialize(t,r,n,i=ze.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(C.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(C.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(C.formSections,t)}async getSectionsJSON(t){let r=[];if(this.sections)for(let n of this.sections)r.push(await n.toJSON(t));return r}async toJSON(t){return{Name:this.getProperty(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Af,E2=k(()=>{"use strict";pt();le();_n();ku();Af=class extends ri{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 Sf,A2=k(()=>{"use strict";Ef();le();E2();Sf=class extends Co{addAndIntializeNavBarSection(t,r,n,i){let o=new Af(C.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(C.formSections,o,n),o}}});var $i,Nf=k(()=>{"use strict";pt();ot();Yt();Ef();le();Dt();wo();$i=class extends Qt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(C.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(C.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=We.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=We.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=We.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=We.TWO_COLUMN_WIDER_RIGHT;break}t=We.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=We.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=We.THREE_COLUMN_WIDER_MID;break}t=We.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,ho.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,ho.IsUserDefined),this.addProperty(y.locklevel,ho.LockLevel),this.addProperty(y.showlabel,ho.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=ze.ONE_COLUMN,o=!0,a){let s=this.getChildren(C.formColumns)[0],l=[];switch(t){case We.ONE_COLUMN:l.push(100);break;case We.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case We.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case We.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case We.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case We.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Co(s);c.initialize(u,r,n,i),this.addGrandChild(C.formColumns,c)}}initialize(t,r,n,i,o,a=ze.ONE_COLUMN,s=!0,l){this.addChild(new re(C.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(C.formColumns);return t.length!==1?[]:t[0].getChildren(C.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){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(C.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(C.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(C.formColumns,t)}async getColumnsJSON(t){let r=[],n=[];if(this.columns){for(let i of this.columns)n.push(i.toJSON(t));for(let i of n)r.push(await i)}return r}async toJSON(t){return{Name:this.Name,Id:this.id&&this.id.guidString,Label:this.getDisplayName(t.langCode)+(!this.visible&&t.formModelService.showHiddenElements?"\u3000\u3000":""),ShowLabel:this.showlabel,Visible:this.visible||t.formModelService.showHiddenElements,LabelId:this.labelId&&this.labelId.guidString,UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString,Columns:await this.getColumnsJSON(t),EventHandlers:[],Expanded:this.expanded,ContentType:this.contentType,AvailableForPhone:this.availableforphone,Header:void 0,Footer:void 0}}getUsedNodeNameSet(t){let r=new Set;return t&&t.visit(n=>{if(n.getNodeName()===C.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ca,py=k(()=>{"use strict";pt();le();Dt();_n();A2();Nf();ca=class extends $i{constructor(t,r,n){super(t,We.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(C.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(C.formColumn)}getNavSectionForArea(t){for(let r of this.columns)for(let n of r.sections)if(n.AreaName===t)return n;return null}getNavCellFromNavId(t){for(let r of this.columns)for(let n of r.sections)for(let i of n.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<nf.FIVE_COLUMN;t++){let r=new Sf(this.getChildren(C.formColumns)[0]);r.initializeDefaultProperties(G_.FiveEqColumn),this.addGrandChild(C.formColumns,r)}}}});function LQ(e){switch(e){case mt.Main:return go.Main;case mt.QuickCreate:return go.QuickCreate;case mt.QuickViewForm:return go.Quick;case mt.Dialog:return go.Dialog;default:return go.None}}function kQ(e,t){if(t===mt.Main){if(e)switch(e.toLowerCase()){case"low":return mo.Low;case"highreadonlyvalues":return mo.HighReadOnlyValues;default:return mo.HighWithControls}return mo.Low}}var Tf,RQ,_f,S2=k(()=>{"use strict";Q_();Tf=Ee(ra());y0();ot();Yt();gs();iy();le();zo();Mg();ta();Lu();le();wo();dy();py();Nf();RQ="1920";_f=class e extends Qt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(C.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Gd,this._metadataChangeEvent=new af}get FormLibraries(){let t=this.getFirstChild(C.formLibraries),r=t?t.getAllChildren():[],n=this._getInternalLibraries();return r.concat(n)}getAllEvents(){let t=[],r=this.events;r&&(t=t.concat(r));for(let n of this.tabs){let i=n.events;i&&(t=t.concat(i)),n.findAll(o=>o instanceof _r).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 _r){if(t.control?.dataFieldName){let r=this.events;return r?r.filter(n=>n.attribute&&t.control.dataFieldName===n.attribute):null}else if(this.isCellEditableGridControl(t)){let r=this.events;return r?r.filter(n=>n.control&&t.control.id===n.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===C.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new Fs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,Tf.trackErrorTrace)(v_,{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))?RQ: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===mt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==mt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===mt.Main||this.formType===mt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(C.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(C.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(C.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(C.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new $i(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new $i(null,We.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(We.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(C.formTabs,a,i);let l=a.columns[0].sections[0];for(let u=0;u<t.rows.length;u++)l.appendRow(t.rows[u])}getNextTabCounter(t){for(let r=0;r<this.tabs.length;r++)if(this.tabs[r].Name===ho.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(C.formTabs);return t.length!==1?[]:t[0].getChildren(C.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ca)return t}return null}get NavigationNode(){let t=this.getChildren(C.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let n=this.getAllChildren().indexOf(this.NavigationNode);n>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,n))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(C.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(C.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(C.formFooter).length>0}get displayCondition(){let t=this.getChildren(C.formDisplayConditions);return t.length>0?t[0]:null}set displayCondition(t){this.deleteChild(this.displayCondition),this.addChild(t)}get entityName(){return this._entityName}get formId(){return this._formId}set formId(t){this._formId=t}get rawFormXml(){return this._rawFormXml}set rawFormXml(t){this._rawFormXml=t}get status(){return this._status}set status(t){this._status=t}get formName(){return this._formName}set formName(t){this.trackObjectPropertyChange("_formName",t)}get formUniqueName(){return this._formUniqueName}set formUniqueName(t){this.trackObjectPropertyChange("_formUniqueName",t)}get formType(){return this._formType}get tabCount(){return this.allTabs.length}get description(){return this._description}set description(t){this.trackObjectPropertyChange("_description",t)}get formactivationstate(){return this._formactivationstate}set formactivationstate(t){this.trackObjectPropertyChange("_formactivationstate",t)}get entityDisplayName(){return this._entityDisplayName}set entityDisplayName(t){this._entityDisplayName=t}get etag(){return this._etag}set etag(t){this._etag=t}indexOfTab(t){return this.getAllGrandChildren(C.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(C.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(C.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(C.controlDescriptions,r)}getControlDescriptionByForControl(t){if(!t)return null;for(let r of this.ControlDescriptions)if(r.forControl.guidString===t.guidString)return r;return null}cellHasCustomControlWithName(t,r){if(!t?.control||!r)return!1;let n=this.getControlDescriptionByForControl(t.control.UniqueId);return n?!!n.customControls.find(i=>i.name===r):!1}isDuplicateCell(t,r){return!!this.findFirst(i=>{if(!(i instanceof _r))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 _r&&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,_i.EditableGridControl)||h2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,_i.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,_i.CanvasAppControl)}findFormNodeById(t,r=this){return r===null?null:r.findFirst(n=>{if(n===this&&t===this.formId.ToString()||n.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,r=this){return r?r.findFirst(n=>{if(n.getNodeName()===C.formCell){let i=n;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let r=this.tabs,n=[],i=[];if(r){for(let o of r)if(!(o instanceof ca)){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,Tf.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===mt.Main?{HeaderDensity:kQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:LQ(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 Df,my,N2=k(()=>{"use strict";pt();ot();le();Dt();wo();Df=class extends Qt{constructor(t){super(C.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(C.formEveryOne)&&this.getChildren(C.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new my(this))}},my=class extends re{constructor(t){super(C.formEveryOne,t)}}});var If,_2=k(()=>{"use strict";le();Dt();If=class extends re{constructor(t,r){super(C.Handler,r),t.length>0&&this.setDefaultProperties(t)}setDefaultProperties(t){this.FunctionName=t[0],this.LibraryName=t[1],this.HandlerUniqueID=t[2],this.Enabled=t[3],this.Parameters=t[4],this.PassExecutionContext=t[5]}get HandlerUniqueID(){return this.getProperty(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Ms,hy=k(()=>{"use strict";le();ku();Ms=class extends ri{constructor(t,r){super(t,r)}get cells(){let t=this.getRows(),r=[];if(this.rows&&t.length){for(let n of this.rows)if(n.cells){let i=n.getChildren(C.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var $u,T2=k(()=>{"use strict";le();hy();$u=class extends Ms{_customFooter;constructor(t,r){super(C.formFooter,t),this._customFooter=r}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}isEmpty(){return!this.cells.find(t=>!!t.control)}}});var xu,D2=k(()=>{"use strict";le();hy();xu=class extends Ms{_customHeader;constructor(t,r){super(C.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.showTabNavigator,String(t))}async getControls(t){let r=[];if(this.rows){for(let n of this.rows)if(n.cells)for(let i of n.cells)i.control&&r.push(await i.control.toJSON(t))}return r}async toJSON(t){return{AvailableForPhone:this.availableforphone,Controls:await this.getControls(t),UniqueId:this.id&&this.id.guidString,PreviewId:this.id&&this.id.guidString}}}});var Tr,da=k(()=>{"use strict";pt();Yt();le();wo();Tr=class e extends Qt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(C.Titles);return t.length===0?[]:t[0].getChildren(C.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(C.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(C.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Fu,I2=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Fu||(Fu={}))});var Of,O2=k(()=>{"use strict";ot();le();da();I2();Of=class extends Tr{constructor(t){super(C.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(n=>n.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(n=>!n.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let r=this.getNavBarLinkItemById(t);return R.IsNullOrUndefined(r)?Fu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Fu.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var xe,$Q,P2,a0e,Us,gy=k(()=>{"use strict";pt();le();da();(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={}));$Q=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),P2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),a0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Us=class extends Tr{constructor(t,r){super(C.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=$Q.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var Bs,yy=k(()=>{"use strict";le();da();Bs=class extends Tr{constructor(t,r){super(C.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(C.formNavBarArea)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Pf,R2=k(()=>{"use strict";ot();le();da();Pf=class extends Tr{RelationshipNameUCIRuntime;constructor(t){super(C.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return 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 Rf,L2=k(()=>{"use strict";le();da();Rf=class extends Tr{constructor(t){super(C.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Lf,k2=k(()=>{"use strict";pt();le();gy();yy();da();Lf=class extends Tr{constructor(t,r){super(t,r)}getNavBarAreaByAreaName(t){let r=this.navBarAreas.AllNavBarAreaItems.filter(n=>n.AreaId===t);return r.length===0?null:r[0]}get navBarAreas(){return this.getFirstChild(C.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[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=>P2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Bs(C.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Us(C.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(C.formNavBar)}get id(){return new U(Yg,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(C.formNavBarAreas,r),this.addGrandChildAtIndex(C.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var $2={};Hr($2,{ControlType:()=>ln,DeserializationService:()=>wy,DeserializationServiceScope:()=>vy,DeserializedFormElementNode:()=>Dr});var by,Dr,vy,ln,wy,cy=k(()=>{"use strict";by=Ee(ra());pt();ot();Yt();gs();Qg();ta();w_();J_();fu();S2();Lu();Ef();Ru();oy();le();le();N2();Dt();_n();ay();_2();T2();sy();ly();D2();dy();fy();ku();Nf();O2();gy();yy();R2();L2();k2();Dr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},vy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(ln||(ln={}));wy=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,by.trackErrorTrace)(sr,{eventName:vy,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!==mt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=na.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 _f(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===mt.Main&&(this.insertHeaderFooterElementProperties(C.formHeader,d,d.header),this.insertHeaderFooterElementProperties(C.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===C.formHeader?new xu(r,!0):new $u(r,!0);Dr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Dr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Dr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Dr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Dr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new ua(o);for(let s=0;s<i.maxColumns;s++){let l=new _r(a);Dr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Dr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===C.formHeader?r.header=i:r.footer=i}}deSerializeFormXmlNode(t,r){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new Dr(`<${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,by.trackErrorTrace)(sr,{eventName:vy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Dr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===C.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Dr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case C.form:throw new Error("Form node shouldn't be created using this method");case C.formTab:return new $i(r);case C.formColumn:return new Co(r);case C.formHeader:return new xu(r,!1);case C.formFooter:return new $u(r,!1);case C.formSection:return new ri(C.formSection,r);case C.formRow:return new ua(r);case C.formCell:return new _r(r);case C.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=ln.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=ln.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=ln.Lookup)}return o===ln.Grid?new $s(r):o===ln.Lookup?new xs(r):new In(r);case C.formEvent:return new ks(r,q.EmptyString);case C.dependency:return this.populateDependencyTable(t),new Ls(r,q.EmptyString);case C.Handler:let a=[];return new If(a,r);case C.formNavigation:return new Lf(t.nodeName,r);case C.formNavBarArea:return new Us(t.nodeName,r);case C.formNavBarAreas:return new Bs(t.nodeName,r);case C.formNavBar:return new Of(r);case C.formNavBarByRelationshipItem:return new Pf(r);case C.formNavBarItem:return new Rf(r);case C.formDisplayConditions:return new Df(r);case C.library:return new Fs(r,q.EmptyString,q.EmptyString);case C.controlDescription:return new Kd(r);case C.customControl:return this.populateCustomControlConfigurationId(t),new of(r);default:return new Dr(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,Xn.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);at.CustomControlIdMap.upsert(l,o);break}}break}}}}});var x2={};Hr(x2,{SerializationService:()=>Cy,SerializationServiceScope:()=>xQ,SerializedFormElementNode:()=>qs});var xQ,qs,Cy,F2=k(()=>{"use strict";Yt();Dt();_n();py();xQ="SerializationService",qs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Cy=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=qs.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=qs.prototype.enumerateProperties.call(t),i=qs.prototype.enumerateChildren.call(t);if(!(t instanceof ca)){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 Ny=v(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.completeRecordAsStored=Vs.completeLabelsAsStored=void 0;var Ey=uo(),FQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",MQ=new Set(["tab","section","cell"]);function On(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Eo(e,t){return On(e).find(r=>r.tagName===t)}function U2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function Ay(e){let t=Eo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===FQ:!1}function Sy(e,t){var r,n;let i=((r=Eo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Eo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function UQ(e,t){if(Eo(e,"labels"))return;let r=On(e),n=On(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!U2(r,n.slice(1)))return;let o=On(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&Ay(e)&&Sy(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function BQ(e,t){let r=qQ(e.ownerDocument,t),n=On(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function qQ(e,t){let r=e.createElement("labels");for(let n of On(t))r.appendChild(B2(e,n));return r}function B2(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 M2(e,t){let r=Eo(e,"labels");return r?On(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function VQ(e,t,r){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return!1;let n=M2(e,r),i=M2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function GQ(e,t){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return;let r=Eo(e,"labels"),n=Eo(t,"labels");if(!r||!n)return;let i=On(r),o=On(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(MQ.has(e.tagName)){let a=UQ(e,t);a&&(BQ(e,a),n.changed=!0),VQ(e,t,r)&&(n.changed=!0);let s=GQ(e,t),l=Eo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=B2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=On(e),o=On(t);U2(i,o)&&i.forEach((a,s)=>q2(a,o[s],r,n))}function V2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ey.parseXmlRoot)(e,""),i=(0,Ey.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return q2(n,i,r,o),o.changed?(0,Ey.serializeNode)(n):e}Vs.completeLabelsAsStored=V2;function WQ(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=V2(n,i,r);return o===n?e:{...e,formxml:o}}Vs.completeRecordAsStored=WQ});var lL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var zQ=(fu(),Fr(Y_)),jQ=Q(),G2=dt(),V=wd(),HQ=Uh(),Ce=en(),Mi=["web","phone","tablet"],Mu={web:"2",phone:"0",tablet:"1"},K2=new Map([["2","web"],["0","phone"],["1","tablet"]]),KQ=["phone","web","tablet"];function $f(e){let t=new Set(e),r=KQ.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Mi.filter(n=>t.has(n))}}ue.pcfEntryLayout=$f;function lr(e){return Array.isArray(e)?e:[]}function st(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Uu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ty(e){return{n:`<${e}`,a:[],c:[]}}function J2(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function W2(e){let t=lr(e.c);return t.length===1&&J2(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function cn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Y2(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function Dy(e){try{let t=(0,zQ.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?Y2(String(t)):void 0}catch{return}}ue.nativeClassFor=Dy;var Iy=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}]]),Q2=new Set(["TwoOptions","Boolean"]),X2=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),JQ=new Map([...[...X2].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),YQ=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Z2(e){return YQ.test(e)&&e!=="__proto__"}function Oy(e){return e!==void 0&&(e==="Enum"||Iy.has(e)||Q2.has(e)||X2.has(e))}function eL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function Bu(e,t){let r=e!==void 0?Iy.get(e):void 0;if(r&&typeof t!="boolean"){let n=eL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=Bu;function QQ(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&Uu(r,a)?s=Bu(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Ty(s)]})}return i}function tL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Mi.filter(d=>Py(i).has(d)),l=$f(s),u=QQ(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Ty(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=tL;function Py(e){return new Set(Mi.filter(t=>e.availableOn[t]))}function kf(e){var t;let r=lr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||lr(r[0].a).length>0)return;let n=lr(r[0].c);return n.every(i=>st(i)&&!J2(i))?n:void 0}function fa(e){let t=lr(e?.c);if(t.length===0||!t.every(p=>st(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=lr(p.a),g=h.length===2?K2.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=$f(o);if(!cn(a.named,o)||i==="")return;let s=kf(n[0]);if(!s||!n.every(p=>cn(kf(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",Mu[h]]],b=kf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&lr(b[0].a).length===0?W2(b[0]):void 0;if(!u||!cn(lr(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=lr(p.a),g=W2(p),b=h.map(w=>w[0]);if(g===void 0||!Z2(p.n)||Uu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||cn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(cn(b,["static"])||cn(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===Mi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=fa;function rL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===Bu(r,e))}function nL(e){let t=e.formFactors;return t===void 0?[...Mi]:Array.isArray(t)?Mi.filter(r=>t.includes(r)):[]}function _y(e,t){var r,n,i;if(e.name!==t.binding.name||!cn(nL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Mi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>Uu(a,l)&&rL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=_y;function ht(e){return st(e)&&e.customControl!==void 0}ue.hasCustomControl=ht;function Fi(e,t){var r;return t?lr((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 Ry(e,t){let r=Fi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?fa(r[0]):void 0}ue.storedBindingOf=Ry;function Ly(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Ly;function XQ(e){if(!Ly(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!st(n)||!n.fieldName||!xi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Ry(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=XQ;function xi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var un=(e,t)=>({kind:"refused",rule:e,message:t});function ZQ(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!xi(e)}function z2(e,t,r){var n,i;let o=fa(r);if(!o)return un("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 un("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 un("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=st(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!cn(l,Object.keys(s).sort()))return un("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=>!rL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>Bu(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return un("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=nL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Mi],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=>!Oy(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return un("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)&&!ZQ(o.nativeClass)?un("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 eX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>ht(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Fi(e.bag,t)}:void 0}function iL(e,t){let r=new Map,n=tX(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:iX(u),uid:(0,V.controlUniqueId)(c),bound:ht(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;st(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(!st(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 O=m.findIndex(D);return O<0?void 0:m.splice(O,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(O=>O.bound&&O.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let O=D.cell?l(c,D.cell):void 0;return!O||!l(d,D.cell)||!m.includes(O)?!0:(m.splice(m.indexOf(O),1),f.includes(O)&&D.uid!==O.uid&&j2(D.control)&&r.set(D.control,H2(O.uid)),!1)}),b=[],w=(D,O)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!O||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)&&j2(D.control)),P=f.filter(D=>m.includes(D));if(S.length===0||P.length===0&&b.length===0)continue;let L=[...P,...b],I=P.length===1&&S.length===1&&m.length===1?H2(P[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function tX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=st(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||ht(a)||o>1)&&n.add(i)}return n}function j2(e){return ht(e)||e.genPage===void 0&&xi((0,V.effectiveClassId)(e))}function rX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!st(l)||ht(l)||l.genPage!==void 0||!xi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Fi(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 nX="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 H2(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 iX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function qu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Fi(e.bag,o),s=r?iL(e,r).get(t):void 0;if(s!==void 0)return un("pcf-binding-unique-id",s);let l=r?eX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?fa(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return un("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&&cn(c[0],a[0]))return z2(t,i,a[0]);let f=a.length===1?fa(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&_y(i,d)&&_y(i,f)?{kind:"unchanged"}:un("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 un("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=z2(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:un("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=qu;function oL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function oX(e){let t=n=>ht(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,G2.newId)()),n.id||(n.id=(0,G2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=oX;function aX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!ht(o)||!st(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=qu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):oL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=aX;function sX(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(!ht(p)||!st(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Fi(u,h).length>0&&c.set(p,{plan:qu(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=st(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(!ht(g))continue;let b=(0,V.controlUniqueId)(g),w=Fi(t.bag,b),E=Fi(u,b);if(w.length!==1||E.length!==1||!cn(w[0],E[0])||!fa(E[0]))continue;let S=p.get(b);if(S&&!ht(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let P=(o=(i=fa(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=P.replace(/^\{|\}$/g,"").toUpperCase(),lX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=lr(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(!ht(m)||!st(m.customControl))continue;xi(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 jQ.ValidationError("form",e.id,[(0,Ce.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&uX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?Dy(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let E=((l=(s=lr((a=m.bag)===null||a===void 0?void 0:a.a).find(P=>P[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=E.startsWith("{")?E:`{${p}}`;d.node.c.push(tL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=sX;function lX(e,t){st(e.bag)&&(e.bag.a=lr(e.bag.a).filter(r=>r[0]!==t))}function uX(e,t){var r,n;let i=lr(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=kf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Ty(Bu(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=K2.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=$f(e.factors),p=m.defaults.map(g=>{let b=a.find(E=>c(E)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Mu[g]]],w}),h=m.named.map(g=>{let b=s.find(E=>c(E)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Mu[g]]],w});e.description.c=[...p,...h]}function cX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>ht(t.control))}ue.mayCommitPcfState=cX;function dX(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(!ht(a))continue;let s=Ry(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=lr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!xi(a.classId)||a.type!==l||u!==void 0&&!xi(u[1])||!cn(a.customControl,s.binding))&&(xi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!xi(u[1])&&(u[1]=Y2(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=dX;var fX=new Set(["name","parameters","formFactors"]);function pX(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;ht(s)&&hX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&gX(e,t,n),n}ue.pcfBindingIssues=pX;function mX(e,t,r){let n=r.length;if(!st(e))return r.push((0,Ce.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))fX.has(i)||r.push((0,Ce.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ce.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!st(e.parameters))r.push((0,Ce.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,Ce.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"&&Mi.includes(a))&&new Set(i).size===i.length||r.push((0,Ce.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function hX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=mX(t.customControl,l,i);t.fieldName||i.push((0,Ce.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ce.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Ly(e)||i.push((0,Ce.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,Ce.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,Ce.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,Ce.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=qu(e,t,o,a);f.kind==="refused"&&i.push((0,Ce.issue)(l,f.rule,f.message))}function gX(e,t,r){var n;let i=new Map,o=iL(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=st(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),st(l.control)&&!ht(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ce.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!ht(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||ht(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ce.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):cn(Fi(t.bag,u),Fi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ce.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ce.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 rX(e,t))s.has(l)||r.push((0,Ce.issue)(l,"pcf-binding-unique-id",nX))}var yX=new Set(["Form.Card"]),bX="MscrmControls.ModelForm.ModelFormControl";function aL(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=>!Z2(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===bX||n.some(s=>s.defaultType!==void 0&&yX.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"&&!Oy(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 vX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function sL(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?Iy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:eL(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&&Q2.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?JQ.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 wX(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(!ht(d)||!d.fieldName)continue;let f=d.customControl;if(!st(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=qu(e,d,r,!0);if(p.kind==="edit"){oL(p)&&AX(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,Ce.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=aL(h.value,f.name);if(b){l.push((0,Ce.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),E=g.kind==="found"?g.value:void 0,S=E?(a=(0,HQ.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&Dy(E)!==void 0&&vX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&l.push((0,Ce.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,Ce.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=st(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Re=L.get(x);if(!Re){l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let qt=sL(Re,K);qt&&l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${qt}`))}for(let x of L.values())x.required&&!Uu(I,x.name)&&!x.defaultValue&&l.push((0,Ce.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Py(h.value),O=Array.isArray(f.formFactors)?f.formFactors:void 0;(O?O.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ce.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=wX;function CX(e,t){return t===void 0||!Oy(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function EX(e,t,r){var n,i;let o=aL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!Uu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function AX(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,Ce.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=EX(u.value,t.name,e.stored);if(c){l.push((0,Ce.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];CX(d.get(h),g)||l.push((0,Ce.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=sL(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ce.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Py(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ce.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var SL=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.classIdForAttributeType=Or.QUICK_VIEW_CLASS_ID=Or.NOTES_CLASS_ID=Or.SUBGRID_CLASS_ID=Or.formRegistration=Or.FormAdapter=void 0;var Ui=(pt(),Fr(d_)),uL=(ot(),Fr(f_)),SX=(Dt(),Fr(m_)),gt=(le(),Fr(p_)),tt=(ta(),Fr(h_)),NX=(cy(),Fr($2)),_X=(F2(),Fr(x2)),yt=so(),cL=Jr(),Ir=en(),TX=vg(),Ws=dt(),DX=Ny(),Xt=wd(),ni=lL(),Gs=Q(),Uy=se(),ky=lo(),gL=Ho(),IX={[gt.FormType.Main]:"Main",[gt.FormType.QuickCreate]:"QuickCreate",[gt.FormType.QuickViewForm]:"QuickView",[gt.FormType.Card]:"Card"},xf={Main:gt.FormType.Main,QuickCreate:gt.FormType.QuickCreate,QuickView:gt.FormType.QuickViewForm,Card:gt.FormType.Card},OX=new Map(Object.entries(tt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function By(e){var t;return e&&(t=OX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Vu(e){return e.getAllProperties().map(t=>[t.key,t.value])}function pa(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function yL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function qy(e,t){var r,n;let i=yL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>pa(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=pa(a).get("description"))!==null&&n!==void 0?n:""}function PX(e){let t=yL(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 bL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function $y(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Gu(e){return String(e??"").replace(/[{}]/g,"")}function xy(e){return`{${Gu(e)}}`}function Fy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Mf(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,yt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Vu(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,yt.rawFromNode)(u)})}),{modeled:s,bag:{a:Vu(e),c:o,w:{n:a.getNodeName(),a:Vu(a),c:l}}}}function vL(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,yt.rawFromNode)(o)})}),{modeled:n,bag:{a:Vu(e),c:i}}}function dL(e,t){let{modeled:r,bag:n}=Mf(e,"tabs","tab");return{tabs:r.map(i=>RX(i,t)),bag:n}}function RX(e,t){var r,n;let i=pa(e),{modeled:o,bag:a}=Mf(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=>LX(s,t)),bag:a}}function LX(e,t){let r=pa(e),{modeled:n,bag:i}=Mf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>kX(o,t)),bag:i}}function kX(e,t){var r,n,i;let o=pa(e),{modeled:a,bag:s}=Mf(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:bL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>$X(l,t)),bag:s}}function $X(e,t){let{modeled:r,bag:n}=vL(e,"cell",!1);return{cells:r.map(i=>xX(i,t)),bag:n}}function xX(e,t){var r;let n=pa(e),{modeled:i,bag:o}=vL(e,"control",!0),a=qy(e,t),s=n.get("showlabel")==="true",l=i[0]?FX(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:Fy(n.get("colspan"),1),rowspan:Fy(n.get("rowspan"),1),control:l,bag:o}}function FX(e,t,r){var n,i;let o=pa(e),a=Gu((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:By(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:PX(e),bag:{a:Vu(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,yt.rawFromNode)(l)}))}}}function No(e){return e.a.length===0&&e.c.length===0&&!e.w}function wL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ma(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=No(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=wL(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,yt.mergeAttrs)(e.a,o)}var Ao=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),So=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),fL=(e,t,r=1)=>({key:e,matches:n=>Fy(n,r)===t,render:()=>String(t),absentDefault:String(r)});function Vy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function My(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Uy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function MX(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 UX(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 Gy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||No(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:Vy(t,r)},...a]}}if(MX(e.c[n].node,r)===t)return e;let i=UX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function BX(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 qX(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function VX(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function GX(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||No(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:My(t)}]}}if(qX(BX(e.c[r].node),t))return e;let n=My(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Uf(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,yt.spliceChildren)(e.w.c,r)};return(0,yt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,yt.spliceChildren)(e.c,[...i,o])}function WX(e,t){let r=e.tabs.map(n=>zX(n,t));return{n:"form",a:ma(e.bag,[]),c:e.tabs.length===0&&No(e.bag)?[]:Uf(e.bag,"tabs",r,()=>[])}}function CL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Vy(t,r)]:[]}function zX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("expanded",e.expanded),So("visible",e.visible,!0)],n=e.columns.map(o=>jX(o,t)),i=Gy(e.bag,e.label,t);return{n:"tab",a:ma(i,r),c:Uf(i,"columns",n,()=>CL(i,e.label,t))}}function jX(e,t){let r=e.width!==void 0?[Ao("width",e.width)]:[],n=e.sections.map(i=>HX(i,t));return{n:"column",a:ma(e.bag,r),c:Uf(e.bag,"sections",n,()=>[])}}function HX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("showlabel",e.showLabel),So("visible",e.visible,!0),{key:"columns",matches:o=>bL(o)===e.columns,render:()=>$y(e.columns),absentDefault:$y(1)}],n=e.rows.map(o=>KX(o,t)),i=Gy(e.bag,e.label,t);return{n:"section",a:ma(i,r),c:Uf(i,"rows",n,()=>CL(i,e.label,t))}}function KX(e,t){let r=e.cells.map(n=>JX(n,t));return{n:"row",a:ma(e.bag,[]),c:No(e.bag)?r:(0,yt.assembleChildren)(e.bag,r)}}function JX(e,t){let r=e.control?e.control.showLabel:wL(e.bag,"showlabel")==="true",n=[Ao("id",e.id),So("showlabel",r),So("visible",e.visible,!0),fL("colspan",e.colspan),fL("rowspan",e.rowspan)],i=e.control?[YX(e.control)]:[],o;if(No(e.bag))o=[...e.control&&e.control.label?[Vy(e.control.label,t)]:[],...i];else{let a=e.control?Gy(e.bag,e.control.label,t):e.bag;o=(0,yt.assembleChildren)(a,i)}return{n:"cell",a:ma(e.bag,n),c:o}}function YX(e){let t=[Ao("id",e.id),{key:"classid",matches:i=>Gu(i)===e.classId,render:()=>xy(e.classId||String(tt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Ao("datafieldname",e.fieldName)),t.push(So("disabled",e.isReadOnly)),t.push(So("isrequired",e.isRequired));let r=e.fieldName===null?VX(e.bag,"datafieldname"):e.bag,n;return No(r)?n=Object.keys(e.parameters).length>0?[My(e.parameters)]:[]:n=(0,yt.assembleChildren)(GX(r,e.parameters),[]),{n:"control",a:ma(r,t),c:n}}var QX={make:(e,t)=>new SX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function pL(e,t,r,n){(0,ky.installDomShim)();let i=ZX(e,r);(0,Xt.reconcileEmbedDescriptions)(i,n),(0,ni.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,yt.rebuildRaw)(WX(i,t),QX,null);return new _X.SerializationService(t).serializeFormXmlNode(o)}function XX(e){return JSON.parse(JSON.stringify(e))}function ZX(e,t){let r=XX(e);r.bag||(r.bag=(0,yt.emptyBag)()),r.tabs||(r.tabs=[]),sZ(r.bag),t&&eZ(r,t);for(let n of r.tabs)tZ(n);return r}function eZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Wy(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=AL(s.attributeType)))})}function mL(e){let t=[];return Wy(e,r=>t.push(r)),t}function Wy(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 tZ(e){e.id||(e.id=Ui.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)rZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function rZ(e){e.sections||(e.sections=[]);for(let t of e.sections)nZ(t);e.bag||(e.bag=(0,yt.emptyBag)()),e.width===void 0&&No(e.bag)&&(e.width="100%")}function nZ(e){e.id||(e.id=Ui.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)iZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function iZ(e){e.cells||(e.cells=[]);for(let t of e.cells)oZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function oZ(e){(0,Xt.hasGenPage)(e.control)&&(0,Xt.applyEmbedCellDefaults)(e),e.id||(e.id=Ui.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&&aZ(e.control),e.bag||(e.bag=(0,yt.emptyBag)())}function aZ(e){var t;(0,Xt.hasGenPage)(e)&&(0,Xt.applyEmbedControlDefaults)(e),e.id||(e.id=Ui.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(tt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":By(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,Uy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,yt.emptyBag)())}function sZ(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"&&!hL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",xy(Ui.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!hL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",xy(Ui.Guid.NewGuid())])}}var Ff=class{constructor(t=gL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=dL(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=IX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,Xt.projectGenPageEmbeds)(l),(0,ni.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:pL(t,this.lcid),formid:t.id||(0,Ws.newId)(),objecttypecode:t.entityLogicalName,type:xf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ws.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,ky.installDomShim)();let f=uL.ScriptUtilities.ParseXml(c),m=lZ(f),p=this.deserializeDocument(d,f);return uZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,Xt.genPageEmbedIssues)(t);if(i.length>0)throw new Gs.ValidationError("form",t.id,i);let o=(0,ni.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Gs.ValidationError("form",t.id,o);let a=(0,ni.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Gs.attachCause)(new Gs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Gs.ValidationError("form",t.id,a.issues);return{formxml:pL(t,this.lcid,n,r),name:t.name,type:xf[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 Wy(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,ni.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,Xt.genPageEmbedIssues)(t),...(0,ni.pcfBindingIssues)(t)];if(p.length>0)throw new Gs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:vZ(this.lcid),g=h!==void 0?h:t.tabs.map(E=>cZ(E,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ws.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:xf[(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:gt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(gt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let E=mL(t);mL(w).forEach((S,P)=>{E[P]&&E[P].label===void 0&&delete S.label,E[P]&&E[P].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(E[P].genPage))),E[P]&&E[P].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(E[P].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,Ws.assignMissingIds)(t)}completeAsStored(t,r){return(0,DX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ni.mintPcfIdentity)((0,Xt.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,Xt.mayCommitEmbedState)(t)||(0,ni.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ws.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:xf[(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:gt.FormPresentation.AirForm,formactivationstate:gt.FormActivationState.Active}),{bag:d}=dL(c,this.lcid),f=(0,ni.commitPcfState)((0,Xt.commitEmbedState)(t,(l=(0,Xt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),By);return{artifact:f,baseline:f}}validate(t){return DZ(t)}deserialize(t){return(0,ky.installDomShim)(),this.deserializeDocument(t,uL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new NX.DeserializationService(this.lcid).deSerializeFormXml(r,new Ui.Guid(t.formid),t.objecttypecode,gt.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===gt.FormActivationState.InActive?"Inactive":"Active"}};Or.FormAdapter=Ff;var EL=["header","footer","DisplayConditions"];function lZ(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&&EL.includes(i.nodeName)&&n.add(i.nodeName);return n}function uZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=EL.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 Pn(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function zy(e,t){return e?`<labels><label description="${Pn(e)}" languagecode="${t}" /></labels>`:""}function jy(e){return e&&e.length>0?Gu(e):(0,Ws.newId)()}function cZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[bZ()]).map(l=>dZ(l,t)).join("");return`<tab id="{${Pn(jy(e.id))}}" name="${Pn((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}">${zy(e.label,t)}<columns>${s}</columns></tab>`}function dZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>fZ(o,t)).join("");return`<column width="${Pn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function fZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>pZ(l,t)).join("");return`<section id="{${Pn(jy(e.id))}}" name="${Pn((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="${$y((a=e.columns)!==null&&a!==void 0?a:1)}">${zy(e.label,t)}<rows>${s}</rows></section>`}function pZ(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>mZ(n,t)).join("")}</row>`}function mZ(e,t){var r,n,i,o,a;let s=hZ(e),l=s.control,u=l?zy((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?gZ(l):"";return`<cell id="{${Pn(jy(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 hZ(e){if(!(0,Xt.hasGenPage)(e.control))return e;let t={...e.control};(0,Xt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,Xt.applyEmbedCellDefaults)(r),r}function gZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Pn(e.fieldName)}"`:"",o=yZ(e.parameters),a=e.classId?Gu(e.classId):String(tt.ControlClassId.TextboxControl);return`<control id="${Pn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Pn(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 yZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Uy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Pn(e[n])}</${n}>`).join("")}</parameters>`)}function bZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function vZ(e){return`<tab id="{${Ui.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Ui.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 wZ(e=gL.DEFAULT_LCID){return{adapter:new Ff(e),api:TX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,cL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,cL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Or.formRegistration=wZ;var CZ=new Set(["id","name","label","expanded","visible","columns","bag"]),EZ=new Set(["id","width","sections","bag"]),AZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),SZ=new Set(["id","cells","bag"]),NZ=new Set(["id","visible","colspan","rowspan","control","bag"]),_Z=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),TZ={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 DZ(e){let t=[];return(0,Ir.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Ir.rejectUnknownKeys)(n,CZ,o,"tab",t),(0,Ir.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Ir.rejectUnknownKeys)(s,EZ,u,"column",t),(0,Ir.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Ir.rejectUnknownKeys)(d,AZ,m,"section",t),(0,Ir.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Ir.rejectUnknownKeys)(h,SZ,b,"row",t),(0,Ir.childObjects)(h,"cells",b,"cell",t).forEach(({node:E,index:S})=>{let P=`${b}/cells/${S}`;(0,Ir.rejectUnknownKeys)(E,NZ,P,"cell",t,TZ);let L=E.control;L!=null&&!(0,Ir.isJsonObject)(L)?t.push((0,Ir.issue)(`${P}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Ir.isJsonObject)(L)&&(0,Ir.rejectUnknownKeys)(L,_Z,`${P}/control`,"control",t)})})})})}),t.push(...(0,Xt.genPageEmbedIssues)(e)),t.push(...(0,ni.pcfBindingIssues)(e)),t}Or.SUBGRID_CLASS_ID=tt.ControlClassId.SubgridControl;Or.NOTES_CLASS_ID=tt.ControlClassId.TimelineControl;Or.QUICK_VIEW_CLASS_ID=tt.ControlClassId.QuickViewControl;var IZ={Lookup:String(tt.ControlClassId.LookupControl),Customer:String(tt.ControlClassId.LookupControl),Owner:String(tt.ControlClassId.LookupControl),PartyList:String(tt.ControlClassId.PartyListControl),Boolean:String(tt.ControlClassId.BooleanControl),DateTime:String(tt.ControlClassId.DateTimeControl),Decimal:String(tt.ControlClassId.DecimalControl),Double:String(tt.ControlClassId.FloatingNumberControl),Money:String(tt.ControlClassId.CurrencyControl),Integer:String(tt.ControlClassId.IntegerControl),BigInt:String(tt.ControlClassId.IntegerControl),Memo:String(tt.ControlClassId.TextAreaControl),String:String(tt.ControlClassId.TextboxControl)},OZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function AL(e){return e==="Picklist"||e==="State"||e==="Status"?OZ:e&&IZ[e]||String(tt.ControlClassId.TextboxControl)}Or.classIdForAttributeType=AL;function hL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Hy=v(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.viewApi=zs.findDefaultViews=void 0;var DL=Lt(),ur=ye(),Rn=se(),PZ=es(),NL="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",RZ="savedqueryid,name,returnedtypecode,querytype,isdefault",LZ=60*1e3;function Bf(e){return(e.localName||e.nodeName).toLowerCase()}function Wu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function kZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new PZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Bf(n)==="fetch"?n:void 0}function $Z(e){for(let t=e.parentNode;t;t=t.parentNode)if(Bf(t)==="link-entity")return!0;return!1}function _L(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=kZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Bf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Bf(u)==="link-entity").every(u=>{var c;return((c=Wu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!$Z(l)&&Wu(l,"entityname")===void 0&&((n=Wu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Wu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Wu(l,"value")===String(t)}function xZ(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 FZ(e){var t,r;let n=e.filter(a=>_L(a,0)),i=e.filter(a=>_L(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:"")))<=LZ&&xZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function MZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Rn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Rn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,DL.collectPages)(e,a,`findDefaultViews('${t}')`),l=FZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}zs.findDefaultViews=MZ;async function UZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Rn.odataPathLiteral)(t)}')${(0,Rn.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 TL(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await UZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}zs.viewApi={async get(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]);return{raw:(0,ur.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]),i=(0,ur.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Rn.odataQuery)([["$select",RZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Rn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,DL.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,ur.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await TL(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,ur.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,ur.ensureSuccess)(await(0,ur.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,ur.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,ur.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Rn.normalizeGuid)(t,"id"),a=(0,ur.echoWrite)("savedqueryid",{"If-Match":(0,ur.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await TL(e,i.layoutxml,i.returnedtypecode),u=(0,ur.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,ur.readEtag)(u)}},delete(e,t){return(0,ur.deleteRecord)(e,"savedqueries",t)}}});var WL=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.viewRegistration=js.ViewAdapter=void 0;var $L=Q(),Wr=en(),Ky=so(),ha=uo(),IL=Jr(),BZ=Hy(),Jy=lo(),qZ=dt(),xL=100,Vf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Jy.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,ha.parseXmlRoot)(c,"<fetch/>"),m=(0,ha.parseXmlRoot)(d,"<grid/>"),p=ML(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:GZ(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:FL(m,f),filters:BL(f),sort:UL(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,ha.projectElementBag)(f):void 0,layoutBag:d?(0,ha.projectElementBag)(m):void 0}}fromArtifact(t){(0,Jy.installDomShim)();let{fetchxml:r,layoutxml:n}=OL(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,Jy.installDomShim)();let{fetchxml:s,layoutxml:l}=OL(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,qZ.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,Wr.childObjects)(n,"columns","","column",r),(0,Wr.childObjects)(n,"sort","","sort",r),(0,Wr.childObjects)(n,"linkEntities","","linkEntity",r),VZ(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Wr.isJsonObject)(i)?Yy(i,"/filters",r):r.push((0,Wr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};js.ViewAdapter=Vf;function VZ(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Wr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,Wr.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,Wr.isJsonObject)(i)?Yy(i,`/linkEntities/${n}/filters`,t):t.push((0,Wr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Yy(e,t,r){(0,Wr.childObjects)(e,"conditions",t,"condition",r),(0,Wr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Yy(i,`${t}/groups/${o}`,r))}function GZ(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function FL(e,t){var r;let n=Gf(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)?xL: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 Gf(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 ML(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Ft(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=Ft(n,"filter").find(c=>!Wf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Qy(u)}:{}})}return r}function UL(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 BL(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Ft(t,"filter").filter(i=>!Wf(i)).map(Qy);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Wf(e){if(e.getAttribute("isquickfindfields")==="1"||qL(e))return!0;if(Ft(e,"filter").length>0)return!1;let t=Ft(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Ft(r,"value").length>0||zZ(r))}function qL(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"?qL(n):n.tagName!=="condition"))return!0}return!1}var WZ=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function zZ(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&&!WZ.has(i))return!0}return!1}function Qy(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(Qy(l))}return{type:n,conditions:i,groups:o}}function Ft(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 Xy=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function jZ(e,t){let r=Gf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Xy(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function HZ(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(Xy(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new $L.ValidationError("view",e.id,a.map(s=>(0,Wr.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 OL(e){var t,r;let n=KZ(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(!PL(e.fetchBag)||!PL(e.layoutBag))return{fetchxml:see({...e,columns:n,sort:i,filters:o}),layoutxml:lee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=RL(e.fetchBag,"fetch",a),l=RL(e.layoutBag,"grid",a),u=FL(l,s),c=!qf(n,u),d=!qf(i,UL(s)),f=!qf(o,BL(s)),m=e.linkEntities,p=m!==void 0&&!qf(m,ML(s)),h=p?jZ(s,u):void 0;return p&&iee(a,s,m),p&&(aee(e,s,n,h),HZ(e,s,n,h)),c?(LL(a,s,n,u),ZZ(a,l,n)):p&&LL(a,s,n,u),d&&ree(a,s,i),f&&nee(a,s,o),{fetchxml:(0,ha.serializeNode)(s),layoutxml:(0,ha.serializeNode)(l)}}function KZ(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:xL,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function PL(e){return!!e&&(e.c.length>0||e.a.length>0)}function RL(e,t,r){let n={n:t,a:(0,Ky.mergeAttrs)(e.a,[]),c:(0,Ky.spliceChildren)(e.c,[])};return(0,Ky.rebuildRaw)(n,(0,ha.domEngine)(r),null)}function LL(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=Gf(t);for(let p of n)u.has(l(p))||(YZ(s,p),p.relatedEntity&&c.has(p.name)&&JZ((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Gf(t),m=new Set(Ft(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||!GL(s,p.relatedEntity)))continue;let g=QZ(e,s,p.relatedEntity),b=e.createElement("attribute");VL(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),XZ(s,h),m.add(p.name)}}function VL(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 JZ(e,t){if(e){for(let r of Ft(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function YZ(e,t){if(t.relatedEntity){for(let r of Ft(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Ft(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Ft(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function GL(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Ft(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 QZ(e,t,r){let n=GL(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function XZ(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 ZZ(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=eee(n);if(tee(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 eee(e){return Ft(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function tee(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 ree(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 Ft(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 nee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Ft(n,"filter"))Wf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(zu(e,r))}}function qf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function iee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Ft(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,P)=>P!==g&&!s[P]&&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){kL(e,g,p);return}let b=e.createElement("link-entity");kL(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var oee=new Set(["inner","outer"]);function aee(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(Xy(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 $L.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,Wr.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 kL(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):oee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Ft(t,"filter").find(o=>!Wf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?zu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function see(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(zu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){VL(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(zu(r,e.filters)),new XMLSerializer().serializeToString(r)}function zu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(zu(e,n));return r}function lee(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 uee(){return{adapter:new Vf,api:BZ.viewApi,publish:(e,t,r)=>(0,IL.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,IL.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}js.viewRegistration=uee});function zf(e,t){return e==="SetFieldValue"&&t!==void 0&&cee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var cee,Zy=k(()=>{"use strict";cee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function zL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function eb(e){return e==="AllForms"||zL(e)?1:2}function tb(e){return zL(e)?e:null}function jL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Hs.WorkflowCategory.BusinessRule,type:Hs.WorkflowTypeCode.Definition,mode:1,scope:Hs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:eb(e.scope),processtriggerformid:tb(e.scope)}}var Hs,HL=k(()=>{"use strict";Hs=Ee(Yi());});function KL(e,t=0){return(Mt[e[t+0]]+Mt[e[t+1]]+Mt[e[t+2]]+Mt[e[t+3]]+"-"+Mt[e[t+4]]+Mt[e[t+5]]+"-"+Mt[e[t+6]]+Mt[e[t+7]]+"-"+Mt[e[t+8]]+Mt[e[t+9]]+"-"+Mt[e[t+10]]+Mt[e[t+11]]+Mt[e[t+12]]+Mt[e[t+13]]+Mt[e[t+14]]+Mt[e[t+15]]).toLowerCase()}var Mt,JL=k(()=>{Mt=[];for(let e=0;e<256;++e)Mt.push((e+256).toString(16).slice(1))});function rb(){return jf>Hf.length-16&&((0,YL.randomFillSync)(Hf),jf=0),Hf.slice(jf,jf+=16)}var YL,Hf,jf,QL=k(()=>{YL=require("crypto"),Hf=new Uint8Array(256),jf=Hf.length});var XL,nb,ZL=k(()=>{XL=require("crypto"),nb={randomUUID:XL.randomUUID}});function dee(e,t,r){if(nb.randomUUID&&!t&&!e)return nb.randomUUID();e=e||{};let n=e.random??e.rng?.()??rb();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 KL(n)}var cr,ek=k(()=>{ZL();QL();JL();cr=dee});var ib=k(()=>{ek()});var tk=k(()=>{"use strict";});function rk(e){return e!=null&&fee.has(e)}function Kf(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 fee,ob=k(()=>{"use strict";fee=new Set(["Picklist","State","Status"])});var Jf=v(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.WorkflowConditionOperator=dn.WorkflowAttributeType=dn.SystemStep=dn.FieldRequiredLevelTypes=dn.AttributeDateTimeBehavior=void 0;dn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};dn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};dn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};dn.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"};dn.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 Yf(e){return e!=null&&ik.includes(e)}function ab(e){return e===oe.WorkflowAttributeType.Integer}function sb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:pee.includes(t)?ik.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 ok(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=ju[e.operator]??oe.WorkflowConditionOperator.Equal;return sb(t,r)}function ak(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||!nk.test(o)||!nk.test(a)||o.length>1&&o.startsWith("0")||o.length>mee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,ju,ik,pee,nk,mee,lb=k(()=>{"use strict";oe=Ee(Jf());ju={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},ik=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],pee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];nk=/^\d*$/,mee=28});var sk=k(()=>{"use strict";});function Ln(e){return!hee.has(e)}function ub(e){return e==="Equals"||e==="DoesNotEqual"}function Qf(e){return uk.has(e)?gee:Cee.has(e)?yee:ck.has(e)?bee:Aee.has(e)?wee:vee}function dk(e){return Qf(e)[0]}function fk(e,t){return Qf(t).includes(e)}function lk(e){return uk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":ck.has(e)?"date":Eee.has(e)?"boolean":"other"}function Xf(e,t){let r=lk(e),n=lk(t);return r==="other"||n==="other"?e===t:r===n}var hee,gee,yee,bee,vee,wee,uk,Cee,ck,Eee,Aee,Zf=k(()=>{"use strict";sk();hee=new Set(["ContainsData","DoesNotContainData"]);gee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],yee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],bee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],vee=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],wee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],uk=new Set(["String","Memo","EntityName"]),Cee=new Set(["Integer","BigInt","Money","Decimal","Double"]),ck=new Set(["DateTime"]),Eee=new Set(["Boolean"]),Aee=new Set(["Lookup","Owner","Customer"])});function gk(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 Ak(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function _ee(e){return{__class:Ek,parameterName:"primaryEntity",entityName:e}}function pk(e){return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:yk,parameters:[e]}}function mk(e,t,r=Fe.WorkflowAttributeType.String){return{__class:vk,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:_ee(t),attributeName:e}}function Tee(e,t=Fe.WorkflowAttributeType.String){return{__class:wk,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function Dee(e){return{__class:Ck,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function Sk(e,t){let r=See[e.operator],n=pk(mk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=Dee(e.right.value??"0"):e.right.kind==="field"?i=mk(e.right.field??"",t,e.right.workflowType):i=Tee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=pk(i);return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:bk,parameters:[r,n,o]}}function Nk(e){return typeof e=="object"&&e.__class===db}function Iee(e){return typeof e=="object"&&e.__class===Ck}function ep(e){return Nk(e)&&e.method===yk&&e.parameters.length>0?ep(e.parameters[0]):e}function hk(e){if(typeof e!="object"||e.__class!==vk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Ek)return null;let r=e.attributeName;return r?{field:r,workflowType:Ak(e.type)}:null}function _k(e){if(!e)return null;let t=ep(e);if(!Nk(t)||t.method!==bk||t.parameters.length!==3)return null;let r=t.parameters[0],n=Nee[String(r)];if(!n)return null;let i=hk(ep(t.parameters[1]));if(!i)return null;let o=ep(t.parameters[2]);if(Iee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=hk(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===wk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:Ak(o.type)}}}return null}function pb(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=fb&&r<=Ks}function ga(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&&!pb(t)?"invalidDayCount":null}function Js(e){return ga(e)===null}var Fe,yk,bk,cb,vk,wk,db,Ck,Ek,See,Nee,fb,Ks,Hu=k(()=>{"use strict";Fe=Ee(Jf());Zf();yk="0",bk="3",cb="0",vk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",wk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",db="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Ck="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Ek="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";See={"+":0,"-":1,"*":2,"/":3},Nee={0:"+",1:"-",2:"*",3:"/"};fb=0,Ks=2147483647});function Pee(e){return e.startsWith("__")&&!Oee.has(e)}function Ree(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Pee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function Bk(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function ba(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function tp(e){return Bk(e)||ba(e)}function Lee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ku(){return{list:[]}}function mb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:cr(),languageCode:r,description:t}]}}function gb(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function op(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:gb(t),attributeName:e}}function ya(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function xee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?Gk:Vk:qk}function Wk(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function Fee(e,t){let r=Wk(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${Dk}_${Tk}`,entityName:Tk,relatedAttributeName:Dk},attributeName:$ee}:op(kee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:vb,parameters:[xee(e),n]}}function zk(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==vb)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===Vk?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===Gk?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===qk?{bpfField:"ProcessName"}:null}function rp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===vb){let r=(t.parameters??[])[0];if(typeof r=="string"&&Mee.has(r.replace(/^"+|"+$/g,"")))return!0}return ba(e)?rp(e.operand):Bk(e)?rp(e.left)||(e.right??[]).some(rp):!1}function jk(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 Uee(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 Ik(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return jk(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 Bee(e){let t=bb[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(ba(e))return r&&Ok(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:Ok(e.left,r,n[0])}function Ok(e,t,r){return zk(e)||jk(e)?t||Ik(r):!1}function yb(e){if(!e||!tp(e))return!1;let t=e.conditionOperatoroperator;if(!ba(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&yb(e.left)&&r.every(yb)}return Bee(e)}function Pk(e){return!e||Uee(e)?!1:rp(e)||!yb(e)}function Hk(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??z.WorkflowAttributeType.Lookup,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:ya(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Vee(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Gee(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Vee(t)}function Wee(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function jee(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function ete(e){let t=Zee.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=Xee.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Qee.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function tte(e){let t=ete(e.trim());return t!==void 0&&Kk(t)?t:e}function Kk(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(!Hee.test(i)||o.length>0&&!Kee.test(o)&&!Jee.test(o)&&!Yee.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 rte(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||zee.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=jee(e);return n==null?r:{value:n,type:t}}return qee.includes(t)?Kf(e)?{value:e.trim(),type:t}:r:Yf(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&Kk(e)?{value:e.trim(),type:t}:r}function Rk(e){return e==="ContainsData"||e==="DoesNotContainData"}function Lk(e){return nte.has(e)}function kk(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function $k(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=ju[e.operator]??z.WorkflowConditionOperator.Equal,i=Gee(e,r),o=sb(r,n);if(e.source==="BusinessProcess"){let l=Fee(e,t);if(Rk(e.operator))return kk(l,n);let u=Wk(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[ya(e.value??"",u)]}}let a=op(e.field,t,r,i);if(Rk(e.operator))return kk(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=Lk(o)&&Lk(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[op(e.valueField,t,l,Wee(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[Hk(e.lookupValue)]}else if(e.valueType==="Clear")s=[ya(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[ip(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=rte(e.value??"",o);s=[ya(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function ite(){return ya(!0,z.WorkflowAttributeType.Boolean)}function ote(e,t,r){if(e.length===0)return null;let n=$k(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[$k(e[i],r)]}}return n}function np(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:tte(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==z.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=_k(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function ate(e){let t=bb[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=ba(e)?e.operand:e.left,i=ba(e)?[]:e.right??[],o=zk(n);if(o){let g=i[0];return{id:cr(),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"}:np(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:cr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function xk(e){if(!e||!tp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(ba(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...ate(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";tp(o.left)&&r(o.left,a),(o.right??[]).filter(tp).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 ip(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return op(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return Sk(i,n);if(o!=null)return o}return e==="Lookup"&&a?Hk(a):e==="Clear"?ya(null,s??z.WorkflowAttributeType.String):ya(t??"",z.WorkflowAttributeType.String)}function hb(e,t){return{propertyName:e,propertyValueExpr:t}}function Ys(e){return`Step_${e.value++}`}function fn(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 Fk(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):fn(t,r)}function ste(e){return e===Uk.StateCode.Activated?"Active":"Draft"}function lte(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 ute(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function Jk(e,t=1033){return new Qs({languageCode:t}).serialize(e)}function Yk(e){return new Qs().deserialize(e)}var Uk,z,Oee,bb,vb,qk,Vk,Gk,kee,$ee,Tk,Dk,Mee,qee,zee,Hee,Kee,Jee,Yee,Qee,Xee,Zee,nte,wb,Qs,Cb=k(()=>{"use strict";ib();Uk=Ee(Yi());tk();ob();lb();Hu();z=Ee(Jf());Oee=new Set(["__class"]);bb={};for(let e of Object.keys(ju))bb[ju[e]]=e;vb="23",qk="BpfProcess",Vk="ActiveStageCategory",Gk="SelectedStageCategory",kee="processid",$ee="stagecategory",Tk="processstage",Dk="stageid";Mee=new Set(["ActiveStage","SelectedStage","Stage"]);qee=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];zee=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];Hee=/^\d{4}-\d{2}-\d{2}$/,Kee=/^\d{2}:\d{2}$/,Jee=/^\d{2}:\d{2}:\d{2}$/,Yee=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Qee=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Xee=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Zee=/^(\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$/;nte=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);wb={setFieldValue:"Set Field Value",setDefaultValue:"Set Default Value",lockUnlock:"Lock/Unlock",setBusinessRequired:"Set Business Required",setVisibility:"Set Visibility",recommendation:"Recommendation",showErrorMessage:"Show Error Message",condition:"Condition"};Qs=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>wb[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??cr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ku(),argumentsArray:[],primaryEntityName:r?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:r?.category??"2",businessProcessType:r?.businessProcessType??"0",mode:r?.mode??"0",title:r?.title??t.name,formId:n,workflowEntityId:r?.workflowEntityId??t.ruleId??"",variables:r?.variables??[],inputs:r?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ys(this.stepCounter),stepLabels:{list:[]},specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:gb(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=mb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:Fk(n?.id,"ActionStep",this.idCounter),name:n?.name??Ys(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??cr(),uniqueName:n?.uniqueName??`id_${cr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=gb(this.entityName),n=t.stepName??Ys(this.stepCounter),i=t.stepLabels??Ku(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:fn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:fn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:fn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:fn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?z.FieldRequiredLevelTypes.Required:z.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode);return{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:fn("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:l,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:r,level:"RECOMMENDATION",actionSteps:u}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let r=t.stepName??Ys(this.stepCounter),n=fn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??ote(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ys(this.stepCounter):Ys(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?Fk(o.branchId,"ConditionBranchStep",this.idCounter):fn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:Ku(),conditionExpression:s??(a?ite():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Ku(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ku(),conditionExpression:void 0,steps:{list:t.map(r=>this.serializeBranchItem(r))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let r=t,n=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??cr():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:Ree(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:ute(r,i?.formId),status:ste(t.statecode),rootCondition:n,wfomRoot:i,...lte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Lee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=xk(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)??cr(),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,...Pk(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=xk(n.conditionExpression);return i.length===0&&!Pk(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||cr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...np(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=np(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=np(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==z.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var Qk=k(()=>{"use strict";});function mte(e){return typeof e=="object"&&e!==null?e:null}function Xs(e){let t=mte(e);if(!t)return!1;if(t.__class===fte){let r=t;return String(r.method)===pte?!0:Array.isArray(r.parameters)&&r.parameters.some(Xs)}if(t.__class===dte)return Xs(t.operand);if(t.__class===cte){let r=t;return Xs(r.left)||Array.isArray(r.right)&&r.right.some(Xs)}return!1}var cte,dte,fte,pte,Xk=k(()=>{"use strict";Qk();cte="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",dte="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",fte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",pte="23"});function Nb(e){return hte.has(e.type)}function Eb(e,t,r,n,i,o,a){let s=i.get(r);!s||!t1.has(s.attributeType)||n!=="Value"||a?.operator&&!ub(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 gte(e,t){let r=t.get(e.field);return!!r&&t1.has(r.attributeType)&&ub(e.operator)}function Ab(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Sb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Ks}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Ks}}}function Zk(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);zf(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 sp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(Nb(t))return!0}else if(sp(t))return!0;return!1}function _b(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=_b(r,t);if(n)return n}}return null}function yte(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 bte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||yte(e.rawConditionExpression))}function wte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||Xs(e.rawConditionExpression)}function Zs(e,t){for(let r=0;r<e.trueBranch.length;r++){let n=e.trueBranch[r];if(n.id===t)return{node:e,branch:"true",index:r};if(n.kind==="condition"){let i=Zs(n,t);if(i)return i}}for(let r=0;r<e.falseBranch.length;r++){let n=e.falseBranch[r];if(n.id===t)return{node:e,branch:"false",index:r};if(n.kind==="condition"){let i=Zs(n,t);if(i)return i}}return null}function Tb(e,t){return{...e,trueBranch:e1(e.trueBranch,t),falseBranch:e1(e.falseBranch,t)}}function e1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Tb(r,t):r)}function _o(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?_o(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?_o(n,t,r):n)}}function ap(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n)}}function r1(e,t,r,n){return _o(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Db(e){return e.length===1&&e[0].kind==="condition"}function Ete(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Db(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function Ate(e){return!!e&&Ete(e)<Cte}function Ste(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Db(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 n1(e,t,r){let n=Ste(e,t);return!n||!Ate(n)?e:_o(e,t,i=>i1(i,r))}function i1(e,t){if(Db(e.falseBranch))return{...e,falseBranch:[i1(e.falseBranch[0],t)]};let r=Ib(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function o1(e,t){let r=Zs(e,t);if(!r||r.branch!=="false")return e;let n=r.node.falseBranch[r.index];if(!n||n.kind!=="condition")return e;let i=n.falseBranch;return _o(e,r.node.id,o=>({...o,falseBranch:i}))}function a1(e,t,r){let n=Zs(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return _o(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 Ib(e){return{kind:"condition",id:cr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function s1(e,t){let r={kind:"action",id:cr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:cr(),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 l1(e){if(!e)return[];let t=[];return u1(e,t),[...new Set(t)]}function u1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?u1(r,t):"field"in r&&r.field&&t.push(r.field)})}function c1(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 f1(e,n,i,!0),r==="Entity"&&d1(e,n),sp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function d1(e,t){wte(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"&&d1(r,t)})}function f1(e,t,r,n=!1){let i=n&&bte(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?ga(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&&!gte(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&&!Js(a.expression)?t.push(s==="invalidDayCount"?Sb(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&&rk(r.get(a.field)?.attributeType)&&!Kf(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=ok(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&Yf(l)&&!ak(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:ab(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:ab(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(Ab(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)&&Eb(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"&&vte.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")f1(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&&!Xf(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:ga(a.expression);!a.rawExpression&&!Js(a.expression)&&t.push(s==="invalidDayCount"?Sb(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"&&!Ab(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&&(Eb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),Zk(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:ga(l.expression);!l.rawExpression&&!Js(l.expression)&&t.push(u==="invalidDayCount"?Sb(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"?Ab(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&&(Eb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),Zk(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var hte,t1,vte,Cte,Ob=k(()=>{"use strict";ib();Zy();Zf();Hu();Xk();lb();ob();hte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);t1=new Set(["Lookup","Customer","Owner"]);vte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Cte=10});var p1={};Hr(p1,{DAY_COUNT_MAX:()=>Ks,DAY_COUNT_MIN:()=>fb,DEFAULT_DESERIALIZE_LABELS:()=>wb,WorkflowJsonMapper:()=>Qs,addElseIfInTree:()=>n1,appendToBranch:()=>r1,areFieldKindsCompatible:()=>Xf,attributeTypeToWorkflowType:()=>gk,buildWorkflowEntity:()=>jL,collectUsedFields:()=>l1,createEmptyAction:()=>s1,createEmptyCondition:()=>Ib,deserializeWorkflowJson:()=>Yk,findNode:()=>_b,findParent:()=>Zs,getDefaultOperatorForFieldType:()=>dk,getExpressionModelIssue:()=>ga,getOperatorsForFieldType:()=>Qf,hasAnyTriggerGeneratingAction:()=>sp,isDayCountValid:()=>pb,isExpressionModelComplete:()=>Js,isOperatorCompatible:()=>fk,isTriggerGeneratingAction:()=>Nb,moveBranchItemInTree:()=>a1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>tb,processTriggerScopeFromScope:()=>eb,removeElseIfInTree:()=>o1,removeNodeFromTree:()=>Tb,serializeToWorkflowJson:()=>Jk,supportsClearForActionType:()=>zf,updateActionInTree:()=>ap,updateConditionInTree:()=>_o,validateBusinessRule:()=>c1});var m1=k(()=>{"use strict";Zy();HL();Cb();Cb();Ob();Ob();Zf();Hu();Hu();});var Pb=v(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});lp.cloneJson=void 0;function Nte(e){return JSON.parse(JSON.stringify(e))}lp.cloneJson=Nte});var _1=v(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.BUSINESS_RULE_NULL_GUID=To.businessRuleRegistration=To.BusinessRuleAdapter=void 0;var h1=dt(),Ju=(m1(),Fr(p1)),g1=Jr(),y1=Q(),_te=Pb(),ii=en(),Tte=Im(),Dte=dt(),Ite=Ho(),Ote=new Set(["ShowErrorMessage","Recommendation"]);function C1(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)?C1(n):Ote.has(String(n.type))):!1}function Pte(e){return E1((0,_te.cloneJson)(e))}function E1(e){var t,r;let n=i=>(i??[]).map(o=>Rte(o)?E1(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 Rte(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 Lte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new y1.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 y1.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 kte="00000000-0000-0000-0000-000000000000";To.BUSINESS_RULE_NULL_GUID=kte;var $te=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),xte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Fte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Mte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function kn(e,t){return e===void 0?t:{...e,...t}}var va=["kind","id","type","displayName","field","stepName","stepLabels"],b1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Ute={Recommendation:[...va,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...va,"lock"],ShowErrorMessage:[...va,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...va,...b1],SetDefaultValue:[...va,...b1],SetBusinessRequired:[...va,"required"],SetVisibility:[...va,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function A1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Rb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",A1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function S1(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 Bte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function qte(e){return kn(e.bag,{id:e.id,field:e.field,...Rb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Vte(e){let t=S1(e,Bte);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 v1(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 w1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Gte=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Wte=new Set,zte="INVALID_CLEAR_FOR_FIELD";function jte(e){let t=n=>{var i;return(0,ii.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,ii.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 up=class{toArtifact(t){let r=this.residualBag(t,xte),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 kn(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:r})}fromApiResponse(t){var r;let n=t??{},i={...(r=n.Entity)!==null&&r!==void 0?r:{},wfomJson:n.WfomJson},o=(0,Ju.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return C1(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,Ju.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Ite.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,h1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,s;let l={ruleId:(r=t.id)!==null&&r!==void 0?r:null,name:(n=t.name)!==null&&n!==void 0?n:"New business rule",description:(i=t.description)!==null&&i!==void 0?i:"",entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,Ju.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Pte(Lte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,h1.newId)()),u}assignMissingIds(t){return(0,Dte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,ii.isJsonObject)(n)?(N1(n,"/rootCondition",r),r):(r.push((0,ii.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,ii.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:jte(n.rootCondition),o;return r.length===0?o=Gte:r.some(a=>a.requiredLevel!==void 0)?o=Wte:o=new Set([zte]),(0,Ju.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,ii.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 S1(t,r)}buildWorkflowEntity(t,r){return(0,Ju.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Fte),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,Mte),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,Ute[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(Vte),...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",...v1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...v1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return w1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return kn(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 kn(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",A1(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(!$te.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Kte(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 kn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(qte),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return kn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return kn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return kn(t.bag,{...r,type:"SetFieldValue",...Rb(t)});case"SetDefaultValue":return kn(t.bag,{...r,type:"SetDefaultValue",...Rb(t)});case"SetBusinessRequired":return kn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return kn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return w1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};To.BusinessRuleAdapter=up;function N1(e,t,r){(0,ii.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,ii.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,ii.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?N1(o,`${t}/${n}/${a}`,r):Hte(o,`${t}/${n}/${a}`,r)})}function Hte(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,ii.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Kte(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Jte(){return{adapter:new up,api:Tte.businessRuleApi,publish:(e,t,r)=>(0,g1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,g1.boundEntityPublishScope)(t)}}To.businessRuleRegistration=Jte});var W1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.appRegistration=Do.AppAdapter=Do.HEADER_NAV_BOOLEAN_RULE=void 0;var Bi=en(),It=so(),Qu=uo(),Yte=Jr(),x1=Ud(),Lb=Od(),kb=lo(),Qte=dt(),Xte=se(),F1=Ho(),M1=Q(),U1=Rd();Object.defineProperty(Do,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return U1.HEADER_NAV_BOOLEAN_RULE}});var pp="7.0.0.0",T1=`<SiteMap IntroducedVersion="${pp}"></SiteMap>`,D1="/_imgs/imagestrips/transparent_spacer.gif",I1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",B1=["Entity","Url","DefaultDashboard","Page","GenPageId"],Yu="sitemapId",O1="sitemapName",Zte="sitemapNameUnique",P1="aiDescription",R1="[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}",ere=new RegExp(`^(?:\\{${R1}\\}|${R1})$`);function L1(e,t){if(!ere.test(e.trim()))throw new M1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function k1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new M1.ValidationError("app",t,[q1(e)]);return e}function q1(e){return(0,Bi.issue)("/headerAndNavigationRefresh",U1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function tre(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,Xte.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 rre(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 mp=class{constructor(t=F1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=cp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,It.emptyBag)()}}fromArtifact(t){(0,kb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,It.rebuildRaw)(i,(0,Qu.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,kb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,Qu.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:T1,T1),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:[[Yu,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[O1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Zte,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[P1,(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,kb.installDomShim)();let w=(0,Qu.serializeNode)(this.fromArtifact(t)),E=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?E.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let P=(s=t.bag)!==null&&s!==void 0?s:(0,It.emptyBag)();return{sitemapId:xb(P,Yu)||(t.sitemapId?L1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:xb(P,O1)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:xb(P,P1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Lb.HEADER_AND_NAVIGATION_REFRESH]:k1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Lb.APP_SETTING_ON:Lb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(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,Qte.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:L1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:k1(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(Mb):Array.isArray(r.areas)?r.areas.forEach(Mb):Array.isArray(r.groups)?Mb(r):Array.isArray(r.subAreas)?G1(r):"type"in r&&hp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Bi.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,Bi.isJsonObject)(i))return r.push((0,Bi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Bi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Bi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Bi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Bi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let E=tre(g);if(!E)return;let S=s.get(E);if(S===void 0){s.set(E,w);return}r.push((0,Bi.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,x1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,rre(t))}applyServerIdentity(t,r){let n=r[Yu];if(!n)return;t.bag||(t.bag=(0,It.emptyBag)());let i=t.bag.a.find(o=>o[0]===Yu);i?i[1]=n:t.bag.a.push([Yu,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=cp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(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}=cp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=cp(t,null),i=nre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:$b(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!==D1&&(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,It.emptyBag)(),l=dp(a)?[["IntroducedVersion",pp]]:[],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,It.mergeAttrs)(a.a,l),c:(0,It.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",pp]),t.icon!==void 0?a.push(["Icon",t.icon]):fp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Fb((0,It.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,It.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",pp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Fb((0,It.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,It.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),i=dp(n),o=ore(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>B1.includes(c));sre(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]):fp(o,"Icon",D1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",I1]):s.push("VectorIcon"):t.type==="GenPage"&&!ire(o,"VectorIcon")&&a.push(["VectorIcon",I1]);let u=Fb((0,It.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,It.mergeAttrs)(o,a,s),c:u}}};Do.AppAdapter=mp;function cp(e,t){let r=(0,Qu.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,It.rawFromNode)((0,Qu.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function $1(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 $b(e,t){var r;let n=$1(e,"Titles")[0];if(!n)return"";let o=$1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function nre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function dp(e){return e.a.length===0&&e.c.length===0}function ire(e,t){return e.some(([r])=>r===t)}function fp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function xb(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function ore(e,t){let r=are(t);return e.filter(([n])=>!B1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function are(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 sre(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 Fb(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]=lre(e[i],t,n),o}return r?[ure(t,n),...e]:e}function lre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&cre(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,It.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(V1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function ure(e,t){return{n:"Titles",a:[],c:[V1(e,t)]}}function V1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function cre(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function dre(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function hp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${dre(8)}`)}function Mb(e){var t;hp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])G1(r)}function G1(e){var t;hp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])hp(r,"subarea")}function fre(e=F1.DEFAULT_LCID){return{adapter:new mp(e),api:x1.appApi,languageSensitive:!0,publish:(t,r)=>(0,Yte.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Do.appRegistration=fre});var z1={};Hr(z1,{ActionType:()=>Bb,AppActionOrigin:()=>Kb,AppActionVisibilityType:()=>Hb,ButtonType:()=>Vb,CannotUpdateAppActionColumns:()=>pre,Context:()=>Wb,IconType:()=>qb,Location:()=>Gb,OnClickEventType:()=>jb,Scope:()=>zb,VisibilityType:()=>Ub});var Ub,Bb,qb,Vb,Gb,Wb,zb,jb,Hb,Kb,pre,j1=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Ub||(Ub={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Bb||(Bb={}));(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"})(Vb||(Vb={}));(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"})(Gb||(Gb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Wb||(Wb={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(zb||(zb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(jb||(jb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Hb||(Hb={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Kb||(Kb={}));pre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Z1=v(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.assertOneWritePerRow=Ot.commandApi=Ot.COMMAND_DUPLICATE_ROW_CODE=Ot.COMMAND_ROW_NOT_IN_BAR_CODE=Ot.COMMAND_TABLE_MISMATCH_CODE=void 0;var Jb=Lt(),Pr=ye(),qi=Q(),Rr=se();Ot.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Ot.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Ot.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var mre="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Yb(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Rr.odataPathLiteral)(t)}')${(0,Rr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Pr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Rr.normalizeGuid)(o,"entityMetadataId"):""}function Qb(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Rr.odataLiteral)(e)}'`}function Xu(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function H1(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new qi.SdkError(Ot.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 K1(e,t,r){let n=await Yb(e,t);if(r){let i=(0,Rr.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Xu(t))}return n}Ot.commandApi={async get(e,t){let r=t,n=await Yb(e,r),i=Qb(r,n),o=`/appactions${(0,Rr.odataQuery)([["$expand",mre],["$filter",i]])}`,a,s=await(0,Jb.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,Rr.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Pr.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=H1(n,r),o=await K1(e,i,n.entityMetadataId);return J1(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=H1(o,t),s=await K1(e,a,o.entityMetadataId);return J1(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Yb(e,t),n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Pr.deleteRecord)(e,"appactions",o.appactionid)}};async function J1(e,t,r,n,i){let o=r.entityMetadataId?(0,Rr.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await gre(e,t,r,o,n,i),s={};try{await bre(e,a,o,s)}catch(l){throw(0,qi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Xb(e){return e.replace(/[{}]/g,"").toLowerCase()}function X1(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=Xb(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new qi.SdkError(Ot.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.`)}}Ot.assertOneWritePerRow=X1;var hre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Y1(e,t){let r=hre[t].exec(e);return r?Xb(r[1]):void 0}async function gre(e,t,r,n,i,o){var a,s;X1(t,r);let l=vre(r.rows),u=new Set(l.map(f=>Xb(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Y1(m,"entities")===n))throw new qi.SdkError(Ot.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"}). `+Xu(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Y1(p,"appactions");if(h===void 0||!u.has(h))throw new qi.SdkError(Ot.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. `+Xu(t))}if(i&&f.exists){let h=(0,Rr.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Pr.isVersionToken)(g))throw Q1(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new qi.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,Rr.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Pr.isVersionToken)(p))throw Q1(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 yre(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new qi.SdkError(Ot.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. `+Xu(t))}return c}function Q1(e,t,r,n){return new qi.SdkError(Pr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Xu(e))}async function yre(e,t,r){let n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Rr.normalizeGuid)(a.appactionid,"appactionid"));return o}async function bre(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Pr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Pr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Pr.readEtag)(s)}else{let o=(0,Pr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Pr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Pr.readCreatedId)(l,"appactionid");u&&(n[(0,Rr.normalizeGuid)(u,"appactionid")]=(0,Pr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Pr.deleteRecord)(e,"appactions",i,o),delete n[i]}function vre(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 h$=v(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.commandRegistration=el.CommandAdapter=void 0;var lt=(j1(),Fr(z1)),e$=Jr(),bt=en(),n$=Z1(),i$=dt(),tl=se(),o$=Q(),tv="$ClientSvg:",rv=".svg",wre=2,Cre=1,Ere=1,a$="entityMetadataId",Are=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"]),gp=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 o$.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=Dre(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:Nre(g,f,c$(h),c)});return{id:c,entityLogicalName:c,commandBars:Tre(p),bag:{a:[[a$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(t),appActions:Zb(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Zb(r).map(l=>l.appactionid):[]),i=Zb(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?qre(l.row):m$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,n$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(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,i$.assignMissingIds)(t)}normalize(t){let r=Rre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,bt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,bt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>f$(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,bt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,bt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,bt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;vp(l.bag)||((0,bt.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."})),s$((0,bt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};el.CommandAdapter=gp;function vp(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function s$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;vp(n.bag)||(0,bt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,bt.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,bt.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,bt.isJsonObject)(n.action)?(0,bt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,bt.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,bt.childObjects)(n,"children",o,"control",r);s.length>0&&s$(s,`${o}/children`,r)})}function nv(e){return{a:Object.entries(e)}}function Sre(e){return Object.fromEntries(e.a)}function Zu(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function iv(e){let t=Zu(e.bag,a$);return typeof t=="string"?t:""}function Nre(e,t,r,n){var i,o;let a=[],s=[];for(let l of bp(e))l.type===lt.ButtonType.Group?a.push({id:u$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:bp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>yp(u,t,r,n)),bag:nv(l)}):s.push(yp(l,t,r,n));return s.length>0&&a.unshift({id:Bre(n,r),title:"",controls:s}),a}function ov(e){let t=e.bag?Zu(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function yp(e,t,r,n){var i,o,a,s,l;let u=u$(e.name,n),c={id:u,type:Ire(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:nv(e)},d=l$(e);d&&(c.icon=d);let f=_re(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 bp(m))if(g.type===lt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=nv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let E=[];for(let S of bp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let P=yp(S,t,r,n);p.push(P),E.push(ov(P))}h.push({id:b,bag:w,childIds:E})}else p.push(yp(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function l$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(tv)?e.fonticon.slice(tv.length)+rv:e.fonticon}function _re(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 t$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function bp(e){return[...e].sort((t,r)=>t$(t)-t$(r))}function Tre(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function u$(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 Dre(e){switch(e){case lt.Location.Form:case lt.Location.QuickForm:return"MainTab";case lt.Location.HomePageGrid:case lt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function c$(e){switch(e){case"MainTab":return lt.Location.Form;case"HomeTab":return lt.Location.HomePageGrid;default:return lt.Location.SubGridStandard}}function Ire(e){switch(e){case lt.ButtonType.Dropdown:return"FlyoutAnchor";case lt.ButtonType.Split:return"SplitButton";default:return"Button"}}function Ore(e){switch(e){case"FlyoutAnchor":return lt.ButtonType.Dropdown;case"SplitButton":return lt.ButtonType.Split;default:return lt.ButtonType.Standard}}function Pre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function d$(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 Zb(e,t=new Set){var r,n,i,o;let a=[],s=iv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=c$(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=>!d$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Pre(m)){let h=kre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])p$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function f$(e,t){if(!(0,bt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>f$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!vp(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,i$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Rre(e){let t=new Set,r=(o,...a)=>{if((0,bt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),vp(o.bag)?Zu(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,bt.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,bt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,bt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function p$(e,t,r,n,i,o,a,s=new Set){var l;let u=Lre(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=>!d$(h,s)),f=(h,g,b)=>{p$(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=>[ov(S),S])),g=new Set,b=0,w;for(let[S,P]of m.entries()){let L=P.id||(S===0?ev(u.appactionid):sv("flyout-group",`${u.appactionid}#${S}`)),I=r$(L,t,u.appactionid,n,i,P.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let O of P.childIds){let x=h.get(O);!x||g.has(O)||(g.add(O),f(x,D,b),b+=1)}}let E=w??ev(u.appactionid);for(let S of c){let P=ov(S);g.has(P)||(g.add(P),f(S,E,b),b+=1)}return}let p=e.flyoutGroupId||ev(u.appactionid);o.push(r$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Lre(e,t,r,n,i,o){let a=av(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=l$(s);return e.location!==void 0&&(s.location=e.location),s.type=Ore(e.type),s.buttonlabeltext=e.label,xre(s,e.icon,l),Mre(s,e.action),Fre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function kre(e,t,r,n,i){let o=av(e,t,r,n,i);return o.row.type=lt.ButtonType.Group,o.row.grouptitle=e.title,o}function r$(e,t,r,n,i,o){let a=av({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command flyout group id")})`,s.type=lt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function av(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Sre(e.bag),a=!0;let u=Zu(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Zu(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new o$.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=$re(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==lt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function $re(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:lt.Context.Entity,contextvalue:r.entityLogicalName,scope:lt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,tl.normalizeGuid)(n,"Command context entity metadata id")})`),i}function xre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,tl.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(rv)?tv+t.slice(0,t.length-rv.length):t,e.IconWebResourceId=null}function Fre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,tl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Cre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Ere)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Mre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=wre,t.webResourceId){let r=(0,tl.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${r})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function Ure(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 sv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Ure(`${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 ev(e){return sv("flyout-group",e)}function Bre(e,t){return sv("loose-group",`${e}|${t}`)}function m$(e){let t={...e};for(let r of Are)delete t[r];return t}function qre(e){let t=m$(e);for(let r of lt.CannotUpdateAppActionColumns)delete t[r];return t}function Vre(){return{adapter:new gp,api:n$.commandApi,publish:(e,t,r)=>(0,e$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,e$.boundEntityPublishScope)(t)}}el.commandRegistration=Vre});var y$=v(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.chartApi=void 0;var Gre=Lt(),Lr=ye(),wa=se(),g$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Wre="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";wp.chartApi={async get(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]);return{raw:(0,Lr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]),i=(0,Lr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,wa.odataQuery)([["$select",Wre],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,wa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Gre.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Lr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Lr.ensureSuccess)(await e.post(o,(0,Lr.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,Lr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Lr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,wa.normalizeGuid)(t,"id"),a=(0,Lr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Lr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Lr.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,Lr.readEtag)(l)}},delete(e,t){return(0,Lr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var k$=v(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.chartRegistration=nl.ChartAdapter=void 0;var lv=so(),b$=en(),oi=uo(),v$=Jr(),zre=y$(),uv=lo(),jre=dt(),Hre=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Kre=new Map(Hre.map(e=>[e.toLowerCase(),e]));function S$(e){var t;return e&&(t=Kre.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Jre(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Yre(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${rl(h.series.attribute)}" aggregate="${rl(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${rl(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${rl(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${rl(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,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="${rl(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var Cp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,uv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,oi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,oi.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:Ep(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:T$(d),categories:D$(d),presentation:N$(f),dataBag:u?(0,oi.projectElementBag)(d):void 0,presentationBag:c?(0,oi.projectElementBag)(f):void 0,rowBag:Qre(t.charttype,t.type)}}fromArtifact(t){(0,uv.installDomShim)();let{datadescription:r,presentationdescription:n}=Xre(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:w$(t.rowBag,"charttype"),type:w$(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,uv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,jre.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,b$.childObjects)(n,"series","","series",r),(0,b$.childObjects)(n,"categories","","category",r),r}};nl.ChartAdapter=Cp;function Qre(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 w$(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 Ep(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return S$(t[r].getAttribute("ChartType"));return"Column"}function N$(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 Ap(e){return e.getElementsByTagName("fetch")[0]}function _$(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 T$(e){let t=Ap(e);if(!t)return[];let r=_$(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=S$(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 D$(e){var t;let r=Ap(e);if(!r)return[];let n=_$(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 Xre(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!C$(e.dataBag)||!C$(e.presentationBag)){let c=Yre({...e,series:n,categories:i});return{datadescription:c,presentationdescription:yne(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=E$(e.dataBag,"datadefinition",o),s=E$(e.presentationBag,"Chart",o),l=e.chartType||Ep(s),u=T$(a);if(!cv(n,u)){let c=dv(a);Zre(o,a,n);let d=dv(a),f=d.length>0?d:n.map(()=>"");I$(o,s,f,c,l)}return cv(i,D$(a))||ene(o,a,i),e.chartType&&e.chartType!==Ep(s)&&R$(s,e.chartType),e.presentation&&!cv(e.presentation,N$(s))&&L$(s,e.presentation),{datadescription:(0,oi.serializeNode)(a),presentationdescription:(0,oi.serializeNode)(s)}}function C$(e){return!!e&&(e.c.length>0||e.a.length>0)}function I$(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 dv(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 E$(e,t,r){let n={n:t,a:(0,lv.mergeAttrs)(e.a,[]),c:(0,lv.spliceChildren)(e.c,[])};return(0,lv.rebuildRaw)(n,(0,oi.domEngine)(r),null)}function Zre(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,sne(n),r,une,{aliasPrefix:"aggregate_column",addRef:nne,removeRef:ane})}function ene(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,lne(n),r,cne,{aliasPrefix:"groupby_column",addRef:ine,removeRef:one})}function O$(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=dne(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),A$(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||rne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),A$(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),pne(m)}}function tne(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 rne(e,t){let r=tne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function P$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function nne(e,t,r){let n=P$(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 ine(e,t,r){let n=P$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function one(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 ane(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"&&!hne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function sne(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 lne(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 une(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function cne(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 dne(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 A$(e,t,r,n){n?fne(e,t,n).appendChild(r):t.appendChild(r)}function fne(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 pne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!mne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function mne(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 hne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function R$(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(!gne(r[i])){r[i].setAttribute("ChartType",t);return}}}function gne(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 L$(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 yne(e,t){let r=(0,oi.parseXmlRoot)(Jre(),"<Chart/>"),n=e.chartType||Ep(r);R$(r,n),e.presentation&&L$(r,e.presentation);let i=dv((0,oi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&I$(r.ownerDocument,r,i,i.slice(0,1),n),(0,oi.serializeNode)(r)}function cv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rl(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function bne(){return{adapter:new Cp,api:zre.chartApi,publish:(e,t,r)=>(0,v$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,v$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}nl.chartRegistration=bne});var M$=v(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.dashboardApi=Ca.dashboardEntity=void 0;var vne=Lt(),Io=ye(),il=se(),wne=mg(),$$=Xl();function x$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ca.dashboardEntity=x$;var F$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",Cne={select:F$,required:["name","type","objecttypecode","istabletenabled"]},Ene="formid,name,type,objecttypecode",Ane=0,Sne=10;Ca.dashboardApi={async get(e,t){let r=(0,il.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,il.odataQuery)([["$select",F$]]),i=(0,Io.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,$$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Io.readEtag)(i)}},async list(e,t){let r=[`(type eq ${Ane} or type eq ${Sne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,il.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,il.odataQuery)([["$select",Ene],["$filter",r.join(" and ")]])}`;return(await(0,vne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=x$(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Io.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Io.ensureSuccess)(await e.post(o,(0,Io.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Io.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Io.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,wne.patchSystemForm)(e,(0,il.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,Cne)},readContentThenToken(e,t){return Ca.dashboardApi.get(e,t)},async delete(e,t){let r=(0,il.normalizeGuid)(t,"id");return await(0,$$.assertSystemFormKind)(e,r,"dashboard"),(0,Io.deleteRecord)(e,"systemforms",r)}}});var Q$=v(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.dashboardRegistration=ai.TILE_CLASS_ID=ai.DashboardAdapter=void 0;var tc=so(),pn=uo(),fv=Jr(),ec=en(),W$=M$(),pv=lo(),Ea=dt(),z$=se(),j$=Ho(),Nne=Ny(),U$="0",mv="10",_ne=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"]]),Tne="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Np=class{constructor(t=j$.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,pv.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,pn.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:Dne(t.type),entityLogicalName:(a=(0,W$.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:Ine(l),components:B$(l,this.lcid),bag:(0,pn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,pv.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?mv:U$,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,Nne.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"?mv:U$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,pv.installDomShim)();let c=(0,pn.parseXmlRoot)(Vne(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Ea.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:B$(c,this.lcid),bag:(0,pn.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,Ea.newId)())}return t}validate(t){let r=[],n=(0,ec.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,ec.isJsonObject)(u)&&r.push((0,ec.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,ec.isJsonObject)(o.position)){let l=rc(o.position);i.has(l)?r.push((0,ec.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ai.DashboardAdapter=Np;function Dne(e){return String(e??"")===mv?"Interactive":"Standard"}function Ine(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 B$(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)=>{One(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function One(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Pne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Pne(e,t,r){var n,i;let o=J$((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=kne(a),u=$ne(s,l,a),c=Rne(a);return{id:a.getAttribute("id")||o,type:u,name:K$(e,r),classId:s,position:t,colspan:_p(e,"colspan",1),rowspan:_p(e,"rowspan",1),parameters:l,bag:(0,pn.projectElementBag)(e),...c?{icProperties:c}:{}}}function H$(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 Rne(e){let t=H$(e);return t?(0,pn.serializeNode)(t):void 0}function Lne(e,t,r){let n=H$(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,tc.rebuildRaw)((0,tc.rawFromNode)((0,pn.nodeLikeFromDom)(i)),(0,pn.domEngine)(e),null);n&&(0,pn.serializeNode)(n)===(0,pn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function K$(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 kne(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 $ne(e,t,r){var n;let i=_ne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Tne?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function _p(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 J$(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function xne(e,t){let r={n:"form",a:(0,tc.mergeAttrs)(e.bag.a,[]),c:(0,tc.spliceChildren)(e.bag.c,[])};return(0,tc.rebuildRaw)(r,(0,pn.domEngine)(t),null)}function q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=xne(e,r);return Une(r,n,e.components,t),Fne(r,n,e.components,t),(0,pn.serializeNode)(n)}function Fne(e,t,r,n){let i=Y$(t);for(let o of r)i.has(rc(o.position))||Mne(e,t,o,n)}function Mne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Gne(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||ai.TILE_CLASS_ID[r.type]||ai.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&V$(r.bag,"id")?String(V$(r.bag,"id")):Sp((0,Ea.newId)()),m=r.id?Sp(r.id):Sp((0,Ea.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],E=w?ae(w,"cell").reduce((x,K)=>x+_p(K,"colspan",1),0):0;(!w||E+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 P=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),P.appendChild(L),S.appendChild(P);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Sp(c));let D=e.createElement("parameters"),O=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(O)){let K=(0,z$.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=O[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function V$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Une(e,t,r,n){var i;let o=Y$(t),a=new Set(r.map(s=>rc(s.position)));for(let s of r){let l=o.get(rc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Bne(e,l,s.name,n),qne(e,u,s.parameters),G$(l,"colspan",s.colspan),G$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Lne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function Y$(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;J$((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(rc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function rc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Bne(e,t,r,n){if(r===K$(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 qne(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,z$.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function G$(e,t,r){_p(e,t,1)!==r&&e.setAttribute(t,String(r))}function Vne(e=2){let t=`{${(0,Ea.newId)()}}`,r=`{${(0,Ea.newId)()}}`,n=`{${(0,Ea.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>`}ai.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 Sp(e){return`{${e.replace(/[{}]/g,"")}}`}function Gne(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Wne(e=j$.DEFAULT_LCID){return{adapter:new Np(e),api:W$.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,fv.publishBoundEntity)(t,n):(0,fv.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,fv.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ai.dashboardRegistration=Wne});var gv=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.readEveryInOrder=kr.readInOrder=kr.plainRead=kr.resolveReadConcurrency=kr.MAX_READ_CONCURRENCY=void 0;var X$=Q();kr.MAX_READ_CONCURRENCY=8;function zne(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>kr.MAX_READ_CONCURRENCY)throw new X$.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${kr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}kr.resolveReadConcurrency=zne;var jne=e=>({ok:!0,value:e}),hv=e=>({ok:!1,error:e});function Hne(e){let t=(async()=>e())().then(jne,hv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}kr.plainRead=Hne;async function Z$(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new X$.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(hv);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:hv(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 Kne(e,t,r,n){return Z$(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}kr.readInOrder=Kne;function Jne(e,t,r,n){return Z$(e,t,r,n,"continue")}kr.readEveryInOrder=Jne});var gx=v(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});Dp.genPageApi=void 0;var Tp=Lt(),dx=Wl(),Be=ye(),ve=se(),$n=Dd(),Ye=Q(),fx=dt(),ex=gv();function Yne(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 si="uxagentprojects",Sa="uxagentprojectfiles",oc="agentconversationmessages",ac="uxagentprojectid",Ut="uxagentprojectfileid",Na="agentconversationmessageid",nc=`${ac},name`,Qne=`${Ut},filename,filetype`,px=2e8,mx=200000001,_a={"MSCRM.IncludeUnpublished":"true"},yv={};function Aa(e,t){return{"MSCRM.VersioningChangeset":e,..._a,...t}}async function wv(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{..._a}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function sc(e,t,r=_a){let n=`/${Sa}(${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=Yne(o);if(a)return{status:"available",data:(0,$n.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,$n.utf8ToBase64)(o)};throw new Ye.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 hx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Xne(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Ye.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=`/${Sa}(${t})/filecontent`,s=(0,$n.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Aa(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":hx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function ic(e,t,r=_a){let n=`/${Sa}`+(0,ve.odataQuery)([["$select",Qne],["$filter",`_${ac}_value eq ${t}`]]);return(await(0,Tp.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 bv(e,t){let r=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Tp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{..._a}})}async function tx(e,t){var r,n,i;let{row:o,etag:a}=await wv(e,si,t,nc),s=new Map;for(let{row:l,etag:u}of await ic(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Ut])!==null&&r!==void 0?r:""),Ut),{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 rx(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 Ye.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 Ye.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 Cv(e){let t=(0,$n.base64ToUtf8)(e);return(0,$n.utf8ToBase64)(t)===(0,$n.bytesToBase64)((0,$n.base64ToBytes)(e))?t:void 0}function Zne(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?{[Na]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${si}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?px:mx}}async function eie(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=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Na} eq ${f}`).join(" or ")]]),u=await(0,Tp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{..._a}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Na])!==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"?px:mx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Ye.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 vv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${si}`,body:(0,Be.withClientMintedId)({name:t.name},ac,e),headers:Aa(n)};case"createRow":return{method:"POST",path:`/${Sa}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${ac}@odata.bind`]:`/${si}(${e})`},Ut,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Aa(n)};case"renameRow":return{method:"PATCH",path:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Aa(n,{"If-Match":"*"})};case"content":{let i=Cv(t.data);if(i===void 0)throw new Ye.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:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Aa(n,{"x-ms-file-name":hx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Sa}(${t.fileId})`,headers:Aa(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${si}(${e})`,body:{name:t.name},headers:Aa(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${oc}`,body:Zne(e,t.turn,r,n)};default:{let i=t;throw new Ye.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function nx(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Cv(r.data)!==void 0)}async function ix(e,t,r,n,i){await(0,dx.postChangeSet)(e,r.map(o=>vv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function ox(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 Xne(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=vv(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=>vv(t,l,n,i));if(e.supportsAtomicBatch)await(0,dx.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 ax(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await tx(e,t),c=new Map;for(let E of r)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,ve.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[E,S]of c){let P=u.rows.get(E);P&&(P.filename!==S.name||P.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${P.filename}' (type ${P.filetype})`)}for(let E of r){if(E.kind!=="content")continue;let S=await sc(e,(0,ve.normalizeGuid)(E.file.id,"file id")),P=(0,$n.bytesToBase64)((0,$n.base64ToBytes)(E.data));(S.status!=="available"||S.data!==P)&&d.push(S.status==="available"?`file '${E.file.name}' holds ${(0,$n.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,$n.base64ToBytes)(P).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(r.filter(E=>E.kind==="content").map(E=>(0,ve.normalizeGuid)(E.file.id,"file id")));for(let[E,S]of c)!f.has(E)&&(await sc(e,E)).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 tx(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(E=>{var S,P;return((S=u.rows.get(E))===null||S===void 0?void 0:S.etag)!==((P=m.rows.get(E))===null||P===void 0?void 0:P.etag)}),g=p.length!==i.size||p.some(E=>!i.has(E)),b={},w=[];for(let[E,S]of m.rows){let P=c.has(E)||!o?S.etag:(s=o.get(E))!==null&&s!==void 0?s:null;b[E]=P,P!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(E=>!E)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):tie({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(E=>`Generative page '${t}' was written, but its file '${E}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function sx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await wv(e,si,o,nc),l=await ic(e,o),u={},c=[];if(n>1)await(0,ex.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Ut])!==null&&m!==void 0?m:""),Ut);return(0,ex.plainRead)(async()=>({fileId:p,content:await sc(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[Ut])!==null&&i!==void 0?i:""),Ut);u[p]=m;let h=await sc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await bv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Dp.genPageApi={get(e,t,r){return sx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return sx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${si}(${i})`+(0,ve.odataQuery)([["$select",nc]]),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 ic(e,i,yv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Ut])!==null&&n!==void 0?n:""),Ut);l[w]=b,u.push({...g,content:await sc(e,w,yv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Ut])}@${String(w)}`).sort().join("|"),f=()=>new Ye.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 ic(e,i,yv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Ye.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=`/${si}`+(0,ve.odataQuery)([["$select",nc]]);return(await(0,Tp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{..._a}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[ac])!==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,fx.newId)(),a=rx(o,i,void 0);cx(e,a),ux(e,o,i);let s=lx(),l=[],u=!0;nx(e,a)?await ix(e,o,a,i,s):{warnings:l,turnRecorded:u}=await ox(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 ax(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 Ye.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 eie(e,l,s);ux(e,l,u);let c=await ic(e,l),{row:d,etag:f}=await wv(e,si,l,nc);if(n&&f&&n!==f)throw new Ye.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 Ye.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,O;return[(0,ve.normalizeGuid)(String((D=I[Ut])!==null&&D!==void 0?D:""),Ut),{filename:String((O=I.filename)!==null&&O!==void 0?O:""),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 Ye.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 Ye.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 Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}));for(let[I,D]of Object.entries(i)){let O=I.toLowerCase();if(!p.has(O))continue;let x=b.get(O);if(!D||!x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${O}' before writing: ${D?"the server did not return its current token":"no baseline token was recorded"}. A file row accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);if(D!==x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${O}' 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=rx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(cx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}))};let E=lx(),S=[],P=!0;nx(e,w)?await ix(e,l,w,u,E):{warnings:S,turnRecorded:P}=await ox(e,l,w,u,E);let L=await ax(e,l,w,u,h,b,S);return P?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await bv(e,n);await(0,Be.deleteRecord)(e,si,n);let o=new Set(i.map(l=>{var u;return String((u=l[Na])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await bv(e,n)){let u=String((r=l[Na])!==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,oc,l)}catch(u){u instanceof Ye.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Ye.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 ${oc} rows regarding '${n}'.`)}};function lx(){return`uxagentproject_${(0,fx.newId)()}`}function tie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function ux(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 Ye.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 cx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Ye.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=>Cv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Ye.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 Lx=v(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.genPageRegistration=al.GenPageAdapter=void 0;var rie=gx(),nie=Jr(),Ie=en(),Lp=dt(),kp=Dd(),iie=se(),Ta=Q(),Tx=Tg(),Ev=Km(),Oo=2e8,Dx=200000001,Gi={source:{name:"src/pages/page.tsx",fileType:Oo},output:{name:"src/pages/page.compiled",fileType:Dx},config:{name:"config.json",fileType:Oo},prompt:{name:"firstPrompt.json",fileType:Oo}},Ix=Object.keys(Gi),oie=["dataSources","model","connectorBindings","actionBindings"],aie=["userMessage","agentMessage"],yx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},lie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Ox(e,t,r){let n=(0,iie.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 Ip(e,t){return Ox(e,sie[t],"id")}function uie(e,t){let r=Ox(e,lie,"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 bx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Lp.newId)()}function Vi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ol(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Op(e){return JSON.parse(JSON.stringify(e))}function cie(e){let t=Vi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function uc(e){if(!e||e.status!=="available")return;let t=(0,kp.base64ToUtf8)(e.data);return(0,kp.utf8ToBase64)(t)===e.data?t:void 0}function Px(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ol((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,Tx.isLoadableGenPageOutput)(r)}function die(e,t){var r;try{return Px(e,t,uc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Pp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function vx(e,t){if(t===Oo&&e.includes("page.tsx"))return"source";if(t===Dx&&e.includes(".compiled"))return"output";if(t===Oo&&e===Gi.config.name)return"config";if(t===Oo&&e===Gi.prompt.name)return"prompt"}function wx(e){let t=e.toLowerCase();return Ix.some(r=>Gi[r].name.toLowerCase()===t)}function Av(e){return Object.fromEntries(e)}function Rx(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),Av(i)}function Cx(e){var t,r,n;return Rx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},oie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Ex(e){var t,r;return Rx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},aie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function Ax(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=Av(n)),!0}function Sx(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=Av(n)),!0}function cc(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 fie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function Nx(e){return cc(e)?[]:fie.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 _x(){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 Rp(e){return{status:"available",data:(0,kp.utf8ToBase64)(e)}}function lc(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 $p=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Vi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,E;let S=Vi(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((E=S.filetype)!==null&&E!==void 0?E:Oo),content:cie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let E=Vi(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((b=E.message)!==null&&b!==void 0?b:""),createdOn:String((w=E.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=vx(g.name,g.fileType);b?((s.has(b)||g.name!==Gi[b].name)&&(u=!1),s.set(b,g)):(wx(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(lc(n,i));let c=lc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=uc(f.content);if(g===void 0)return a(lc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Pp(uc(p.content));if(!g||!Ax(c,d,g))return a(lc(n,i))}let h=s.get("prompt");if(h){let g=Pp(uc(h.content));if(!g||!Sx(c,d,g))return a(lc(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&&!ol((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Ta.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=Nx(t);if(b.length>0)throw new Ta.ValidationError("genPage",t.id,b);let w=[],E=r===void 0,S=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(cc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=ge=>{var je;return(je=I[ge])!==null&&je!==void 0?je:Ip(S.id,ge)},O=(ge,je,de)=>{w.push({id:D(ge),name:Gi[ge].name,fileType:Gi[ge].fileType,content:je,unchanged:de})};if(S.source!==void 0){O("source",Rp(S.source),!E&&r?.source===S.source&&I.source!==void 0);let ge=uc((l=S.bag)===null||l===void 0?void 0:l.output);Px(S,r,ge)?O("output",{status:"retain"},!0):O("output",Rp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Ta.ValidationError("genPage",S.id,[_x()]);if(I.output!==void 0){if(!E&&!ol((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Ta.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.")]);O("output",{status:"retain"},!0)}}let x=Cx(S),K=!E&&r!==void 0&&ol(Cx(r),x);(E||I.config!==void 0||!K)&&O("config",Rp(JSON.stringify(x)),K&&I.config!==void 0);let Re=Ex(S),qt=!E&&r!==void 0&&ol(Ex(r),Re);(I.prompt!==void 0||Object.keys(Re).length>0&&!qt)&&O("prompt",Rp(JSON.stringify(Re)),qt&&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(O=>O.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ol(D,I)})}let P=[];if(S.newTurn){let I=S.newTurn.id,D=O=>I?{id:uie(I,O)}:{};P.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&P.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...P.length>0?{messages:P,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:Op(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!cc(t)&&!t.newTurn)return t;let u=Op(t);if(delete u.newTurn,!cc(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=Ix.find(p=>Gi[p].name===d.name&&Gi[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,kp.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,Ax(u,c,(s=Pp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Sx(u,c,(l=Pp(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"&&yx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Lp.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 Ta.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Ta.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,Ev.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Ev.buildGenPageLegacyEnums)(a):void 0,d=(0,Tx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Ta.ValidationError("genPage",t.id,d.diagnostics.map(pie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=die(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=bx(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:bx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Oo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=Op(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=Op(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:Ip(i,"source"),output:Ip(i,"output"),config:Ip(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Lp.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,Lp.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&&Vi(Vi(n.bag).rows).source!==void 0&&r.push(_x()),r.push(...Nx(t)),n.newTurn!==void 0){let s=Vi(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"||!yx.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"||!Ev.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=cc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Vi(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&&(wx(f)||vx(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=Vi(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}};al.GenPageAdapter=$p;function pie(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 mie(){return{adapter:new $p,api:rie.genPageApi,publish:(e,t)=>(0,nie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}al.genPageRegistration=mie});var $x=v(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});Fp.reconcileBpfSecurityRoles=void 0;var kx=Lt(),Nv=Q(),xp=ye(),dc=se(),hie="Global",Sv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function gie(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,dc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,xp.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 Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,kx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Sv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Sv[u]);if(c){let d=(0,dc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function yie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,xp.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 Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,kx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,dc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function bie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:hie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function vie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function wie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await gie(e,t.toLowerCase());for(let s of r){let l=(0,dc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new Nv.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Sv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,dc.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 yie(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 bie(e,l,f);for(let p of m)await vie(e,l,p)}}Fp.reconcileBpfSecurityRoles=wie});var Kx=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.bpfApi=void 0;var dr=Yi(),xx=Wl(),Cie=Lt(),Qe=Q(),ut=ye(),mn=se(),Eie=$x(),Aie=_m(),fc=Dm(),Sie={"Content-Type":"application/json",Accept:"application/json"},Tv={...Sie,Prefer:"return=representation"},Nie=`category eq ${dr.WorkflowCategory.BusinessProcessFlow} and type eq ${dr.WorkflowTypeCode.Definition} and businessprocesstype eq ${dr.BusinessProcessType.BusinessFlow}`,_ie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Tie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Die=["xaml","name","description","processorder"];async function _v(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,Eie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Iv(e,t,r){let n={statecode:dr.StateCode.Activated,statuscode:dr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await Hx(e,i,n,r,null);try{return(0,ut.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?zx(s):s}}var Wx=new WeakSet;function zx(e){return typeof e=="object"&&e!==null&&Wx.add(e),e}function jx(e){return typeof e=="object"&&e!==null&&Wx.has(e)}function Fx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||ut.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function Hx(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ut.resendWhile)(ut.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...Tv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ut.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?zx(s):s}}async function Mx(e,t,r){return(0,ut.readEtag)(await Iv(e,t,r))}function Ux(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. `+Mp(e))}async function pc(e,t){var r;let n=`/workflows(${t})${(0,mn.odataQuery)([["$select","statecode"]])}`,i=(0,ut.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 Dv(e,t,r,n,i=null){if((n??await pc(e,t))!==dr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:dr.StateCode.Draft,statuscode:dr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await Hx(e,a,o,r,i))}catch(c){return await Bx(e,t,c,jx(c))}if(ut.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Bx(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,ut.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ut.readEtag)(u)}}async function Bx(e,t,r,n){let i;try{i=await pc(e,t)}catch{i=void 0}if(i===dr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===dr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===dr.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 Iie(e,t){let r=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,r,null),"restored"}catch{return Ov(e,r)}}async function Oie(e,t,r){let n=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,n,r),"restored"}catch(i){return i instanceof Qe.SdkError&&i.code===ut.VERSION_CONFLICT_CODE?"changed":Ov(e,n)}}async function Ov(e,t){try{let r=await pc(e,t);return r===dr.StateCode.Activated?"restored":r===dr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function qx(e,t,r,n){return r?{outcome:await Oie(e,t,r),attempted:!0}:n?{outcome:await Ov(e,(0,mn.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await Iie(e,t),attempted:!0}}function Pie(e,t){let r=new Qe.SdkError(fc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,fc.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 Vx(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 Rie(e,t){try{return await pc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Lie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Dv(e,t,r),o=n?i:r;if(o)return await(0,fc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Rie(e,t)}function Mp(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 Gx(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. ${Mp(e)}`)}function kie(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.) ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function $ie(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. ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function xie(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 Pv(e){let t={};for(let r of Die)e[r]!==void 0&&(t[r]=e[r]);return t}var Fie=["name,processorder","description,name,processorder"];function Mie(e){let{xaml:t,...r}=Pv(e);return typeof t=="string"&&Fie.includes(Object.keys(r).sort().join(","))}async function Uie(e,t,r,n){let{xaml:i,...o}=Pv(r),[,a]=await(0,xx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,mn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ut.readEtag)((0,xx.partResponse)(a))}Up.bpfApi={async get(e,t){let n=`/workflows(${(0,mn.normalizeGuid)(t,"id")})${(0,mn.odataQuery)([["$select",Tie]])}`,i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.readEtag)(i)}},async list(e,t){let r=[Nie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,mn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,mn.odataQuery)([["$select",_ie],["$filter",r.join(" and ")]])}`;return(await(0,Cie.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,mn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ut.ensureSuccess)(await e.post(i,r.record,{headers:Tv}),e.apiUrl(i)),a=(0,ut.readEtag)(o);if(!a)throw Gx(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 Mx(e,n,a)),await _v(e,r)}catch(l){let u=await Lie(e,n,s);throw u==="survived"?kie(n,l):u==="unknown"?$ie(n,l):l instanceof Qe.SdkError&&l.code===ut.VERSION_CONFLICT_CODE?xie(n,l):l}if(!s)throw Gx(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,mn.normalizeGuid)(t,"id"),a=(0,ut.requireEtag)(n,"bpf",o),s=await pc(e,o);if(s===dr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Mie(i.record)){let m=await Uie(e,o,i.record,a);return await _v(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await Dv(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw Ux(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ut.ensureSuccess)(await e.patch(p,Pv(i.record),{headers:{...Tv,"If-Match":m}}),e.apiUrl(p))}catch(b){throw Fx(b)&&(d=null),b}let g=(0,ut.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw Ux(o,"definition write");try{g=await Mx(e,o,g)}catch(b){throw Fx(b)&&(d=null),b}f=!0}return await _v(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await qx(e,o,d,jx(m));if(p!=="restored")throw Vx(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,mn.normalizeGuid)(t,"id"),n=await(0,Aie.assertWorkflowKind)(e,r,dr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Dv(e,r,null,void 0,n);try{await(0,fc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,fc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await qx(e,r,o,!1);if(s==="changed")throw Pie(r,a);if(s!=="restored")throw Vx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var PF=v(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});ll.bpfRegistration=ll.BpfAdapter=void 0;var Bp=Yi(),Bie=Kx(),Rv=so(),Da=uo(),sF=lo(),zr=en(),$r=dt(),xn=Q(),qie=100,Lv='<?xml version="1.0" encoding="utf-16"?>',Jx=1033,lF="mxswa:Workflow",Vie="mxswa:ActivityReference.Properties",Gie="mcwo:StepLabel",Wie="mcwb:Control",Yx="mcwb:Control.ControlDisplayName",uF="mcwb:Control.DataFieldName",cF="DataFieldName",Qx="ControlDisplayName",dF="Literal",Vp="x:Null",Xx="x:String",kv="x:Key",$v="DisplayName",Wp="Activities",zie="StepLabels",fF="StageId",pF="StageCategory",mF="NextStageId",hF="ProcessStepId",qp="IsProcessRequired",gF="EntityComposite",yF="StageComposite",bF="StepComposite";function mc(e){return(0,zr.isJsonObject)(e)?e:{}}function ui(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 Ia(e,t){var r;return(r=ui(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function di(e){return Ia(e,Vie)}function fr(e,t){var r;return(r=ui(e).find(n=>n.getAttribute(kv)===t))!==null&&r!==void 0?r:null}function sl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function vF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function hc(e){var t;let r=(t=e.getAttribute($v))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function wF(e,t){var r;let n=(r=e.getAttribute($v))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute($v,i>=0?n.slice(0,i+2)+t:t)}function CF(e,t){let r=fr(e,zie),n=Ia(r,Gie);n&&n.setAttribute("Description",t)}function jie(e){let t=fr(e,pF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:Number(r)}function Hie(e){let t=fr(e,mF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:r}function EF(e){let t=AF(e);if(!t)return;let r=NF(t,cF,uF);return r===""?void 0:r}function xv(e,t){let r=ui(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ui(n))r.push(i)}return null}function AF(e){let t=fr(di(e),Wp);return t?xv(t,Wie):null}function SF(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 NF(e,t,r){var n;return SF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":Xie(e,r)}function Zx(e,t,r,n){if(SF(e,t)){e.setAttribute(t,n);return}if(Ia(e,r)){Kie(e,r,n);return}throw new xn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Kie(e,t,r){let n=Ia(e,t),i=n?xv(n,dF):null;if(!i)throw new xn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function _F(e){return hc(e)}function zp(e){let t=Ia(e,lF),r=[];for(let n of ui(t).filter(i=>sl(i,gF))){let i=fr(di(n),Wp);for(let o of ui(i).filter(a=>sl(a,yF)))r.push({el:o,entity:_F(n)})}return r}function Fv(e){let t=fr(di(e),Wp);return ui(t).filter(r=>sl(r,bF))}function Jie(e){let t=di(e),r=ci(fr(t,qp)).trim().toLowerCase(),n=EF(e),i={id:ci(fr(t,hF)),name:hc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Yie(e,t){let r=di(e),n=jie(r),i=Hie(r),o={id:ci(fr(r,fF)),name:hc(e),entityLogicalName:t,steps:Fv(e).map(Jie)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Qie(e){return zp(e).map(({el:t,entity:r})=>Yie(t,r))}function li(e){return new xn.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 Xie(e,t){var r;let n=Ia(e,t),i=n?xv(n,dF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Mv(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(Mv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function TF(e){return fr(di(e),Wp)}function Zie(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,$r.newId)(),{body:a}=jp(Uv(i,(0,$r.newId)(),t.id,o));return Mv(e,zp((0,Da.parseXmlRoot)(a,"<Activity/>"))[0].el)}function eoe(e,t){let{body:r}=jp(Uv("account",(0,$r.newId)(),(0,$r.newId)(),t.id));return Mv(e,Fv(zp((0,Da.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function DF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function IF(e,t,r,n){let i=fr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw li(`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!==Vp&&ci(i).trim()!==""){let s=t.createElement(Vp);s.setAttribute(kv,r),o.replaceChild(s,i)}return}if(i.tagName===Xx){ci(i).trim()!==n&&vF(i,t,n);return}let a=t.createElement(Xx);a.setAttribute(kv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function toe(e,t,r){IF(e,t,pF,r===void 0?void 0:String(r))}function roe(e,t,r){IF(e,t,mF,r)}function OF(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 eF(e){return ci(fr(di(e),fF))}function tF(e){return ci(fr(di(e),hF))}function rF(e,t,r){var n,i,o,a;let s=di(e);r.name!==hc(e)&&(wF(e,r.name),CF(s,r.name));let l=ci(fr(s,qp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=fr(s,qp);if(!u)throw li(`setting '${qp}' on a step whose xaml does not expose that slot`);vF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=EF(e))!==null&&o!==void 0?o:"")){let u=AF(e);if(!u)throw new xn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";Zx(u,cF,uF,c),c!==""&&NF(u,Qx,Yx)===""&&Zx(u,Qx,Yx,c)}}function nF(e,t,r,n){var i;let o=di(e);if(!o)throw new xn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==hc(e)&&(wF(e,r.name),CF(o,r.name)),toe(o,t,r.category),roe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw li("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw li("stage actions or conditional branching");let a=TF(e);if(!a)throw new xn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new xn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Fv(e);if(OF(l,s.map(d=>d.id),tF)){l.forEach((d,f)=>rF(d,t,s[f]));return}let u=new Map(l.map(d=>[tF(d),d]));if(ui(a).some(d=>!sl(d,bF)))throw li("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:eoe(t,d)});DF(a,c),c.forEach((d,f)=>rF(d,t,s[f]))}function noe(e,t,r){let n=Ia(e,lF);if(!n)throw new xn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw li("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new xn.InvalidArgumentError("a BPF must have at least one stage");let i=zp(e),o=i.map(f=>f.el);if(OF(o,r.stages.map(f=>f.id),eF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw li(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);nF(f,t,h,h.nextStageId)});return}let a=ui(n).filter(f=>sl(f,gF));if(a.length!==1)throw li("adding, removing or reordering stages on a multi-table process");let s=a[0],l=_F(s),u=TF(s);if(!u)throw new xn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ui(u).some(f=>!sl(f,yF)))throw li("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 li(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[eF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Zie(t,f,l)});DF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;nF(f,t,r.stages[m],p)})}function jp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function ioe(e){var t,r,n,i,o,a;(0,sF.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,Rv.mergeAttrs)(s.a,[]),c:(0,Rv.spliceChildren)(s.c,[])};return{root:(0,Rv.rebuildRaw)(m,(0,Da.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Lv,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=Uv(e.entityLogicalName,(0,$r.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,$r.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,$r.newId)()),{body:d}=jp(c);return{root:(0,Da.parseXmlRoot)(d,"<Activity/>"),prolog:Lv,eol:"lf"}}function ooe(e){let{root:t,prolog:r,eol:n}=ioe(e);noe(t,t.ownerDocument,e);let i=(0,Da.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r+`)),r+i}function aoe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Gp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,sF.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}=jp(o),u=(0,Da.parseXmlRoot)(l,"<Activity/>");a.stages=Qie(u),a.bag={xaml:(0,Da.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,$r.newId)(),name:t.name,uniquename:aoe(t),primaryentity:t.entityLogicalName,xaml:ooe(t),category:Bp.WorkflowCategory.BusinessProcessFlow,type:Bp.WorkflowTypeCode.Definition,businessprocesstype:Bp.BusinessProcessType.BusinessFlow,scope:Bp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:qie};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 xn.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(oF):[oF({id:(0,$r.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,$r.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=mc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,$r.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,zr.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,zr.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=mc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,zr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,zr.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,zr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,zr.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 mc(h).id=="string"?h.id.trim():"";w===""?r.push((0,zr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,zr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!iF(i,d.branch.nextStageId)&&r.push((0,zr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!iF(i,d.nextStageId)&&r.push((0,zr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,zr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=soe(i);return s>=0&&r.push((0,zr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};ll.BpfAdapter=Gp;function soe(e){let t=new Map(e.map(r=>[mc(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 iF(e,t){return e.some(r=>mc(r).id===t)}function oF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(aF):[aF({id:(0,$r.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 aF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 Uv(e,t,r,n){return`${Lv}<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="${Jx}" /></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="${Jx}" /></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 loe(){return{adapter:new Gp,api:Bie.bpfApi,languageSensitive:!0}}ll.bpfRegistration=loe});var RF=v(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});Hp.buildRegistrations=void 0;var uoe=SL(),coe=WL(),doe=_1(),foe=W1(),poe=h$(),moe=k$(),hoe=Q$(),goe=Lx(),yoe=PF();function boe(e){let t=new Map;return t.set("form",(0,uoe.formRegistration)(e)),t.set("view",(0,coe.viewRegistration)()),t.set("businessRule",(0,doe.businessRuleRegistration)()),t.set("app",(0,foe.appRegistration)(e)),t.set("command",(0,poe.commandRegistration)()),t.set("chart",(0,moe.chartRegistration)()),t.set("dashboard",(0,hoe.dashboardRegistration)(e)),t.set("genPage",(0,goe.genPageRegistration)()),t.set("bpf",(0,yoe.bpfRegistration)()),t}Hp.buildRegistrations=boe});var jF=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 Wi=Lt(),hn=ye(),qe=se(),LF=dt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var UF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},voe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>UF[e]===t).map(([e])=>e)),woe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Bv(e){return woe[e]}var Kp=1e6;function Coe(e,t){let r=Bv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Kp} (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>Kp?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(Kp).length||Number(s)>Kp?n():s}}return n()}function Eoe(e,t){let r=Bv(t);return r?e===r.enabled:e!=="0"}async function Aoe(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,Wi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function Soe(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 kF=new WeakMap;async function Noe(e,t){var r,n;let i=kF.get(e);if(i||(i=new Map,kF.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,Wi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function _oe(e,t,r){var n,i;let o=await Noe(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,Wi.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 Toe=4,Doe=500,$F=20,xF=3e4;function Ioe(e){if(e===void 0)return Toe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${$F}; got ${e}.`);return Math.min($F,Math.max(1,Math.floor(e)))}function Ooe(e){if(e===void 0)return Doe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${xF}; got ${e}.`);return Math.min(xF,Math.max(0,Math.floor(e)))}async function Poe(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 _oe(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 Jp(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 BF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Bv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Jp(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,hn.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=Jp;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,hn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=qF;async function Roe(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Jp(e,i,t);r[n]={enabled:BF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Roe;async function Loe(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=Ioe(n.verifyAttempts),a=Ooe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=UF[p];g&&s.push({feature:p,setting:g,requestedValue:Coe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await Soe(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 Aoe(e,t)),c),f=new Map,m=async p=>{if(voe.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Jp(e,h);f.set(h,{enabled:BF(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 Poe(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 E=Eoe(g,p)?await m(p):void 0;E&&!E.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 '${E.setting}' reads '${E.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=Loe;var VF="GptPowerPrompt",koe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function GF(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=GF;async function $oe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,hn.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,Wi.describeMalformedValue)(o)}`);return o}function qv(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,Wi.describeMalformedValue)(i)}`);return i}async function WF(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${VF}'`],["$top",1]])}`,n=(0,hn.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,Wi.describeMalformedValue)(i)}`);let o=qv(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,Wi.describeMalformedValue)(a)}`)}function zF(e){return`${e} row summary`}async function xoe(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,hn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await WF(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===zF(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Foe(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,hn.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,Wi.describeMalformedValue)(s)}`);let l=qv(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 $oe(e,t.entityLogicalName),c=await WF(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 '${VF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,LF.newId)(),f=(0,LF.newId)(),m=JSON.stringify(GF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:zF(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:koe,RunConfiguration:""};(0,hn.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,hn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,hn.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=Foe;async function Moe(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,hn.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,Wi.describeMalformedValue)(a)}`);let s=qv(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 xoe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await FF(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 (${MF(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 FF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Boe);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"} (${MF(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=Moe;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 Uoe="0x8004f01f";function Boe(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()===Uoe}function qoe(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 FF(e,t,r,n=()=>!1){let i;try{let o=await(0,hn.resendWhile)(qoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,hn.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 MF(e){return e instanceof Error?e.message:String(e)}});var JF=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.findArtifact=ul.resolveArtifact=void 0;var Bt=se(),zi=Td(),Voe=Ud(),Goe=Lt(),Woe=ye(),HF=Q();async function KF(e,t,r){let n="/uxagentprojects"+(0,Bt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Bt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Goe.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function zoe(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Voe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Bt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Woe.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,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.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,zi.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Bt.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,zi.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Bt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Bt.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,zi.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Bt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Bt.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,zi.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Bt.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,zi.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Bt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return KF(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}ul.resolveArtifact=zoe;async function joe(e,t,r){var n,i,o,a,s,l;let u=(0,Bt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Bt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,zi.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await KF(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new HF.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=Hoe(t,u,c,r),f=t!=="app",m=await(0,zi.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new HF.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}ul.findArtifact=joe;function Hoe(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,Bt.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 QF=v(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});Qp.seedRecordGraph=void 0;var YF=Td(),Koe=cd(),Yp=se(),Joe=Q();async function Yoe(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,Koe.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let O=D.parentEntity.toLowerCase(),x=(s=d(O))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Joe.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,Yp.assertODataName)(await u(O),`entity set for parent '${D.parentEntity}'`),Re=(0,Yp.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Re})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Yp.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Yp.odataLiteral)(x)}'`).join(" or "),O=await(0,YF.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of O??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],E=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let O=D.toLowerCase(),x=E.get(O);if(x!==void 0)return x;let K=w.push(L)-1;return E.set(O,K),K}return w.push(L)-1}),P=w.length?await(0,YF.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):P[S[I]]})}return{createdIds:c}}Qp.seedRecordGraph=Yoe});var sM=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.getEntityPrivileges=Zt.addEntityPrivilegesToRole=Zt.deleteSecurityRole=Zt.createPersonaRole=Zt.createSecurityRole=Zt.SDK_ROLE_MARKER=void 0;var Fn=ye(),Pt=se(),jr=Q(),Xp={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Gv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},XF={user:1,businessUnit:2,parentChild:3,organization:4},Vv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Zt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Qoe(e){return Object.prototype.hasOwnProperty.call(Xp,e)?Xp[e]:void 0}function Xoe(e){return Object.prototype.hasOwnProperty.call(Gv,e)}var ZF=new WeakMap,eM=new WeakMap;async function nM(e,t){var r,n;(0,Pt.assertODataName)(t,"entity logical name");let i=ZF.get(e);i||(i=new Map,ZF.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Pt.odataPathLiteral)(t)}')${(0,Pt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Fn.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 jr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Zoe(e){var t,r,n;let i=eM.get(e);if(i)return i;let o=`/businessunits${(0,Pt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Fn.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 jr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Pt.normalizeGuid)(l,"businessUnitId");return eM.set(e,u),u}async function iM(e,t){var r;let n=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=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Xoe(o))throw new jr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await nM(e,i.entity);for(let s of i.access){let l=Qoe(s);if(!l)throw new jr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new jr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Vv[o];if(u[c]===!1)throw new jr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Pt.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 jr.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=XF[o]>XF[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 eae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Gv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Fn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function tM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Pt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Fn.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 tae(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,Pt.normalizeGuid)(l,"teamId");if(!await tM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Fn.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,Pt.normalizeGuid)(l,"userId");if(!await tM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Fn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function rM(e,t,r){var n,i;let o=`/roles${(0,Pt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Pt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Fn.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:"")===Zt.SDK_ROLE_MARKER};if(l.some(d=>!u(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(l.length>1)throw new jr.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,Pt.normalizeGuid)(c,"roleId"):void 0}function rae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Pt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Pt.normalizeGuid)(n,"userId"))}}function oM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function aM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new jr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Pt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Zoe(e),a=await iM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=rae(t.assignTo),l=await rM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Zt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Fn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Pt.normalizeGuid)((0,Fn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await rM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await eae(e,l,a,u);let c=await tae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:oM(a),assignedTeams:c.teams,assignedUsers:c.users}}Zt.createSecurityRole=aM;async function nae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.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:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return aM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Zt.createPersonaRole=nae;async function iae(e,t){let n=`/roles(${(0,Pt.normalizeGuid)(t,"roleId")})`;(0,Fn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Zt.deleteSecurityRole=iae;async function oae(e,t,r){let n=(0,Pt.normalizeGuid)(t,"roleId");if(r.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 iM(e,r),o={Privileges:i.map(s=>({Depth:Gv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Fn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),oM(i)}Zt.addEntityPrivilegesToRole=oae;var aae=new Map(Object.keys(Xp).map(e=>[Xp[e],e]));async function sae(e,t){return(await nM(e,t)).map(n=>{let i=Object.keys(Vv).filter(a=>n[Vv[a]]!==!1),o=aae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}Zt.getEntityPrivileges=sae});var SM=v(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.createMakerSdk=mr.MakerSdk=mr.PUSH_NOT_ATTEMPTED_CODE=mr.ALREADY_EXISTS_CODE=void 0;var lM=Im(),uM=Jr(),Z=Q(),gn=$a(),lae=DC(),wM=$C(),cl=qC(),uae=Pm(),cae=lE(),dl=dE(),dae=NE(),fae=PE(),pae=lA(),cM=iS(),Rt=cd(),Wv=vg(),dM=hN(),Zp=Xl(),ji=Td(),em=AN(),fl=Od(),mae=Rd(),er=wg(),hae=Tg(),gae=$g(),fM=Dg(),yae=RF(),tm=dt(),bae=Ho(),fi=Pb(),yn=xm(),zv=gv(),vae=3e5,pr=ye(),Oa=se(),pl=jF(),pM=JF(),wae=QF(),Cae=Hy(),gc=sM(),CM=Symbol("cds-maker-sdk.committedWrite");function Eae(e){return typeof e=="object"&&e!==null&&(e[CM]=!0),e}function Aae(e){return typeof e=="object"&&e!==null&&e[CM]===!0}var Sae={fileConcurrency:1},jv="SOLUTION_COMPONENT_UNCLASSIFIED",Nae=2,_ae=4,Tae="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 mM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Tae}:{}}}function hM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Po(t)}}function gM(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,pr.nowIso)(),isDirty:!1}}var Dae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function Iae(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,Oa.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 Oae(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 wM.WorkspaceManager(Rae,e.instanceUrl,(0,uae.assertStorageContract)(t))}mr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Pae="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";mr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Rae="<injected workspaceStorage>",rm=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,zv.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:bae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:vae,this.compiler={load:(0,hae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Oae(t),this.versions=new cl.VersionManager(this.workspace),this.dataverse=new cae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new pae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,yae.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,yn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,pr.nowIso)()},b)}return(0,fi.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:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.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,fi.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,er.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(mM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(gM(a,o,s))}catch(a){i.push(hM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,pr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,zv.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(mM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(gM(a.type,o,s))}catch(a){n.push(hM(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,Sae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,zv.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,dl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,dae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,dl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,fae.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,dl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Rt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Rt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Wv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Wv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Rt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Rt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Rt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Rt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Rt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Rt.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,Oa.xmlText)(t)}</entity></entities></importexportxml>`;(0,pr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Rt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Rt.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,Rt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Rt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Rt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,gc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,gc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,gc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,gc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,gc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,ji.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,ji.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,ji.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,ji.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,ji.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,ji.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,ji.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,wae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,pM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,pM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,gae.deleteAppCascade)(this.dataverse,t,r),i=(0,Oa.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,ji.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,ji.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,em.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,em.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,em.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,em.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,fl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,fl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:mae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,fl.setAppSetting)(this.dataverse,t,fl.HEADER_AND_NAVIGATION_REFRESH,r?fl.APP_SETTING_ON:fl.APP_SETTING_OFF)}getSolution(t){return(0,er.getSolution)(this.dataverse,t)}createPublisher(t){return(0,er.createPublisher)(this.dataverse,t)}createSolution(t){return(0,er.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,er.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,er.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,er.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,er.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,er.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,er.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,er.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,wM.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,yn.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=gn.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,lae.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=gn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Hi(s)&&Hi(i)?{...s,...i}:i;return gn.JsonPointer.set(a,n,(0,fi.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=gn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Hi(l)||!Hi(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,fi.cloneJson)(i[f]),p=(0,tm.isValueMapKey)(f)||(0,tm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Hi(h)?this.assignMissingIds(t,h):h):Hi(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))gn.JsonPointer.set(s,gn.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,tm.pointerTouchesValueMap)(n)?(0,fi.cloneJson)(i):this.assignMissingIds(t,(0,fi.cloneJson)(i)),c=xae(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=gn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=gn.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");gn.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),vM(c);let f=gn.JsonPointer.resolve(l,bM(n));return Array.isArray(f)&&f!==c&&vM(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(gn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return gn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,bM(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,pl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,pl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,pl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,pl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,pl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,pl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Cae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,uM.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&&Aae(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,fi.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=Iae(a),f;if(d)try{await(0,uM.publishXml)(this.dataverse,d)}catch(p){f=Po(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||!Dae.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,yn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Po(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,pr.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||!kae(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,yn.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,pr.isVersionToken)(o)||!EM(a,t.heldSiblings)||!AM(a)||!(o!==t.heldEtag||!(0,yn.deepEqual)(a??void 0,t.heldSiblings))||!(0,yn.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,pr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Po(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,yn.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,yn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,pr.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,Oa.normalizeGuid)(r,"id")})${(0,Oa.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:Po(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,yn.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,yn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Po(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),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,dl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg: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 O=await this.createWithMintedId(m,d,f,g,p);if("adopted"in O)return await this.persistAdoption(d,f,p,O.adopted);w=O.written}b=!0;let E=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),E=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,P=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,E,P.artifact,h&&E===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,yn.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,E,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,E,{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:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(P.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},E===f?h:void 0),{type:d,id:E,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var O;let x=(O=m.publishScope)===null||O===void 0?void 0:O.call(m,E,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let E=(0,Z.readPartialTokens)(w);if(E&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},P={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(P).length>0?{siblingEtags:P}:{}},h)}if(w instanceof Z.SdkError&&w.code===mr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===lM.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===lM.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===pr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,fM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Eae(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==cl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${cl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Wv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,dM.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(mr.ALREADY_EXISTS_CODE,Hv(r,n,u)+(this.createRecovery==="adoptExact"?` ${yM(Pae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==pr.VERSION_CONFLICT_CODE||(0,fM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,dM.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(mr.ALREADY_EXISTS_CODE,`${Hv(r,n)} ${yM(l.refused)}`)}throw new Z.SdkError(mr.ALREADY_EXISTS_CODE,Hv(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,yn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=dl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(O=>O.entityLogicalName===L).map(O=>O.fieldName);try{let O=await(0,dl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(O.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,O,x;return(O=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&O!==void 0?O:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,E=!((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),P=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:$ae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...E!==void 0?{baseLanguageCode:E}:{},...P?{pcf:P}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,cM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,cM.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(mr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,tm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case er.SolutionComponentType.SavedQuery:return"view";case er.SolutionComponentType.SavedQueryVisualization:return"chart";case er.SolutionComponentType.AppModule:return"app";case er.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case er.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,Zp.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(jv,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Zp.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,Oa.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,Oa.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,pr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,Zp.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(jv,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Nae)return"businessRule";if(a===_ae){let s=(0,Zp.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(jv,`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}};mr.MakerSdk=rm;function Lae(e){return new rm(e)}mr.createMakerSdk=Lae;function Po(e){return e instanceof Error?e:new Error(String(e))}function EM(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 AM(e){return Object.values(e??{}).every(pr.isVersionToken)}function kae(e,t){return EM(e,t)&&AM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function yM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Hv(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 $ae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function vM(e){e.length===0||!e.every(t=>Hi(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function xae(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=>Hi(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Hi(n)&&n.id===t.after);return r<0?e.length:r+1}});var NM=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.ARTIFACT_TYPES=void 0;nm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var TM=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0})});var IM=v(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0})});var PM=v(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0})});var LM=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0})});var $M=v(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0})});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(ce=>{"use strict";var Fae=ce&&ce.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ge=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Fae(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Mae=SM();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Mae.createMakerSdk}});Ge(NM(),ce);Ge(TM(),ce);Ge(IM(),ce);Ge(PM(),ce);Ge(LM(),ce);Ge($M(),ce);Ge(FM(),ce);Ge(UM(),ce);Ge(qM(),ce);Ge(GM(),ce);Ge(zM(),ce);Ge(HM(),ce);Ge(JM(),ce);Ge(QM(),ce);Ge(ZM(),ce);Ge(Rd(),ce);Ge(tU(),ce);Ge(nU(),ce);Ge(oU(),ce);Ge(sU(),ce);Ge(uU(),ce);Ge(dU(),ce);Ge(pU(),ce);Ge(Q(),ce);var mU=Al();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return mU.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return mU.projectConnectorOperationSchema}})});var Jv=v(pi=>{"use strict";var Uae=pi&&pi.__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]})),Bae=pi&&pi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),bU=pi&&pi.__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)&&Uae(t,e,r);return Bae(t,e),t};Object.defineProperty(pi,"__esModule",{value:!0});pi.NodeFileSystemStorage=void 0;var vt=bU(require("fs")),tr=bU(require("path")),gU=Q(),yU=Rm();async function vU(e){let t;try{t=await vt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await vt.promises.unlink(e)}catch{await vt.promises.rmdir(e)}return}if(!t.isDirectory()){await vt.promises.unlink(e);return}for(let r of await vt.promises.readdir(e))await vU(tr.join(e,r));await vt.promises.rmdir(e)}var Kv=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(tr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!vt.existsSync(r);){n.unshift(tr.basename(r));let i=tr.dirname(r);if(i===r)return tr.resolve(t);r=i}return tr.resolve(vt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=tr.resolve(this.root),i=tr.resolve(t);if(i!==n&&!i.startsWith(n+tr.sep))throw new gU.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):tr.resolve(this.realPathThroughNearestAncestor(tr.dirname(i)),tr.basename(i));if(a!==o&&!a.startsWith(o+tr.sep))throw new gU.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!vt.existsSync(r))return null;try{return await(0,yU.retryTransientIoAsync)(()=>vt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=tr.dirname(n);await vt.promises.mkdir(i,{recursive:!0});let o=tr.join(i,`.${tr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await vt.promises.writeFile(o,r,"utf8"),await(0,yU.retryTransientIoAsync)(()=>vt.promises.rename(o,n))}catch(a){try{vt.existsSync(o)&&await vt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);vt.existsSync(r)&&await vt.promises.unlink(r)}async deleteByPrefix(t){await vU(this.pathFor(t,!1))}async ensureContainer(t){await vt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return vt.existsSync(this.pathFor(t))}};pi.NodeFileSystemStorage=Kv});var wU=v(xr=>{"use strict";var qae=xr&&xr.__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]})),Vae=xr&&xr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Gae=xr&&xr.__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 Vae(t,e),t};Object.defineProperty(xr,"__esModule",{value:!0});xr.loadNodeTypeScript=xr.createNodeWorkspaceStorage=xr.NodeFileSystemStorage=void 0;var Wae=Jv(),zae=Jv();Object.defineProperty(xr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return zae.NodeFileSystemStorage}});function jae(e){return new Wae.NodeFileSystemStorage(e)}xr.createNodeWorkspaceStorage=jae;async function Hae(){return await Promise.resolve().then(()=>Gae(require("typescript")))}xr.loadNodeTypeScript=Hae});var Ki={};module.exports=Fr(Ki);Ji(Ki,Ee(hU()),module.exports);Ji(Ki,Ee(wU()),module.exports);diff --git a/plugins/pcf/scripts/verify-pcf.js b/plugins/pcf/scripts/verify-pcf.jsindex bf10bba69..ba2f81aac 100644--- a/plugins/pcf/scripts/verify-pcf.js+++ b/plugins/pcf/scripts/verify-pcf.js@@ -3,6 +3,7 @@const path = require('node:path');const { parseArgs, validateFlags, readJsonArg } = require('./lib/dataverse-auth.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const {makePcfSdk,findCustomControl,@@ -44,6 +45,7 @@ const CLIENTS_HINT = 'allowed values: web,phone,tablet';const FORM_TYPE_CODES = Object.freeze({ main: 2, 'quick-create': 7, 'quick-view': 6, card: 11, other: 100 });function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`${USAGE}\n${message}\n`);process.exit(1);}@@ -271,6 +273,9 @@ function errorMessage(err) {}function writeResult(ok, payload) {+ // The process exits right after printing the result, which grows with the bindings an intent names: blocking writes put the whole+ // text in the pipe first (on Linux and macOS a pipe's writes are queued, and process.exit does not wait for them — lib/output-redaction.js).+ makeWritesBlocking(process.stdout, process.stderr);if (ok) {process.stdout.write(JSON.stringify(payload) + '\n');process.exit(0);diff --git a/plugins/pcf/scripts/write-pcf-plan.js b/plugins/pcf/scripts/write-pcf-plan.jsindex c60f1b72d..cb08131ab 100644--- a/plugins/pcf/scripts/write-pcf-plan.js+++ b/plugins/pcf/scripts/write-pcf-plan.js@@ -6,6 +6,7 @@ const path = require('node:path');const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');const { parseManifest } = require('./lib/pcf-manifest.js');const { validateIntent, lintBindingIntent, renderPlanMarkdown } = require('./lib/pcf-intent.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');const USAGE = 'Usage: node scripts/write-pcf-plan.js --intent @pcf-intent.json [--manifest ControlManifest.Input.xml] [--out pcf-plan.md]';@@ -36,6 +37,7 @@ function runMain() {needValue: ['intent', 'manifest', 'out'],});if (flagError) {+ makeWritesBlocking(process.stdout, process.stderr);process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);process.exit(1);}diff --git a/scripts/validate-plugin-copies.js b/scripts/validate-plugin-copies.jsindex ef2af0384..ec532d889 100644--- a/scripts/validate-plugin-copies.js+++ b/scripts/validate-plugin-copies.js@@ -25,6 +25,7 @@ const COPY_SETS = [verbatim: [['scripts/lib/process-runner.js', 'scripts/lib/process-runner.js'],['scripts/lib/sdk-http-client.js', 'scripts/lib/sdk-http-client.js'],+ ['scripts/lib/output-redaction.js', 'scripts/lib/output-redaction.js'],['scripts/lib/odata.js', 'scripts/lib/odata.js'],['scripts/lib/source-literals.js', 'scripts/lib/source-literals.js'],['scripts/lib/interaction-mode.js', 'scripts/lib/interaction-mode.js'],diff --git a/shared/telemetry/tests/emit-spawn.test.js b/shared/telemetry/tests/emit-spawn.test.jsindex 385b60d69..21df404e2 100644--- a/shared/telemetry/tests/emit-spawn.test.js+++ b/shared/telemetry/tests/emit-spawn.test.js@@ -6,7 +6,12 @@ const fs = require("node:fs");const os = require("node:os");const path = require("node:path");+const childProcess = require("node:child_process");+const { fireAndForget } = require("../lib/emit-spawn");+const { telemetryOptOutEnvVarName } = require("../lib/user-config");++const EMIT_SPAWN = require.resolve("../lib/emit-spawn");function mkTmp() {return fs.mkdtempSync(path.join(os.tmpdir(), "ppskills-spawn-"));@@ -22,14 +27,169 @@ const sampleEvent = {},};-test("fireAndForget returns synchronously (<100 ms)", () => {- const start = Date.now();- fireAndForget(sampleEvent, {+// What the dispatcher is started with is what makes dispatch non-blocking, and it can be read without starting one:+// a recorder stands in for child_process.spawn. emit-spawn takes `spawn` from child_process when it loads, so the+// recorder is in place only while a private copy of the module loads; it is put back, and the copy dropped from+// the module cache, straight away, so no other test sees either.+// throwOnSpawn spawn() throws, as it does when the executable cannot be started+// throwOnWrite writing the event throws, as it does when the dispatcher has already exited+function loadWithRecordedSpawn({ throwOnSpawn = false, throwOnWrite = false } = {}) {+ const calls = [];+ const realSpawn = childProcess.spawn;+ childProcess.spawn = (command, args, options) => {+ if (throwOnSpawn) throw new Error("spawn EAGAIN");+ const child = {+ written: [],+ ended: false,+ unrefs: 0,+ stdin: {+ write(chunk) {+ if (throwOnWrite) throw new Error("write EPIPE");+ child.written.push(String(chunk));+ },+ end() {+ child.ended = true;+ },+ },+ unref() {+ child.unrefs += 1;+ },+ };+ calls.push({ command, args, options, child });+ return child;+ };+ delete require.cache[EMIT_SPAWN];+ try {+ return { fireAndForget: require("../lib/emit-spawn").fireAndForget, calls };+ } finally {+ childProcess.spawn = realSpawn;+ delete require.cache[EMIT_SPAWN];+ }+}++// Sets environment variables for the duration of `fn` and puts every one back, whether it was set before or not.+function withEnv(vars, fn) {+ const before = {};+ for (const [name, value] of Object.entries(vars)) {+ before[name] = process.env[name];+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ try {+ return fn();+ } finally {+ for (const [name, value] of Object.entries(before)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ }+}++// An earlier version of this test asserted that fireAndForget returns in under 100 ms. How long a spawn takes is+// the machine's, not the code's: a call that took 14-80 ms on an idle machine took up to 611 ms on a busy one, and+// the bound failed under suite load with nothing having regressed. What keeps a caller from ever waiting on the+// dispatcher's network POST is how the dispatcher is started, so that is what is pinned: the caller holds on to+// nothing the dispatcher does, and a POST that hangs cannot hold the caller.+test("fireAndForget hands the event to a detached dispatcher and returns without waiting for it", () => {+ const { fireAndForget: dispatch, calls } = loadWithRecordedSpawn();+ const returned = dispatch(sampleEvent, {iKey: "real-ikey",collectorUrl: "https://example.invalid/",});- const elapsed = Date.now() - start;- assert.ok(elapsed < 100, `expected <100ms, got ${elapsed}ms`);++ assert.equal(returned, undefined, "there is no promise for the caller to wait on");+ assert.equal(calls.length, 1, "exactly one dispatcher is started");+ const { command, args, options, child } = calls[0];+ assert.equal(command, process.execPath);+ assert.deepEqual(args.map((a) => path.basename(a)), ["emit-dispatcher.js"]);+ assert.equal(options.detached, true, "the dispatcher outlives the caller");+ assert.deepEqual(+ options.stdio,+ ["pipe", "ignore", "ignore"],+ "a pipe only to hand over the event; nothing the dispatcher prints is ever read"+ );+ assert.deepEqual(child.written, [JSON.stringify(sampleEvent)], "the whole event is handed over before the call returns");+ assert.equal(child.ended, true, "and the dispatcher is told that it is complete");+ assert.equal(child.unrefs, 1, "the caller's event loop does not wait for the dispatcher");+});++test("dispatch never breaks the caller: a dispatcher that cannot start, or has already exited, is ignored", () => {+ const unstartable = loadWithRecordedSpawn({ throwOnSpawn: true });+ assert.doesNotThrow(() => unstartable.fireAndForget(sampleEvent, {}));++ const gone = loadWithRecordedSpawn({ throwOnWrite: true });+ assert.doesNotThrow(() => gone.fireAndForget(sampleEvent, {}));+ assert.equal(gone.calls[0].child.unrefs, 1, "a dispatcher that exited first is still released, so it cannot hold the caller open");+});++// The dispatcher is the only process that talks to the collector, and it starts from the caller's environment,+// which can hold anything: cloud credentials, tokens, a preload for the caller's own Node. It gets a short list.+test("the dispatcher is started with a minimal environment: the caller's secrets never reach it", () => {+ const secrets = {+ AZURE_CLIENT_SECRET: "client-secret-value",+ GITHUB_TOKEN: "github-token-value",+ MY_PRIVATE_TOKEN: "private-token-value",+ // A preload the caller set for itself must not run inside the dispatcher.+ NODE_OPTIONS: "--require ./caller-preload.js",+ };+ withEnv({ ...secrets, POWER_PLATFORM_SKILLS_IKEY_JSON: undefined }, () => {+ const { fireAndForget: dispatch, calls } = loadWithRecordedSpawn();+ dispatch(sampleEvent, {+ iKey: "ikey-value",+ collectorUrl: "https://collector.invalid/",+ configDir: "/config-dir",+ fakeProbe: "/probe.json",+ cloud: "Public",+ ikeyJsonPath: "/plugin/ikey.json",+ });+ const env = calls[0].options.env;++ assert.deepEqual(+ Object.keys(env).sort(),+ [+ "APPDATA",+ "HOME",+ "PATH",+ "POWER_PLATFORM_SKILLS_CLOUD",+ "POWER_PLATFORM_SKILLS_COLLECTOR",+ "POWER_PLATFORM_SKILLS_CONFIG_DIR",+ "POWER_PLATFORM_SKILLS_FAKE_HTTPS",+ "POWER_PLATFORM_SKILLS_IKEY",+ "POWER_PLATFORM_SKILLS_IKEY_JSON",+ "SystemRoot",+ "USERPROFILE",+ ],+ "only the variables the dispatcher needs; adding one is a privacy decision, so it changes this list on purpose"+ );+ for (const [name, value] of Object.entries(secrets)) {+ assert.ok(!(name in env), `${name} must not be passed on`);+ assert.ok(!Object.values(env).includes(value), `the value of ${name} must not be passed on under another name`);+ }+ // What the dispatcher does need arrives as given.+ assert.equal(env.POWER_PLATFORM_SKILLS_IKEY, "ikey-value");+ assert.equal(env.POWER_PLATFORM_SKILLS_COLLECTOR, "https://collector.invalid/");+ assert.equal(env.POWER_PLATFORM_SKILLS_CONFIG_DIR, "/config-dir");+ assert.equal(env.POWER_PLATFORM_SKILLS_FAKE_HTTPS, "/probe.json");+ assert.equal(env.POWER_PLATFORM_SKILLS_CLOUD, "Public");+ assert.equal(env.POWER_PLATFORM_SKILLS_IKEY_JSON, "/plugin/ikey.json");+ });+});++test("only the event's own plugin opt-out reaches the dispatcher, and only when it is set", () => {+ const powerPages = telemetryOptOutEnvVarName("power-pages");+ const modelApps = telemetryOptOutEnvVarName("model-apps");+ // Whatever else the machine or the CI job has set, `vars` decides which of the two is set here.+ const forwarded = (pluginName, vars) =>+ withEnv(vars, () => {+ const { fireAndForget: dispatch, calls } = loadWithRecordedSpawn();+ dispatch({ name: "X", data: { pluginName } }, {});+ return Object.keys(calls[0].options.env).filter((name) => /^POWER_PLATFORM_SKILLS_TELEMETRY_.+_OPTOUT$/.test(name));+ });++ assert.deepEqual(forwarded("power-pages", { [powerPages]: "1", [modelApps]: "1" }), [powerPages], "not another plugin's opt-out");+ assert.deepEqual(forwarded("model-apps", { [powerPages]: "1", [modelApps]: "1" }), [modelApps]);+ assert.deepEqual(forwarded("power-pages", { [powerPages]: undefined, [modelApps]: "1" }), [], "a plugin that has not opted out passes nothing");+ assert.deepEqual(forwarded(undefined, { [powerPages]: "1", [modelApps]: "1" }), [], "an event that names no plugin passes none");});test("dispatcher child receives the event and writes the probe", async () => {